xstate 5.0.0-beta.26 → 5.0.0-beta.28

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 (71) hide show
  1. package/README.md +9 -7
  2. package/actions/dist/xstate-actions.cjs.js +14 -18
  3. package/actions/dist/xstate-actions.cjs.mjs +0 -6
  4. package/actions/dist/xstate-actions.development.cjs.js +14 -18
  5. package/actions/dist/xstate-actions.development.cjs.mjs +0 -6
  6. package/actions/dist/xstate-actions.development.esm.js +3 -1
  7. package/actions/dist/xstate-actions.esm.js +3 -1
  8. package/actions/dist/xstate-actions.umd.min.js +1 -1
  9. package/actions/dist/xstate-actions.umd.min.js.map +1 -1
  10. package/actors/dist/xstate-actors.cjs.js +439 -14
  11. package/actors/dist/xstate-actors.cjs.mjs +0 -5
  12. package/actors/dist/xstate-actors.development.cjs.js +439 -14
  13. package/actors/dist/xstate-actors.development.cjs.mjs +0 -5
  14. package/actors/dist/xstate-actors.development.esm.js +435 -1
  15. package/actors/dist/xstate-actors.esm.js +435 -1
  16. package/actors/dist/xstate-actors.umd.min.js +1 -1
  17. package/actors/dist/xstate-actors.umd.min.js.map +1 -1
  18. package/dist/declarations/src/Machine.d.ts +4 -3
  19. package/dist/declarations/src/State.d.ts +1 -1
  20. package/dist/declarations/src/StateNode.d.ts +3 -12
  21. package/dist/declarations/src/actions/assign.d.ts +11 -11
  22. package/dist/declarations/src/actions/cancel.d.ts +5 -12
  23. package/dist/declarations/src/actions/choose.d.ts +9 -7
  24. package/dist/declarations/src/actions/log.d.ts +5 -20
  25. package/dist/declarations/src/actions/pure.d.ts +11 -9
  26. package/dist/declarations/src/actions/raise.d.ts +6 -5
  27. package/dist/declarations/src/actions/send.d.ts +7 -12
  28. package/dist/declarations/src/actions/stop.d.ts +5 -12
  29. package/dist/declarations/src/actions.d.ts +8 -42
  30. package/dist/declarations/src/actors/index.d.ts +2 -22
  31. package/dist/declarations/src/actors/promise.d.ts +2 -1
  32. package/dist/declarations/src/constants.d.ts +8 -0
  33. package/dist/declarations/src/guards.d.ts +2 -2
  34. package/dist/declarations/src/index.d.ts +11 -18
  35. package/dist/declarations/src/spawn.d.ts +25 -0
  36. package/dist/declarations/src/stateUtils.d.ts +1 -1
  37. package/dist/declarations/src/typegenTypes.d.ts +5 -5
  38. package/dist/declarations/src/types.d.ts +81 -108
  39. package/dist/declarations/src/utils.d.ts +2 -3
  40. package/dist/interpreter-672794ae.cjs.js +792 -0
  41. package/dist/interpreter-a1432c7d.development.cjs.js +800 -0
  42. package/dist/interpreter-a77bb0ec.development.esm.js +765 -0
  43. package/dist/interpreter-b5203bcb.esm.js +757 -0
  44. package/dist/raise-436a57a2.cjs.js +1458 -0
  45. package/dist/raise-74b72ca5.development.cjs.js +1498 -0
  46. package/dist/raise-a60c9290.development.esm.js +1468 -0
  47. package/dist/raise-b9c9a234.esm.js +1428 -0
  48. package/dist/send-35e1a689.cjs.js +349 -0
  49. package/dist/send-4192e7bc.esm.js +339 -0
  50. package/dist/send-e63b7b83.development.esm.js +364 -0
  51. package/dist/send-e8b55d00.development.cjs.js +374 -0
  52. package/dist/xstate.cjs.js +140 -160
  53. package/dist/xstate.cjs.mjs +4 -2
  54. package/dist/xstate.development.cjs.js +140 -160
  55. package/dist/xstate.development.cjs.mjs +4 -2
  56. package/dist/xstate.development.esm.js +75 -95
  57. package/dist/xstate.esm.js +75 -95
  58. package/dist/xstate.umd.min.js +1 -1
  59. package/dist/xstate.umd.min.js.map +1 -1
  60. package/guards/dist/xstate-guards.cjs.js +7 -6
  61. package/guards/dist/xstate-guards.development.cjs.js +7 -6
  62. package/guards/dist/xstate-guards.development.esm.js +2 -1
  63. package/guards/dist/xstate-guards.esm.js +2 -1
  64. package/guards/dist/xstate-guards.umd.min.js +1 -1
  65. package/guards/dist/xstate-guards.umd.min.js.map +1 -1
  66. package/package.json +1 -1
  67. package/dist/actions-0971b43d.development.cjs.js +0 -3168
  68. package/dist/actions-319cefe7.cjs.js +0 -3095
  69. package/dist/actions-5943a9db.esm.js +0 -3018
  70. package/dist/actions-cf69419d.development.esm.js +0 -3091
  71. package/dist/declarations/src/constantPrefixes.d.ts +0 -6
@@ -1,3095 +0,0 @@
1
- 'use strict';
2
-
3
- var dev_dist_xstateDev = require('../dev/dist/xstate-dev.cjs.js');
4
-
5
- /**
6
- * `T | unknown` reduces to `unknown` and that can be problematic when it comes to contextual typing.
7
- * It especially is a problem when the union has a function member, like here:
8
- *
9
- * ```ts
10
- * declare function test(cbOrVal: ((arg: number) => unknown) | unknown): void;
11
- * test((arg) => {}) // oops, implicit any
12
- * ```
13
- *
14
- * This type can be used to avoid this problem. This union represents the same value space as `unknown`.
15
- */
16
-
17
- // https://github.com/microsoft/TypeScript/issues/23182#issuecomment-379091887
18
-
19
- /**
20
- * The full definition of an event, with a string `type`.
21
- */
22
-
23
- // TODO: do not accept machines without all implementations
24
- // we should also accept a raw machine as actor logic here
25
- // or just make machine actor logic
26
-
27
- /**
28
- * The string or object representing the state value relative to the parent state node.
29
- *
30
- * - For a child atomic state node, this is a string, e.g., `"pending"`.
31
- * - For complex state nodes, this is an object, e.g., `{ success: "someChildState" }`.
32
- */
33
-
34
- // TODO: remove once TS fixes this type-widening issue
35
-
36
- // TODO: possibly refactor this somehow, use even a simpler type, and maybe even make `machine.options` private or something
37
-
38
- let ConstantPrefix = /*#__PURE__*/function (ConstantPrefix) {
39
- ConstantPrefix["After"] = "xstate.after";
40
- ConstantPrefix["DoneState"] = "done.state";
41
- ConstantPrefix["DoneInvoke"] = "done.invoke";
42
- ConstantPrefix["ErrorExecution"] = "error.execution";
43
- ConstantPrefix["ErrorCommunication"] = "error.communication";
44
- ConstantPrefix["ErrorPlatform"] = "error.platform";
45
- ConstantPrefix["ErrorCustom"] = "xstate.error";
46
- return ConstantPrefix;
47
- }({});
48
- let SpecialTargets = /*#__PURE__*/function (SpecialTargets) {
49
- SpecialTargets["Parent"] = "#_parent";
50
- SpecialTargets["Internal"] = "#_internal";
51
- return SpecialTargets;
52
- }({});
53
-
54
- const after$1 = ConstantPrefix.After;
55
- const doneState = ConstantPrefix.DoneState;
56
- const errorExecution = ConstantPrefix.ErrorExecution;
57
- const errorPlatform = ConstantPrefix.ErrorPlatform;
58
- const error$1 = ConstantPrefix.ErrorCustom;
59
-
60
- var constantPrefixes = /*#__PURE__*/Object.freeze({
61
- __proto__: null,
62
- after: after$1,
63
- doneState: doneState,
64
- errorExecution: errorExecution,
65
- errorPlatform: errorPlatform,
66
- error: error$1
67
- });
68
-
69
- const STATE_DELIMITER = '.';
70
- const TARGETLESS_KEY = '';
71
- const NULL_EVENT = '';
72
- const STATE_IDENTIFIER = '#';
73
- const WILDCARD = '*';
74
- const INIT_TYPE = 'xstate.init';
75
-
76
- function resolve$8(actorContext, state, args, {
77
- to,
78
- event: eventOrExpr,
79
- id,
80
- delay
81
- }) {
82
- const delaysMap = state.machine.implementations.delays;
83
- if (typeof eventOrExpr === 'string') {
84
- throw new Error(`Only event objects may be used with sendTo; use sendTo({ type: "${eventOrExpr}" }) instead`);
85
- }
86
- const resolvedEvent = typeof eventOrExpr === 'function' ? eventOrExpr(args) : eventOrExpr;
87
- let resolvedDelay;
88
- if (typeof delay === 'string') {
89
- const configDelay = delaysMap && delaysMap[delay];
90
- resolvedDelay = typeof configDelay === 'function' ? configDelay(args) : configDelay;
91
- } else {
92
- resolvedDelay = typeof delay === 'function' ? delay(args) : delay;
93
- }
94
- const resolvedTarget = typeof to === 'function' ? to(args) : to;
95
- let targetActorRef;
96
- if (typeof resolvedTarget === 'string') {
97
- if (resolvedTarget === SpecialTargets.Parent) {
98
- targetActorRef = actorContext?.self._parent;
99
- } else if (resolvedTarget === SpecialTargets.Internal) {
100
- targetActorRef = actorContext?.self;
101
- } else if (resolvedTarget.startsWith('#_')) {
102
- // SCXML compatibility: https://www.w3.org/TR/scxml/#SCXMLEventProcessor
103
- // #_invokeid. If the target is the special term '#_invokeid', where invokeid is the invokeid of an SCXML session that the sending session has created by <invoke>, the Processor must add the event to the external queue of that session.
104
- targetActorRef = state.children[resolvedTarget.slice(2)];
105
- } else {
106
- targetActorRef = state.children[resolvedTarget];
107
- }
108
- if (!targetActorRef) {
109
- throw new Error(`Unable to send event to actor '${resolvedTarget}' from machine '${state.machine.id}'.`);
110
- }
111
- } else {
112
- targetActorRef = resolvedTarget || actorContext?.self;
113
- }
114
- return [state, {
115
- to: targetActorRef,
116
- event: resolvedEvent,
117
- id,
118
- delay: resolvedDelay
119
- }];
120
- }
121
- function execute$5(actorContext, params) {
122
- if (typeof params.delay === 'number') {
123
- actorContext.self.delaySend(params);
124
- return;
125
- }
126
- const {
127
- to,
128
- event
129
- } = params;
130
- actorContext.defer(() => {
131
- to.send(event.type === error$1 ? {
132
- type: `${error(actorContext.self.id)}`,
133
- data: event.data
134
- } : event);
135
- });
136
- }
137
-
138
- /**
139
- * Sends an event to an actor.
140
- *
141
- * @param actor The `ActorRef` to send the event to.
142
- * @param event The event to send, or an expression that evaluates to the event to send
143
- * @param options Send action options
144
- * - `id` - The unique send event identifier (used with `cancel()`).
145
- * - `delay` - The number of milliseconds to delay the sending of the event.
146
- */
147
- function sendTo(to, eventOrExpr, options) {
148
- function sendTo(_) {
149
- }
150
- sendTo.type = 'xstate.sendTo';
151
- sendTo.to = to;
152
- sendTo.event = eventOrExpr;
153
- sendTo.id = options?.id;
154
- sendTo.delay = options?.delay;
155
- sendTo.resolve = resolve$8;
156
- sendTo.execute = execute$5;
157
- return sendTo;
158
- }
159
-
160
- /**
161
- * Sends an event to this machine's parent.
162
- *
163
- * @param event The event to send to the parent machine.
164
- * @param options Options to pass into the send event.
165
- */
166
- function sendParent(event, options) {
167
- return sendTo(SpecialTargets.Parent, event, options);
168
- }
169
- /**
170
- * Forwards (sends) an event to a specified service.
171
- *
172
- * @param target The target service to forward the event to.
173
- * @param options Options to pass into the send action creator.
174
- */
175
- function forwardTo(target, options) {
176
- return sendTo(target, ({
177
- event
178
- }) => event, options);
179
- }
180
-
181
- /**
182
- * Escalates an error by sending it as an event to this machine's parent.
183
- *
184
- * @param errorData The error data to send, or the expression function that
185
- * takes in the `context`, `event`, and `meta`, and returns the error data to send.
186
- * @param options Options to pass into the send action creator.
187
- */
188
- function escalate(errorData, options) {
189
- return sendParent(arg => {
190
- return {
191
- type: error$1,
192
- data: typeof errorData === 'function' ? errorData(arg) : errorData
193
- };
194
- }, options);
195
- }
196
-
197
- const cache = new WeakMap();
198
- function memo(object, key, fn) {
199
- let memoizedData = cache.get(object);
200
- if (!memoizedData) {
201
- memoizedData = {
202
- [key]: fn()
203
- };
204
- cache.set(object, memoizedData);
205
- } else if (!(key in memoizedData)) {
206
- memoizedData[key] = fn();
207
- }
208
- return memoizedData[key];
209
- }
210
-
211
- function resolve$7(_, state, actionArgs, {
212
- sendId
213
- }) {
214
- const resolvedSendId = typeof sendId === 'function' ? sendId(actionArgs) : sendId;
215
- return [state, resolvedSendId];
216
- }
217
- function execute$4(actorContext, resolvedSendId) {
218
- actorContext.self.cancel(resolvedSendId);
219
- }
220
-
221
- /**
222
- * Cancels an in-flight `send(...)` action. A canceled sent action will not
223
- * be executed, nor will its event be sent, unless it has already been sent
224
- * (e.g., if `cancel(...)` is called after the `send(...)` action's `delay`).
225
- *
226
- * @param sendId The `id` of the `send(...)` action to cancel.
227
- */
228
- function cancel(sendId) {
229
- function cancel(_) {
230
- }
231
- cancel.type = 'xstate.cancel';
232
- cancel.sendId = sendId;
233
- cancel.resolve = resolve$7;
234
- cancel.execute = execute$4;
235
- return cancel;
236
- }
237
-
238
- class Mailbox {
239
- constructor(_process) {
240
- this._process = _process;
241
- this._active = false;
242
- this._current = null;
243
- this._last = null;
244
- }
245
- start() {
246
- this._active = true;
247
- this.flush();
248
- }
249
- clear() {
250
- // we can't set _current to null because we might be currently processing
251
- // and enqueue following clear shouldnt start processing the enqueued item immediately
252
- if (this._current) {
253
- this._current.next = null;
254
- this._last = this._current;
255
- }
256
- }
257
-
258
- // TODO: rethink this design
259
- prepend(event) {
260
- if (!this._current) {
261
- this.enqueue(event);
262
- return;
263
- }
264
-
265
- // we know that something is already queued up
266
- // so the mailbox is already flushing or it's inactive
267
- // therefore the only thing that we need to do is to reassign `this._current`
268
- this._current = {
269
- value: event,
270
- next: this._current
271
- };
272
- }
273
- enqueue(event) {
274
- const enqueued = {
275
- value: event,
276
- next: null
277
- };
278
- if (this._current) {
279
- this._last.next = enqueued;
280
- this._last = enqueued;
281
- return;
282
- }
283
- this._current = enqueued;
284
- this._last = enqueued;
285
- if (this._active) {
286
- this.flush();
287
- }
288
- }
289
- flush() {
290
- while (this._current) {
291
- // atm the given _process is responsible for implementing proper try/catch handling
292
- // we assume here that this won't throw in a way that can affect this mailbox
293
- const consumed = this._current;
294
- this._process(consumed.value);
295
- // something could have been prepended in the meantime
296
- // so we need to be defensive here to avoid skipping over a prepended item
297
- if (consumed === this._current) {
298
- this._current = this._current.next;
299
- }
300
- }
301
- this._last = null;
302
- }
303
- }
304
-
305
- const symbolObservable = (() => typeof Symbol === 'function' && Symbol.observable || '@@observable')();
306
-
307
- /**
308
- * Returns actor logic from a transition function and its initial state.
309
- *
310
- * A transition function is a function that takes the current state and an event and returns the next state.
311
- *
312
- * @param transition The transition function that returns the next state given the current state and event.
313
- * @param initialState The initial state of the transition function.
314
- * @returns Actor logic
315
- */
316
- function fromTransition(transition, initialState) {
317
- return {
318
- config: transition,
319
- transition: (state, event, actorContext) => {
320
- return transition(state, event, actorContext);
321
- },
322
- getInitialState: (_, input) => {
323
- return typeof initialState === 'function' ? initialState({
324
- input
325
- }) : initialState;
326
- },
327
- getSnapshot: state => state,
328
- getPersistedState: state => state,
329
- restoreState: state => state
330
- };
331
- }
332
-
333
- function matchesState(parentStateId, childStateId) {
334
- const parentStateValue = toStateValue(parentStateId);
335
- const childStateValue = toStateValue(childStateId);
336
- if (typeof childStateValue === 'string') {
337
- if (typeof parentStateValue === 'string') {
338
- return childStateValue === parentStateValue;
339
- }
340
-
341
- // Parent more specific than child
342
- return false;
343
- }
344
- if (typeof parentStateValue === 'string') {
345
- return parentStateValue in childStateValue;
346
- }
347
- return Object.keys(parentStateValue).every(key => {
348
- if (!(key in childStateValue)) {
349
- return false;
350
- }
351
- return matchesState(parentStateValue[key], childStateValue[key]);
352
- });
353
- }
354
- function toStatePath(stateId) {
355
- try {
356
- if (isArray(stateId)) {
357
- return stateId;
358
- }
359
- return stateId.toString().split(STATE_DELIMITER);
360
- } catch (e) {
361
- throw new Error(`'${stateId}' is not a valid state path.`);
362
- }
363
- }
364
- function isStateLike(state) {
365
- return typeof state === 'object' && 'value' in state && 'context' in state && 'event' in state;
366
- }
367
- function toStateValue(stateValue) {
368
- if (isStateLike(stateValue)) {
369
- return stateValue.value;
370
- }
371
- if (isArray(stateValue)) {
372
- return pathToStateValue(stateValue);
373
- }
374
- if (typeof stateValue !== 'string') {
375
- return stateValue;
376
- }
377
- const statePath = toStatePath(stateValue);
378
- return pathToStateValue(statePath);
379
- }
380
- function pathToStateValue(statePath) {
381
- if (statePath.length === 1) {
382
- return statePath[0];
383
- }
384
- const value = {};
385
- let marker = value;
386
- for (let i = 0; i < statePath.length - 1; i++) {
387
- if (i === statePath.length - 2) {
388
- marker[statePath[i]] = statePath[i + 1];
389
- } else {
390
- const previous = marker;
391
- marker = {};
392
- previous[statePath[i]] = marker;
393
- }
394
- }
395
- return value;
396
- }
397
- function mapValues(collection, iteratee) {
398
- const result = {};
399
- const collectionKeys = Object.keys(collection);
400
- for (let i = 0; i < collectionKeys.length; i++) {
401
- const key = collectionKeys[i];
402
- result[key] = iteratee(collection[key], key, collection, i);
403
- }
404
- return result;
405
- }
406
- function flatten(array) {
407
- return [].concat(...array);
408
- }
409
- function toArrayStrict(value) {
410
- if (isArray(value)) {
411
- return value;
412
- }
413
- return [value];
414
- }
415
- function toArray(value) {
416
- if (value === undefined) {
417
- return [];
418
- }
419
- return toArrayStrict(value);
420
- }
421
- function mapContext(mapper, context, event, self) {
422
- if (typeof mapper === 'function') {
423
- return mapper({
424
- context,
425
- event,
426
- self
427
- });
428
- }
429
- return mapper;
430
- }
431
- function isPromiseLike(value) {
432
- if (value instanceof Promise) {
433
- return true;
434
- }
435
- // Check if shape matches the Promise/A+ specification for a "thenable".
436
- if (value !== null && (typeof value === 'function' || typeof value === 'object') && typeof value.then === 'function') {
437
- return true;
438
- }
439
- return false;
440
- }
441
- function isArray(value) {
442
- return Array.isArray(value);
443
- }
444
- function isErrorEvent(event) {
445
- return typeof event.type === 'string' && (event.type === errorExecution || event.type.startsWith(errorPlatform));
446
- }
447
- function toTransitionConfigArray(configLike) {
448
- return toArrayStrict(configLike).map(transitionLike => {
449
- if (typeof transitionLike === 'undefined' || typeof transitionLike === 'string') {
450
- return {
451
- target: transitionLike
452
- };
453
- }
454
- return transitionLike;
455
- });
456
- }
457
- function normalizeTarget(target) {
458
- if (target === undefined || target === TARGETLESS_KEY) {
459
- return undefined;
460
- }
461
- return toArray(target);
462
- }
463
- function toInvokeConfig(invocable, id) {
464
- if (typeof invocable === 'object') {
465
- if ('src' in invocable) {
466
- return invocable;
467
- }
468
- if ('transition' in invocable) {
469
- return {
470
- id,
471
- src: invocable
472
- };
473
- }
474
- }
475
- return {
476
- id,
477
- src: invocable
478
- };
479
- }
480
- function toObserver(nextHandler, errorHandler, completionHandler) {
481
- const isObserver = typeof nextHandler === 'object';
482
- const self = isObserver ? nextHandler : undefined;
483
- return {
484
- next: (isObserver ? nextHandler.next : nextHandler)?.bind(self),
485
- error: (isObserver ? nextHandler.error : errorHandler)?.bind(self),
486
- complete: (isObserver ? nextHandler.complete : completionHandler)?.bind(self)
487
- };
488
- }
489
- function createInvokeId(stateNodeId, index) {
490
- return `${stateNodeId}:invocation[${index}]`;
491
- }
492
- function resolveReferencedActor(referenced) {
493
- return referenced ? 'transition' in referenced ? {
494
- src: referenced,
495
- input: undefined
496
- } : referenced : undefined;
497
- }
498
-
499
- function fromCallback(invokeCallback) {
500
- return {
501
- config: invokeCallback,
502
- start: (_state, {
503
- self
504
- }) => {
505
- self.send({
506
- type: startSignalType
507
- });
508
- },
509
- transition: (state, event, {
510
- self,
511
- id,
512
- system
513
- }) => {
514
- if (event.type === startSignalType) {
515
- const sendBack = eventForParent => {
516
- if (state.canceled) {
517
- return;
518
- }
519
- self._parent?.send(eventForParent);
520
- };
521
- const receive = newListener => {
522
- state.receivers.add(newListener);
523
- };
524
- state.dispose = invokeCallback({
525
- input: state.input,
526
- system,
527
- self: self,
528
- sendBack,
529
- receive
530
- });
531
- if (isPromiseLike(state.dispose)) {
532
- state.dispose.then(resolved => {
533
- self._parent?.send(doneInvoke(id, resolved));
534
- state.canceled = true;
535
- }, errorData => {
536
- state.canceled = true;
537
- self._parent?.send(error(id, errorData));
538
- });
539
- }
540
- return state;
541
- }
542
- if (event.type === stopSignalType) {
543
- state.canceled = true;
544
- if (typeof state.dispose === 'function') {
545
- state.dispose();
546
- }
547
- return state;
548
- }
549
- if (isSignal(event)) {
550
- // TODO: unrecognized signal
551
- return state;
552
- }
553
- state.receivers.forEach(receiver => receiver(event));
554
- return state;
555
- },
556
- getInitialState: (_, input) => {
557
- return {
558
- canceled: false,
559
- receivers: new Set(),
560
- dispose: undefined,
561
- input
562
- };
563
- },
564
- getSnapshot: () => undefined,
565
- getPersistedState: ({
566
- input,
567
- canceled
568
- }) => ({
569
- input,
570
- canceled
571
- })
572
- };
573
- }
574
-
575
- function fromObservable(observableCreator) {
576
- const nextEventType = '$$xstate.next';
577
- const errorEventType = '$$xstate.error';
578
- const completeEventType = '$$xstate.complete';
579
- return {
580
- config: observableCreator,
581
- transition: (state, event, {
582
- self,
583
- id,
584
- defer
585
- }) => {
586
- if (state.status !== 'active') {
587
- return state;
588
- }
589
- switch (event.type) {
590
- case nextEventType:
591
- // match the exact timing of events sent by machines
592
- // send actions are not executed immediately
593
- defer(() => {
594
- self._parent?.send({
595
- type: `xstate.snapshot.${id}`,
596
- data: event.data
597
- });
598
- });
599
- return {
600
- ...state,
601
- data: event.data
602
- };
603
- case errorEventType:
604
- return {
605
- ...state,
606
- status: 'error',
607
- input: undefined,
608
- data: event.data,
609
- // TODO: if we keep this as `data` we should reflect this in the type
610
- subscription: undefined
611
- };
612
- case completeEventType:
613
- return {
614
- ...state,
615
- status: 'done',
616
- input: undefined,
617
- subscription: undefined
618
- };
619
- case stopSignalType:
620
- state.subscription.unsubscribe();
621
- return {
622
- ...state,
623
- status: 'canceled',
624
- input: undefined,
625
- subscription: undefined
626
- };
627
- default:
628
- return state;
629
- }
630
- },
631
- getInitialState: (_, input) => {
632
- return {
633
- subscription: undefined,
634
- status: 'active',
635
- data: undefined,
636
- input
637
- };
638
- },
639
- start: (state, {
640
- self,
641
- system
642
- }) => {
643
- if (state.status === 'done') {
644
- // Do not restart a completed observable
645
- return;
646
- }
647
- state.subscription = observableCreator({
648
- input: state.input,
649
- system,
650
- self
651
- }).subscribe({
652
- next: value => {
653
- self.send({
654
- type: nextEventType,
655
- data: value
656
- });
657
- },
658
- error: err => {
659
- self.send({
660
- type: errorEventType,
661
- data: err
662
- });
663
- },
664
- complete: () => {
665
- self.send({
666
- type: completeEventType
667
- });
668
- }
669
- });
670
- },
671
- getSnapshot: state => state.data,
672
- getPersistedState: ({
673
- status,
674
- data,
675
- input
676
- }) => ({
677
- status,
678
- data,
679
- input
680
- }),
681
- getStatus: state => state,
682
- restoreState: state => ({
683
- ...state,
684
- subscription: undefined
685
- })
686
- };
687
- }
688
-
689
- /**
690
- * Creates event observable logic that listens to an observable
691
- * that delivers event objects.
692
- *
693
- *
694
- * @param lazyObservable A function that creates an observable
695
- * @returns Event observable logic
696
- */
697
-
698
- function fromEventObservable(lazyObservable) {
699
- const errorEventType = '$$xstate.error';
700
- const completeEventType = '$$xstate.complete';
701
-
702
- // TODO: event types
703
- return {
704
- config: lazyObservable,
705
- transition: (state, event) => {
706
- if (state.status !== 'active') {
707
- return state;
708
- }
709
- switch (event.type) {
710
- case errorEventType:
711
- return {
712
- ...state,
713
- status: 'error',
714
- input: undefined,
715
- data: event.data,
716
- // TODO: if we keep this as `data` we should reflect this in the type
717
- subscription: undefined
718
- };
719
- case completeEventType:
720
- return {
721
- ...state,
722
- status: 'done',
723
- input: undefined,
724
- subscription: undefined
725
- };
726
- case stopSignalType:
727
- state.subscription.unsubscribe();
728
- return {
729
- ...state,
730
- status: 'canceled',
731
- input: undefined,
732
- subscription: undefined
733
- };
734
- default:
735
- return state;
736
- }
737
- },
738
- getInitialState: (_, input) => {
739
- return {
740
- subscription: undefined,
741
- status: 'active',
742
- data: undefined,
743
- input
744
- };
745
- },
746
- start: (state, {
747
- self,
748
- system
749
- }) => {
750
- if (state.status === 'done') {
751
- // Do not restart a completed observable
752
- return;
753
- }
754
- state.subscription = lazyObservable({
755
- input: state.input,
756
- system,
757
- self
758
- }).subscribe({
759
- next: value => {
760
- self._parent?.send(value);
761
- },
762
- error: err => {
763
- self.send({
764
- type: errorEventType,
765
- data: err
766
- });
767
- },
768
- complete: () => {
769
- self.send({
770
- type: completeEventType
771
- });
772
- }
773
- });
774
- },
775
- getSnapshot: _ => undefined,
776
- getPersistedState: ({
777
- status,
778
- data,
779
- input
780
- }) => ({
781
- status,
782
- data,
783
- input
784
- }),
785
- getStatus: state => state,
786
- restoreState: state => ({
787
- ...state,
788
- subscription: undefined
789
- })
790
- };
791
- }
792
-
793
- const resolveEventType = '$$xstate.resolve';
794
- const rejectEventType = '$$xstate.reject';
795
- function fromPromise(
796
- // TODO: add types
797
- promiseCreator) {
798
- // TODO: add event types
799
- const logic = {
800
- config: promiseCreator,
801
- transition: (state, event) => {
802
- if (state.status !== 'active') {
803
- return state;
804
- }
805
- switch (event.type) {
806
- case resolveEventType:
807
- return {
808
- ...state,
809
- status: 'done',
810
- data: event.data,
811
- input: undefined
812
- };
813
- case rejectEventType:
814
- return {
815
- ...state,
816
- status: 'error',
817
- data: event.data,
818
- // TODO: if we keep this as `data` we should reflect this in the type
819
- input: undefined
820
- };
821
- case stopSignalType:
822
- return {
823
- ...state,
824
- status: 'canceled',
825
- input: undefined
826
- };
827
- default:
828
- return state;
829
- }
830
- },
831
- start: (state, {
832
- self,
833
- system
834
- }) => {
835
- // TODO: determine how to allow customizing this so that promises
836
- // can be restarted if necessary
837
- if (state.status !== 'active') {
838
- return;
839
- }
840
- const resolvedPromise = Promise.resolve(promiseCreator({
841
- input: state.input,
842
- system,
843
- self
844
- }));
845
- resolvedPromise.then(response => {
846
- // TODO: remove this condition once dead letter queue lands
847
- if (self._state.status !== 'active') {
848
- return;
849
- }
850
- self.send({
851
- type: resolveEventType,
852
- data: response
853
- });
854
- }, errorData => {
855
- // TODO: remove this condition once dead letter queue lands
856
- if (self._state.status !== 'active') {
857
- return;
858
- }
859
- self.send({
860
- type: rejectEventType,
861
- data: errorData
862
- });
863
- });
864
- },
865
- getInitialState: (_, input) => {
866
- return {
867
- status: 'active',
868
- data: undefined,
869
- input
870
- };
871
- },
872
- getSnapshot: state => state.data,
873
- getStatus: state => state,
874
- getPersistedState: state => state,
875
- restoreState: state => state
876
- };
877
- return logic;
878
- }
879
-
880
- const startSignalType = 'xstate.init';
881
- const stopSignalType = 'xstate.stop';
882
- const startSignal = {
883
- type: 'xstate.init'
884
- };
885
- const stopSignal = {
886
- type: 'xstate.stop'
887
- };
888
- /**
889
- * An object that expresses the actor logic in reaction to received events,
890
- * as well as an optionally emitted stream of values.
891
- *
892
- * @template TReceived The received event
893
- * @template TSnapshot The emitted value
894
- */
895
-
896
- function isSignal(event) {
897
- return event.type === startSignalType || event.type === stopSignalType;
898
- }
899
- function isActorRef(item) {
900
- return !!item && typeof item === 'object' && typeof item.send === 'function';
901
- }
902
-
903
- // TODO: refactor the return type, this could be written in a better way
904
- // but it's best to avoid unneccessary breaking changes now
905
- // @deprecated use `interpret(actorLogic)` instead
906
- function toActorRef(actorRefLike) {
907
- return {
908
- subscribe: () => ({
909
- unsubscribe: () => void 0
910
- }),
911
- id: 'anonymous',
912
- sessionId: '',
913
- getSnapshot: () => undefined,
914
- // TODO: this isn't safe
915
- [symbolObservable]: function () {
916
- return this;
917
- },
918
- status: ActorStatus.Running,
919
- stop: () => void 0,
920
- ...actorRefLike
921
- };
922
- }
923
- const emptyLogic = fromTransition(_ => undefined, undefined);
924
- function createEmptyActor() {
925
- return createActor(emptyLogic);
926
- }
927
-
928
- /**
929
- * This function makes sure that unhandled errors are thrown in a separate macrotask.
930
- * It allows those errors to be detected by global error handlers and reported to bug tracking services
931
- * without interrupting our own stack of execution.
932
- *
933
- * @param err error to be thrown
934
- */
935
- function reportUnhandledError(err) {
936
- setTimeout(() => {
937
- throw err;
938
- });
939
- }
940
-
941
- function createSystem() {
942
- let sessionIdCounter = 0;
943
- const children = new Map();
944
- const keyedActors = new Map();
945
- const reverseKeyedActors = new WeakMap();
946
- const system = {
947
- _bookId: () => `x:${sessionIdCounter++}`,
948
- _register: (sessionId, actorRef) => {
949
- children.set(sessionId, actorRef);
950
- return sessionId;
951
- },
952
- _unregister: actorRef => {
953
- children.delete(actorRef.sessionId);
954
- const systemId = reverseKeyedActors.get(actorRef);
955
- if (systemId !== undefined) {
956
- keyedActors.delete(systemId);
957
- reverseKeyedActors.delete(actorRef);
958
- }
959
- },
960
- get: systemId => {
961
- return keyedActors.get(systemId);
962
- },
963
- _set: (systemId, actorRef) => {
964
- const existing = keyedActors.get(systemId);
965
- if (existing && existing !== actorRef) {
966
- throw new Error(`Actor with system ID '${systemId}' already exists.`);
967
- }
968
- keyedActors.set(systemId, actorRef);
969
- reverseKeyedActors.set(actorRef, systemId);
970
- }
971
- };
972
- return system;
973
- }
974
-
975
- let ActorStatus = /*#__PURE__*/function (ActorStatus) {
976
- ActorStatus[ActorStatus["NotStarted"] = 0] = "NotStarted";
977
- ActorStatus[ActorStatus["Running"] = 1] = "Running";
978
- ActorStatus[ActorStatus["Stopped"] = 2] = "Stopped";
979
- return ActorStatus;
980
- }({});
981
-
982
- /**
983
- * @deprecated Use `ActorStatus` instead.
984
- */
985
- const InterpreterStatus = ActorStatus;
986
- const defaultOptions = {
987
- deferEvents: true,
988
- clock: {
989
- setTimeout: (fn, ms) => {
990
- return setTimeout(fn, ms);
991
- },
992
- clearTimeout: id => {
993
- return clearTimeout(id);
994
- }
995
- },
996
- logger: console.log.bind(console),
997
- devTools: false
998
- };
999
- class Actor {
1000
- /**
1001
- * The current internal state of the actor.
1002
- */
1003
-
1004
- /**
1005
- * The clock that is responsible for setting and clearing timeouts, such as delayed events and transitions.
1006
- */
1007
-
1008
- /**
1009
- * The unique identifier for this actor relative to its parent.
1010
- */
1011
-
1012
- /**
1013
- * Whether the service is started.
1014
- */
1015
-
1016
- // Actor Ref
1017
-
1018
- // TODO: add typings for system
1019
-
1020
- /**
1021
- * The globally unique process ID for this invocation.
1022
- */
1023
-
1024
- /**
1025
- * Creates a new actor instance for the given logic with the provided options, if any.
1026
- *
1027
- * @param logic The logic to create an actor from
1028
- * @param options Actor options
1029
- */
1030
- constructor(logic, options) {
1031
- this.logic = logic;
1032
- this._state = void 0;
1033
- this.clock = void 0;
1034
- this.options = void 0;
1035
- this.id = void 0;
1036
- this.mailbox = new Mailbox(this._process.bind(this));
1037
- this.delayedEventsMap = {};
1038
- this.observers = new Set();
1039
- this.logger = void 0;
1040
- this.status = ActorStatus.NotStarted;
1041
- this._parent = void 0;
1042
- this.ref = void 0;
1043
- this._actorContext = void 0;
1044
- this._systemId = void 0;
1045
- this.sessionId = void 0;
1046
- this.system = void 0;
1047
- this._doneEvent = void 0;
1048
- this.src = void 0;
1049
- this._deferred = [];
1050
- const resolvedOptions = {
1051
- ...defaultOptions,
1052
- ...options
1053
- };
1054
- const {
1055
- clock,
1056
- logger,
1057
- parent,
1058
- id,
1059
- systemId
1060
- } = resolvedOptions;
1061
- const self = this;
1062
- this.system = parent?.system ?? createSystem();
1063
- if (systemId) {
1064
- this._systemId = systemId;
1065
- this.system._set(systemId, this);
1066
- }
1067
- this.sessionId = this.system._bookId();
1068
- this.id = id ?? this.sessionId;
1069
- this.logger = logger;
1070
- this.clock = clock;
1071
- this._parent = parent;
1072
- this.options = resolvedOptions;
1073
- this.src = resolvedOptions.src;
1074
- this.ref = this;
1075
- this._actorContext = {
1076
- self,
1077
- id: this.id,
1078
- sessionId: this.sessionId,
1079
- logger: this.logger,
1080
- defer: fn => {
1081
- this._deferred.push(fn);
1082
- },
1083
- system: this.system,
1084
- stopChild: child => {
1085
- if (child._parent !== this) {
1086
- throw new Error(`Cannot stop child actor ${child.id} of ${this.id} because it is not a child`);
1087
- }
1088
- child._stop();
1089
- }
1090
- };
1091
-
1092
- // Ensure that the send method is bound to this Actor instance
1093
- // if destructured
1094
- this.send = this.send.bind(this);
1095
- this._initState();
1096
- }
1097
- _initState() {
1098
- this._state = this.options.state ? this.logic.restoreState ? this.logic.restoreState(this.options.state, this._actorContext) : this.options.state : this.logic.getInitialState(this._actorContext, this.options?.input);
1099
- }
1100
-
1101
- // array of functions to defer
1102
-
1103
- update(state) {
1104
- // Update state
1105
- this._state = state;
1106
- const snapshot = this.getSnapshot();
1107
-
1108
- // Execute deferred effects
1109
- let deferredFn;
1110
- while (deferredFn = this._deferred.shift()) {
1111
- deferredFn();
1112
- }
1113
- for (const observer of this.observers) {
1114
- // TODO: should observers be notified in case of the error?
1115
- try {
1116
- observer.next?.(snapshot);
1117
- } catch (err) {
1118
- reportUnhandledError(err);
1119
- }
1120
- }
1121
- const status = this.logic.getStatus?.(state);
1122
- switch (status?.status) {
1123
- case 'done':
1124
- this._stopProcedure();
1125
- this._complete();
1126
- this._doneEvent = doneInvoke(this.id, status.data);
1127
- this._parent?.send(this._doneEvent);
1128
- break;
1129
- case 'error':
1130
- this._stopProcedure();
1131
- this._error(status.data);
1132
- this._parent?.send(error(this.id, status.data));
1133
- break;
1134
- }
1135
- }
1136
- subscribe(nextListenerOrObserver, errorListener, completeListener) {
1137
- const observer = toObserver(nextListenerOrObserver, errorListener, completeListener);
1138
- if (this.status !== ActorStatus.Stopped) {
1139
- this.observers.add(observer);
1140
- } else {
1141
- try {
1142
- observer.complete?.();
1143
- } catch (err) {
1144
- reportUnhandledError(err);
1145
- }
1146
- }
1147
- return {
1148
- unsubscribe: () => {
1149
- this.observers.delete(observer);
1150
- }
1151
- };
1152
- }
1153
-
1154
- /**
1155
- * Starts the Actor from the initial state
1156
- */
1157
- start() {
1158
- if (this.status === ActorStatus.Running) {
1159
- // Do not restart the service if it is already started
1160
- return this;
1161
- }
1162
- this.system._register(this.sessionId, this);
1163
- if (this._systemId) {
1164
- this.system._set(this._systemId, this);
1165
- }
1166
- this.status = ActorStatus.Running;
1167
- const status = this.logic.getStatus?.(this._state);
1168
- switch (status?.status) {
1169
- case 'done':
1170
- // a state machine can be "done" upon intialization (it could reach a final state using initial microsteps)
1171
- // we still need to complete observers, flush deferreds etc
1172
- this.update(this._state);
1173
- // fallthrough
1174
- case 'error':
1175
- // TODO: rethink cleanup of observers, mailbox, etc
1176
- return this;
1177
- }
1178
- if (this.logic.start) {
1179
- try {
1180
- this.logic.start(this._state, this._actorContext);
1181
- } catch (err) {
1182
- this._stopProcedure();
1183
- this._error(err);
1184
- this._parent?.send(error(this.id, err));
1185
- return this;
1186
- }
1187
- }
1188
-
1189
- // TODO: this notifies all subscribers but usually this is redundant
1190
- // there is no real change happening here
1191
- // we need to rethink if this needs to be refactored
1192
- this.update(this._state);
1193
- if (this.options.devTools) {
1194
- this.attachDevTools();
1195
- }
1196
- this.mailbox.start();
1197
- return this;
1198
- }
1199
- _process(event) {
1200
- // TODO: reexamine what happens when an action (or a guard or smth) throws
1201
- let nextState;
1202
- let caughtError;
1203
- try {
1204
- nextState = this.logic.transition(this._state, event, this._actorContext);
1205
- } catch (err) {
1206
- // we wrap it in a box so we can rethrow it later even if falsy value gets caught here
1207
- caughtError = {
1208
- err
1209
- };
1210
- }
1211
- if (caughtError) {
1212
- const {
1213
- err
1214
- } = caughtError;
1215
- this._stopProcedure();
1216
- this._error(err);
1217
- this._parent?.send(error(this.id, err));
1218
- return;
1219
- }
1220
- this.update(nextState);
1221
- if (event.type === stopSignalType) {
1222
- this._stopProcedure();
1223
- this._complete();
1224
- }
1225
- }
1226
- _stop() {
1227
- if (this.status === ActorStatus.Stopped) {
1228
- return this;
1229
- }
1230
- this.mailbox.clear();
1231
- if (this.status === ActorStatus.NotStarted) {
1232
- this.status = ActorStatus.Stopped;
1233
- return this;
1234
- }
1235
- this.mailbox.enqueue({
1236
- type: stopSignalType
1237
- });
1238
- return this;
1239
- }
1240
-
1241
- /**
1242
- * Stops the Actor and unsubscribe all listeners.
1243
- */
1244
- stop() {
1245
- if (this._parent) {
1246
- throw new Error('A non-root actor cannot be stopped directly.');
1247
- }
1248
- return this._stop();
1249
- }
1250
- _complete() {
1251
- for (const observer of this.observers) {
1252
- try {
1253
- observer.complete?.();
1254
- } catch (err) {
1255
- reportUnhandledError(err);
1256
- }
1257
- }
1258
- this.observers.clear();
1259
- }
1260
- _error(err) {
1261
- if (!this.observers.size) {
1262
- if (!this._parent) {
1263
- reportUnhandledError(err);
1264
- }
1265
- return;
1266
- }
1267
- let reportError = false;
1268
- for (const observer of this.observers) {
1269
- const errorListener = observer.error;
1270
- reportError ||= !errorListener;
1271
- try {
1272
- errorListener?.(err);
1273
- } catch (err2) {
1274
- reportUnhandledError(err2);
1275
- }
1276
- }
1277
- this.observers.clear();
1278
- if (reportError) {
1279
- reportUnhandledError(err);
1280
- }
1281
- }
1282
- _stopProcedure() {
1283
- if (this.status !== ActorStatus.Running) {
1284
- // Actor already stopped; do nothing
1285
- return this;
1286
- }
1287
-
1288
- // Cancel all delayed events
1289
- for (const key of Object.keys(this.delayedEventsMap)) {
1290
- this.clock.clearTimeout(this.delayedEventsMap[key]);
1291
- }
1292
-
1293
- // TODO: mailbox.reset
1294
- this.mailbox.clear();
1295
- // TODO: after `stop` we must prepare ourselves for receiving events again
1296
- // events sent *after* stop signal must be queued
1297
- // it seems like this should be the common behavior for all of our consumers
1298
- // so perhaps this should be unified somehow for all of them
1299
- this.mailbox = new Mailbox(this._process.bind(this));
1300
- this.status = ActorStatus.Stopped;
1301
- this.system._unregister(this);
1302
- return this;
1303
- }
1304
-
1305
- /**
1306
- * Sends an event to the running Actor to trigger a transition.
1307
- *
1308
- * @param event The event to send
1309
- */
1310
- send(event) {
1311
- if (typeof event === 'string') {
1312
- throw new Error(`Only event objects may be sent to actors; use .send({ type: "${event}" }) instead`);
1313
- }
1314
- if (this.status === ActorStatus.Stopped) {
1315
- return;
1316
- }
1317
- if (this.status !== ActorStatus.Running && !this.options.deferEvents) {
1318
- throw new Error(`Event "${event.type}" was sent to uninitialized actor "${this.id
1319
- // tslint:disable-next-line:max-line-length
1320
- }". Make sure .start() is called for this actor, or set { deferEvents: true } in the actor options.\nEvent: ${JSON.stringify(event)}`);
1321
- }
1322
- this.mailbox.enqueue(event);
1323
- }
1324
-
1325
- // TODO: make private (and figure out a way to do this within the machine)
1326
- delaySend({
1327
- event,
1328
- id,
1329
- delay,
1330
- to
1331
- }) {
1332
- const timerId = this.clock.setTimeout(() => {
1333
- if (to) {
1334
- to.send(event);
1335
- } else {
1336
- this.send(event);
1337
- }
1338
- }, delay);
1339
-
1340
- // TODO: consider the rehydration story here
1341
- if (id) {
1342
- this.delayedEventsMap[id] = timerId;
1343
- }
1344
- }
1345
-
1346
- // TODO: make private (and figure out a way to do this within the machine)
1347
- cancel(sendId) {
1348
- this.clock.clearTimeout(this.delayedEventsMap[sendId]);
1349
- delete this.delayedEventsMap[sendId];
1350
- }
1351
- attachDevTools() {
1352
- const {
1353
- devTools
1354
- } = this.options;
1355
- if (devTools) {
1356
- const resolvedDevToolsAdapter = typeof devTools === 'function' ? devTools : dev_dist_xstateDev.devToolsAdapter;
1357
- resolvedDevToolsAdapter(this);
1358
- }
1359
- }
1360
- toJSON() {
1361
- return {
1362
- id: this.id
1363
- };
1364
- }
1365
- getPersistedState() {
1366
- return this.logic.getPersistedState?.(this._state);
1367
- }
1368
- [symbolObservable]() {
1369
- return this;
1370
- }
1371
- getSnapshot() {
1372
- return this.logic.getSnapshot ? this.logic.getSnapshot(this._state) : this._state;
1373
- }
1374
- }
1375
-
1376
- /**
1377
- * Creates a new `ActorRef` instance for the given machine with the provided options, if any.
1378
- *
1379
- * @param machine The machine to create an actor from
1380
- * @param options `ActorRef` options
1381
- */
1382
-
1383
- function createActor(logic, options) {
1384
- const interpreter = new Actor(logic, options);
1385
- return interpreter;
1386
- }
1387
-
1388
- /**
1389
- * Creates a new Interpreter instance for the given machine with the provided options, if any.
1390
- *
1391
- * @deprecated Use `createActor` instead
1392
- */
1393
- const interpret = createActor;
1394
-
1395
- /**
1396
- * @deprecated Use `Actor` instead.
1397
- */
1398
-
1399
- function resolve$6(actorContext, state, actionArgs, {
1400
- id,
1401
- systemId,
1402
- src,
1403
- input
1404
- }) {
1405
- const referenced = resolveReferencedActor(state.machine.implementations.actors[src]);
1406
- let actorRef;
1407
- if (referenced) {
1408
- // TODO: inline `input: undefined` should win over the referenced one
1409
- const configuredInput = input || referenced.input;
1410
- actorRef = createActor(referenced.src, {
1411
- id,
1412
- src,
1413
- parent: actorContext?.self,
1414
- systemId,
1415
- input: typeof configuredInput === 'function' ? configuredInput({
1416
- context: state.context,
1417
- event: actionArgs.event,
1418
- self: actorContext?.self
1419
- }) : configuredInput
1420
- });
1421
- }
1422
- return [cloneState(state, {
1423
- children: {
1424
- ...state.children,
1425
- [id]: actorRef
1426
- }
1427
- }), {
1428
- id,
1429
- actorRef
1430
- }];
1431
- }
1432
- function execute$3(actorContext, {
1433
- id,
1434
- actorRef
1435
- }) {
1436
- if (!actorRef) {
1437
- return;
1438
- }
1439
- actorContext.defer(() => {
1440
- if (actorRef.status === ActorStatus.Stopped) {
1441
- return;
1442
- }
1443
- try {
1444
- actorRef.start?.();
1445
- } catch (err) {
1446
- actorContext.self.send(error(id, err));
1447
- return;
1448
- }
1449
- });
1450
- }
1451
- function invoke({
1452
- id,
1453
- systemId,
1454
- src,
1455
- input
1456
- }) {
1457
- function invoke(_) {
1458
- }
1459
- invoke.type = 'xstate.invoke';
1460
- invoke.id = id;
1461
- invoke.systemId = systemId;
1462
- invoke.src = src;
1463
- invoke.input = input;
1464
- invoke.resolve = resolve$6;
1465
- invoke.execute = execute$3;
1466
- return invoke;
1467
- }
1468
-
1469
- function checkStateIn(state, _, {
1470
- stateValue
1471
- }) {
1472
- if (typeof stateValue === 'string' && isStateId(stateValue)) {
1473
- return state.configuration.some(sn => sn.id === stateValue.slice(1));
1474
- }
1475
- return state.matches(stateValue);
1476
- }
1477
- function stateIn(stateValue) {
1478
- function stateIn(_) {
1479
- return false;
1480
- }
1481
- stateIn.check = checkStateIn;
1482
- stateIn.stateValue = stateValue;
1483
- return stateIn;
1484
- }
1485
- function checkNot(state, {
1486
- context,
1487
- event
1488
- }, {
1489
- guards
1490
- }) {
1491
- return !evaluateGuard(guards[0], context, event, state);
1492
- }
1493
- function not(guard) {
1494
- function not(_) {
1495
- return false;
1496
- }
1497
- not.check = checkNot;
1498
- not.guards = [guard];
1499
- return not;
1500
- }
1501
- function checkAnd(state, {
1502
- context,
1503
- event
1504
- }, {
1505
- guards
1506
- }) {
1507
- return guards.every(guard => evaluateGuard(guard, context, event, state));
1508
- }
1509
- function and(guards) {
1510
- function and(_) {
1511
- return false;
1512
- }
1513
- and.check = checkAnd;
1514
- and.guards = guards;
1515
- return and;
1516
- }
1517
- function checkOr(state, {
1518
- context,
1519
- event
1520
- }, {
1521
- guards
1522
- }) {
1523
- return guards.some(guard => evaluateGuard(guard, context, event, state));
1524
- }
1525
- function or(guards) {
1526
- function or(_) {
1527
- return false;
1528
- }
1529
- or.check = checkOr;
1530
- or.guards = guards;
1531
- return or;
1532
- }
1533
-
1534
- // TODO: throw on cycles (depth check should be enough)
1535
- function evaluateGuard(guard, context, event, state) {
1536
- const {
1537
- machine
1538
- } = state;
1539
- const isInline = typeof guard === 'function';
1540
- const resolved = isInline ? guard : machine.implementations.guards[typeof guard === 'string' ? guard : guard.type];
1541
- if (!isInline && !resolved) {
1542
- throw new Error(`Guard '${typeof guard === 'string' ? guard : guard.type}' is not implemented.'.`);
1543
- }
1544
- if (typeof resolved !== 'function') {
1545
- return evaluateGuard(resolved, context, event, state);
1546
- }
1547
- const guardArgs = {
1548
- context,
1549
- event,
1550
- guard: isInline ? undefined : typeof guard === 'string' ? {
1551
- type: guard
1552
- } : guard
1553
- };
1554
- if (!('check' in resolved)) {
1555
- // the existing type of `.guards` assumes non-nullable `TExpressionGuard`
1556
- // inline guards expect `TExpressionGuard` to be set to `undefined`
1557
- // it's fine to cast this here, our logic makes sure that we call those 2 "variants" correctly
1558
- return resolved(guardArgs);
1559
- }
1560
- const builtinGuard = resolved;
1561
- return builtinGuard.check(state, guardArgs, resolved // this holds all params
1562
- );
1563
- }
1564
-
1565
- function getOutput(configuration, context, event, self) {
1566
- const machine = configuration[0].machine;
1567
- const finalChildStateNode = configuration.find(stateNode => stateNode.type === 'final' && stateNode.parent === machine.root);
1568
- return finalChildStateNode && finalChildStateNode.output ? mapContext(finalChildStateNode.output, context, event, self) : undefined;
1569
- }
1570
- const isAtomicStateNode = stateNode => stateNode.type === 'atomic' || stateNode.type === 'final';
1571
- function getChildren(stateNode) {
1572
- return Object.values(stateNode.states).filter(sn => sn.type !== 'history');
1573
- }
1574
- function getProperAncestors(stateNode, toStateNode) {
1575
- const ancestors = [];
1576
-
1577
- // add all ancestors
1578
- let m = stateNode.parent;
1579
- while (m && m !== toStateNode) {
1580
- ancestors.push(m);
1581
- m = m.parent;
1582
- }
1583
- return ancestors;
1584
- }
1585
- function getConfiguration(stateNodes) {
1586
- const configuration = new Set(stateNodes);
1587
- const configurationSet = new Set(stateNodes);
1588
- const adjList = getAdjList(configurationSet);
1589
-
1590
- // add descendants
1591
- for (const s of configuration) {
1592
- // if previously active, add existing child nodes
1593
- if (s.type === 'compound' && (!adjList.get(s) || !adjList.get(s).length)) {
1594
- getInitialStateNodes(s).forEach(sn => configurationSet.add(sn));
1595
- } else {
1596
- if (s.type === 'parallel') {
1597
- for (const child of getChildren(s)) {
1598
- if (child.type === 'history') {
1599
- continue;
1600
- }
1601
- if (!configurationSet.has(child)) {
1602
- for (const initialStateNode of getInitialStateNodes(child)) {
1603
- configurationSet.add(initialStateNode);
1604
- }
1605
- }
1606
- }
1607
- }
1608
- }
1609
- }
1610
-
1611
- // add all ancestors
1612
- for (const s of configurationSet) {
1613
- let m = s.parent;
1614
- while (m) {
1615
- configurationSet.add(m);
1616
- m = m.parent;
1617
- }
1618
- }
1619
- return configurationSet;
1620
- }
1621
- function getValueFromAdj(baseNode, adjList) {
1622
- const childStateNodes = adjList.get(baseNode);
1623
- if (!childStateNodes) {
1624
- return {}; // todo: fix?
1625
- }
1626
-
1627
- if (baseNode.type === 'compound') {
1628
- const childStateNode = childStateNodes[0];
1629
- if (childStateNode) {
1630
- if (isAtomicStateNode(childStateNode)) {
1631
- return childStateNode.key;
1632
- }
1633
- } else {
1634
- return {};
1635
- }
1636
- }
1637
- const stateValue = {};
1638
- for (const childStateNode of childStateNodes) {
1639
- stateValue[childStateNode.key] = getValueFromAdj(childStateNode, adjList);
1640
- }
1641
- return stateValue;
1642
- }
1643
- function getAdjList(configuration) {
1644
- const adjList = new Map();
1645
- for (const s of configuration) {
1646
- if (!adjList.has(s)) {
1647
- adjList.set(s, []);
1648
- }
1649
- if (s.parent) {
1650
- if (!adjList.has(s.parent)) {
1651
- adjList.set(s.parent, []);
1652
- }
1653
- adjList.get(s.parent).push(s);
1654
- }
1655
- }
1656
- return adjList;
1657
- }
1658
- function getStateValue(rootNode, configuration) {
1659
- const config = getConfiguration(configuration);
1660
- return getValueFromAdj(rootNode, getAdjList(config));
1661
- }
1662
- function isInFinalState(configuration, stateNode = configuration[0].machine.root) {
1663
- if (stateNode.type === 'compound') {
1664
- return getChildren(stateNode).some(s => s.type === 'final' && configuration.includes(s));
1665
- }
1666
- if (stateNode.type === 'parallel') {
1667
- return getChildren(stateNode).every(sn => isInFinalState(configuration, sn));
1668
- }
1669
- return false;
1670
- }
1671
- const isStateId = str => str[0] === STATE_IDENTIFIER;
1672
- function getCandidates(stateNode, receivedEventType) {
1673
- const candidates = stateNode.transitions.get(receivedEventType) || [...stateNode.transitions.keys()].filter(descriptor => {
1674
- // check if transition is a wildcard transition,
1675
- // which matches any non-transient events
1676
- if (descriptor === WILDCARD) {
1677
- return true;
1678
- }
1679
- if (!descriptor.endsWith('.*')) {
1680
- return false;
1681
- }
1682
- const partialEventTokens = descriptor.split('.');
1683
- const eventTokens = receivedEventType.split('.');
1684
- for (let tokenIndex = 0; tokenIndex < partialEventTokens.length; tokenIndex++) {
1685
- const partialEventToken = partialEventTokens[tokenIndex];
1686
- const eventToken = eventTokens[tokenIndex];
1687
- if (partialEventToken === '*') {
1688
- const isLastToken = tokenIndex === partialEventTokens.length - 1;
1689
- return isLastToken;
1690
- }
1691
- if (partialEventToken !== eventToken) {
1692
- return false;
1693
- }
1694
- }
1695
- return true;
1696
- }).sort((a, b) => b.length - a.length).flatMap(key => stateNode.transitions.get(key));
1697
- return candidates;
1698
- }
1699
-
1700
- /**
1701
- * All delayed transitions from the config.
1702
- */
1703
- function getDelayedTransitions(stateNode) {
1704
- const afterConfig = stateNode.config.after;
1705
- if (!afterConfig) {
1706
- return [];
1707
- }
1708
- const mutateEntryExit = (delay, i) => {
1709
- const delayRef = typeof delay === 'function' ? `${stateNode.id}:delay[${i}]` : delay;
1710
- const eventType = after(delayRef, stateNode.id);
1711
- stateNode.entry.push(raise({
1712
- type: eventType
1713
- }, {
1714
- id: eventType,
1715
- delay
1716
- }));
1717
- stateNode.exit.push(cancel(eventType));
1718
- return eventType;
1719
- };
1720
- const delayedTransitions = isArray(afterConfig) ? afterConfig.map((transition, i) => {
1721
- const eventType = mutateEntryExit(transition.delay, i);
1722
- return {
1723
- ...transition,
1724
- event: eventType
1725
- };
1726
- }) : Object.keys(afterConfig).flatMap((delay, i) => {
1727
- const configTransition = afterConfig[delay];
1728
- const resolvedTransition = typeof configTransition === 'string' ? {
1729
- target: configTransition
1730
- } : configTransition;
1731
- const resolvedDelay = !isNaN(+delay) ? +delay : delay;
1732
- const eventType = mutateEntryExit(resolvedDelay, i);
1733
- return toArray(resolvedTransition).map(transition => ({
1734
- ...transition,
1735
- event: eventType,
1736
- delay: resolvedDelay
1737
- }));
1738
- });
1739
- return delayedTransitions.map(delayedTransition => {
1740
- const {
1741
- delay
1742
- } = delayedTransition;
1743
- return {
1744
- ...formatTransition(stateNode, delayedTransition.event, delayedTransition),
1745
- delay
1746
- };
1747
- });
1748
- }
1749
- function formatTransition(stateNode, descriptor, transitionConfig) {
1750
- const normalizedTarget = normalizeTarget(transitionConfig.target);
1751
- const reenter = transitionConfig.reenter ?? false;
1752
- const target = resolveTarget(stateNode, normalizedTarget);
1753
- const transition = {
1754
- ...transitionConfig,
1755
- actions: toArray(transitionConfig.actions),
1756
- guard: transitionConfig.guard,
1757
- target,
1758
- source: stateNode,
1759
- reenter,
1760
- eventType: descriptor,
1761
- toJSON: () => ({
1762
- ...transition,
1763
- source: `#${stateNode.id}`,
1764
- target: target ? target.map(t => `#${t.id}`) : undefined
1765
- })
1766
- };
1767
- return transition;
1768
- }
1769
- function formatTransitions(stateNode) {
1770
- const transitions = new Map();
1771
- if (stateNode.config.on) {
1772
- for (const descriptor of Object.keys(stateNode.config.on)) {
1773
- if (descriptor === NULL_EVENT) {
1774
- throw new Error('Null events ("") cannot be specified as a transition key. Use `always: { ... }` instead.');
1775
- }
1776
- const transitionsConfig = stateNode.config.on[descriptor];
1777
- transitions.set(descriptor, toTransitionConfigArray(transitionsConfig).map(t => formatTransition(stateNode, descriptor, t)));
1778
- }
1779
- }
1780
- if (stateNode.config.onDone) {
1781
- const descriptor = String(done(stateNode.id));
1782
- transitions.set(descriptor, toTransitionConfigArray(stateNode.config.onDone).map(t => formatTransition(stateNode, descriptor, t)));
1783
- }
1784
- for (const invokeDef of stateNode.invoke) {
1785
- if (invokeDef.onDone) {
1786
- const descriptor = `done.invoke.${invokeDef.id}`;
1787
- transitions.set(descriptor, toTransitionConfigArray(invokeDef.onDone).map(t => formatTransition(stateNode, descriptor, t)));
1788
- }
1789
- if (invokeDef.onError) {
1790
- const descriptor = `error.platform.${invokeDef.id}`;
1791
- transitions.set(descriptor, toTransitionConfigArray(invokeDef.onError).map(t => formatTransition(stateNode, descriptor, t)));
1792
- }
1793
- if (invokeDef.onSnapshot) {
1794
- const descriptor = `xstate.snapshot.${invokeDef.id}`;
1795
- transitions.set(descriptor, toTransitionConfigArray(invokeDef.onSnapshot).map(t => formatTransition(stateNode, descriptor, t)));
1796
- }
1797
- }
1798
- for (const delayedTransition of stateNode.after) {
1799
- let existing = transitions.get(delayedTransition.eventType);
1800
- if (!existing) {
1801
- existing = [];
1802
- transitions.set(delayedTransition.eventType, existing);
1803
- }
1804
- existing.push(delayedTransition);
1805
- }
1806
- return transitions;
1807
- }
1808
- function formatInitialTransition(stateNode, _target) {
1809
- if (typeof _target === 'string' || isArray(_target)) {
1810
- const targets = toArray(_target).map(t => {
1811
- // Resolve state string keys (which represent children)
1812
- // to their state node
1813
- const descStateNode = typeof t === 'string' ? isStateId(t) ? stateNode.machine.getStateNodeById(t) : stateNode.states[t] : t;
1814
- if (!descStateNode) {
1815
- throw new Error(`Initial state node "${t}" not found on parent state node #${stateNode.id}`);
1816
- }
1817
- if (!isDescendant(descStateNode, stateNode)) {
1818
- throw new Error(`Invalid initial target: state node #${descStateNode.id} is not a descendant of #${stateNode.id}`);
1819
- }
1820
- return descStateNode;
1821
- });
1822
- const resolvedTarget = resolveTarget(stateNode, targets);
1823
- const transition = {
1824
- source: stateNode,
1825
- actions: [],
1826
- eventType: null,
1827
- reenter: false,
1828
- target: resolvedTarget,
1829
- toJSON: () => ({
1830
- ...transition,
1831
- source: `#${stateNode.id}`,
1832
- target: resolvedTarget ? resolvedTarget.map(t => `#${t.id}`) : undefined
1833
- })
1834
- };
1835
- return transition;
1836
- }
1837
- return formatTransition(stateNode, '__INITIAL__', {
1838
- target: toArray(_target.target).map(t => {
1839
- if (typeof t === 'string') {
1840
- return isStateId(t) ? t : `${STATE_DELIMITER}${t}`;
1841
- }
1842
- return t;
1843
- }),
1844
- actions: _target.actions
1845
- });
1846
- }
1847
- function resolveTarget(stateNode, targets) {
1848
- if (targets === undefined) {
1849
- // an undefined target signals that the state node should not transition from that state when receiving that event
1850
- return undefined;
1851
- }
1852
- return targets.map(target => {
1853
- if (typeof target !== 'string') {
1854
- return target;
1855
- }
1856
- if (isStateId(target)) {
1857
- return stateNode.machine.getStateNodeById(target);
1858
- }
1859
- const isInternalTarget = target[0] === STATE_DELIMITER;
1860
- // If internal target is defined on machine,
1861
- // do not include machine key on target
1862
- if (isInternalTarget && !stateNode.parent) {
1863
- return getStateNodeByPath(stateNode, target.slice(1));
1864
- }
1865
- const resolvedTarget = isInternalTarget ? stateNode.key + target : target;
1866
- if (stateNode.parent) {
1867
- try {
1868
- const targetStateNode = getStateNodeByPath(stateNode.parent, resolvedTarget);
1869
- return targetStateNode;
1870
- } catch (err) {
1871
- throw new Error(`Invalid transition definition for state node '${stateNode.id}':\n${err.message}`);
1872
- }
1873
- } else {
1874
- throw new Error(`Invalid target: "${target}" is not a valid target from the root node. Did you mean ".${target}"?`);
1875
- }
1876
- });
1877
- }
1878
- function resolveHistoryTarget(stateNode) {
1879
- const normalizedTarget = normalizeTarget(stateNode.target);
1880
- if (!normalizedTarget) {
1881
- return stateNode.parent.initial.target;
1882
- }
1883
- return normalizedTarget.map(t => typeof t === 'string' ? getStateNodeByPath(stateNode.parent, t) : t);
1884
- }
1885
- function isHistoryNode(stateNode) {
1886
- return stateNode.type === 'history';
1887
- }
1888
- function getInitialStateNodes(stateNode) {
1889
- const set = new Set();
1890
- function iter(descStateNode) {
1891
- if (set.has(descStateNode)) {
1892
- return;
1893
- }
1894
- set.add(descStateNode);
1895
- if (descStateNode.type === 'compound') {
1896
- for (const targetStateNode of descStateNode.initial.target) {
1897
- for (const a of getProperAncestors(targetStateNode, stateNode)) {
1898
- set.add(a);
1899
- }
1900
- iter(targetStateNode);
1901
- }
1902
- } else if (descStateNode.type === 'parallel') {
1903
- for (const child of getChildren(descStateNode)) {
1904
- iter(child);
1905
- }
1906
- }
1907
- }
1908
- iter(stateNode);
1909
- return [...set];
1910
- }
1911
- /**
1912
- * Returns the child state node from its relative `stateKey`, or throws.
1913
- */
1914
- function getStateNode(stateNode, stateKey) {
1915
- if (isStateId(stateKey)) {
1916
- return stateNode.machine.getStateNodeById(stateKey);
1917
- }
1918
- if (!stateNode.states) {
1919
- throw new Error(`Unable to retrieve child state '${stateKey}' from '${stateNode.id}'; no child states exist.`);
1920
- }
1921
- const result = stateNode.states[stateKey];
1922
- if (!result) {
1923
- throw new Error(`Child state '${stateKey}' does not exist on '${stateNode.id}'`);
1924
- }
1925
- return result;
1926
- }
1927
-
1928
- /**
1929
- * Returns the relative state node from the given `statePath`, or throws.
1930
- *
1931
- * @param statePath The string or string array relative path to the state node.
1932
- */
1933
- function getStateNodeByPath(stateNode, statePath) {
1934
- if (typeof statePath === 'string' && isStateId(statePath)) {
1935
- try {
1936
- return stateNode.machine.getStateNodeById(statePath);
1937
- } catch (e) {
1938
- // try individual paths
1939
- // throw e;
1940
- }
1941
- }
1942
- const arrayStatePath = toStatePath(statePath).slice();
1943
- let currentStateNode = stateNode;
1944
- while (arrayStatePath.length) {
1945
- const key = arrayStatePath.shift();
1946
- if (!key.length) {
1947
- break;
1948
- }
1949
- currentStateNode = getStateNode(currentStateNode, key);
1950
- }
1951
- return currentStateNode;
1952
- }
1953
-
1954
- /**
1955
- * Returns the state nodes represented by the current state value.
1956
- *
1957
- * @param state The state value or State instance
1958
- */
1959
- function getStateNodes(stateNode, state) {
1960
- const stateValue = state instanceof State ? state.value : toStateValue(state);
1961
- if (typeof stateValue === 'string') {
1962
- return [stateNode, stateNode.states[stateValue]];
1963
- }
1964
- const childStateKeys = Object.keys(stateValue);
1965
- const childStateNodes = childStateKeys.map(subStateKey => getStateNode(stateNode, subStateKey)).filter(Boolean);
1966
- return [stateNode.machine.root, stateNode].concat(childStateNodes, childStateKeys.reduce((allSubStateNodes, subStateKey) => {
1967
- const subStateNode = getStateNode(stateNode, subStateKey);
1968
- if (!subStateNode) {
1969
- return allSubStateNodes;
1970
- }
1971
- const subStateNodes = getStateNodes(subStateNode, stateValue[subStateKey]);
1972
- return allSubStateNodes.concat(subStateNodes);
1973
- }, []));
1974
- }
1975
- function transitionAtomicNode(stateNode, stateValue, state, event) {
1976
- const childStateNode = getStateNode(stateNode, stateValue);
1977
- const next = childStateNode.next(state, event);
1978
- if (!next || !next.length) {
1979
- return stateNode.next(state, event);
1980
- }
1981
- return next;
1982
- }
1983
- function transitionCompoundNode(stateNode, stateValue, state, event) {
1984
- const subStateKeys = Object.keys(stateValue);
1985
- const childStateNode = getStateNode(stateNode, subStateKeys[0]);
1986
- const next = transitionNode(childStateNode, stateValue[subStateKeys[0]], state, event);
1987
- if (!next || !next.length) {
1988
- return stateNode.next(state, event);
1989
- }
1990
- return next;
1991
- }
1992
- function transitionParallelNode(stateNode, stateValue, state, event) {
1993
- const allInnerTransitions = [];
1994
- for (const subStateKey of Object.keys(stateValue)) {
1995
- const subStateValue = stateValue[subStateKey];
1996
- if (!subStateValue) {
1997
- continue;
1998
- }
1999
- const subStateNode = getStateNode(stateNode, subStateKey);
2000
- const innerTransitions = transitionNode(subStateNode, subStateValue, state, event);
2001
- if (innerTransitions) {
2002
- allInnerTransitions.push(...innerTransitions);
2003
- }
2004
- }
2005
- if (!allInnerTransitions.length) {
2006
- return stateNode.next(state, event);
2007
- }
2008
- return allInnerTransitions;
2009
- }
2010
- function transitionNode(stateNode, stateValue, state, event) {
2011
- // leaf node
2012
- if (typeof stateValue === 'string') {
2013
- return transitionAtomicNode(stateNode, stateValue, state, event);
2014
- }
2015
-
2016
- // compound node
2017
- if (Object.keys(stateValue).length === 1) {
2018
- return transitionCompoundNode(stateNode, stateValue, state, event);
2019
- }
2020
-
2021
- // parallel node
2022
- return transitionParallelNode(stateNode, stateValue, state, event);
2023
- }
2024
- function getHistoryNodes(stateNode) {
2025
- return Object.keys(stateNode.states).map(key => stateNode.states[key]).filter(sn => sn.type === 'history');
2026
- }
2027
- function isDescendant(childStateNode, parentStateNode) {
2028
- let marker = childStateNode;
2029
- while (marker.parent && marker.parent !== parentStateNode) {
2030
- marker = marker.parent;
2031
- }
2032
- return marker.parent === parentStateNode;
2033
- }
2034
- function getPathFromRootToNode(stateNode) {
2035
- const path = [];
2036
- let marker = stateNode.parent;
2037
- while (marker) {
2038
- path.unshift(marker);
2039
- marker = marker.parent;
2040
- }
2041
- return path;
2042
- }
2043
- function hasIntersection(s1, s2) {
2044
- const set1 = new Set(s1);
2045
- const set2 = new Set(s2);
2046
- for (const item of set1) {
2047
- if (set2.has(item)) {
2048
- return true;
2049
- }
2050
- }
2051
- for (const item of set2) {
2052
- if (set1.has(item)) {
2053
- return true;
2054
- }
2055
- }
2056
- return false;
2057
- }
2058
- function removeConflictingTransitions(enabledTransitions, configuration, historyValue) {
2059
- const filteredTransitions = new Set();
2060
- for (const t1 of enabledTransitions) {
2061
- let t1Preempted = false;
2062
- const transitionsToRemove = new Set();
2063
- for (const t2 of filteredTransitions) {
2064
- if (hasIntersection(computeExitSet([t1], configuration, historyValue), computeExitSet([t2], configuration, historyValue))) {
2065
- if (isDescendant(t1.source, t2.source)) {
2066
- transitionsToRemove.add(t2);
2067
- } else {
2068
- t1Preempted = true;
2069
- break;
2070
- }
2071
- }
2072
- }
2073
- if (!t1Preempted) {
2074
- for (const t3 of transitionsToRemove) {
2075
- filteredTransitions.delete(t3);
2076
- }
2077
- filteredTransitions.add(t1);
2078
- }
2079
- }
2080
- return Array.from(filteredTransitions);
2081
- }
2082
- function findLCCA(stateNodes) {
2083
- const [head] = stateNodes;
2084
- let current = getPathFromRootToNode(head);
2085
- let candidates = [];
2086
- for (const stateNode of stateNodes) {
2087
- const path = getPathFromRootToNode(stateNode);
2088
- candidates = current.filter(sn => path.includes(sn));
2089
- current = candidates;
2090
- candidates = [];
2091
- }
2092
- return current[current.length - 1];
2093
- }
2094
- function getEffectiveTargetStates(transition, historyValue) {
2095
- if (!transition.target) {
2096
- return [];
2097
- }
2098
- const targets = new Set();
2099
- for (const targetNode of transition.target) {
2100
- if (isHistoryNode(targetNode)) {
2101
- if (historyValue[targetNode.id]) {
2102
- for (const node of historyValue[targetNode.id]) {
2103
- targets.add(node);
2104
- }
2105
- } else {
2106
- for (const node of getEffectiveTargetStates({
2107
- target: resolveHistoryTarget(targetNode)
2108
- }, historyValue)) {
2109
- targets.add(node);
2110
- }
2111
- }
2112
- } else {
2113
- targets.add(targetNode);
2114
- }
2115
- }
2116
- return [...targets];
2117
- }
2118
- function getTransitionDomain(transition, historyValue) {
2119
- const targetStates = getEffectiveTargetStates(transition, historyValue);
2120
- if (!targetStates) {
2121
- return null;
2122
- }
2123
- if (!transition.reenter && transition.source.type !== 'parallel' && targetStates.every(targetStateNode => isDescendant(targetStateNode, transition.source))) {
2124
- return transition.source;
2125
- }
2126
- const lcca = findLCCA(targetStates.concat(transition.source));
2127
- return lcca;
2128
- }
2129
- function computeExitSet(transitions, configuration, historyValue) {
2130
- const statesToExit = new Set();
2131
- for (const t of transitions) {
2132
- if (t.target?.length) {
2133
- const domain = getTransitionDomain(t, historyValue);
2134
- for (const stateNode of configuration) {
2135
- if (isDescendant(stateNode, domain)) {
2136
- statesToExit.add(stateNode);
2137
- }
2138
- }
2139
- }
2140
- }
2141
- return [...statesToExit];
2142
- }
2143
-
2144
- /**
2145
- * https://www.w3.org/TR/scxml/#microstepProcedure
2146
- *
2147
- * @private
2148
- * @param transitions
2149
- * @param currentState
2150
- * @param mutConfiguration
2151
- */
2152
-
2153
- function microstep(transitions, currentState, actorCtx, event, isInitial) {
2154
- const mutConfiguration = new Set(currentState.configuration);
2155
- if (!transitions.length) {
2156
- return currentState;
2157
- }
2158
- const microstate = microstepProcedure(transitions, currentState, mutConfiguration, event, actorCtx, isInitial);
2159
- return cloneState(microstate, {
2160
- value: {} // TODO: make optional
2161
- });
2162
- }
2163
-
2164
- function microstepProcedure(transitions, currentState, mutConfiguration, event, actorCtx, isInitial) {
2165
- const actions = [];
2166
- const historyValue = {
2167
- ...currentState.historyValue
2168
- };
2169
- const filteredTransitions = removeConflictingTransitions(transitions, mutConfiguration, historyValue);
2170
- const internalQueue = [...currentState._internalQueue];
2171
-
2172
- // Exit states
2173
- if (!isInitial) {
2174
- exitStates(filteredTransitions, mutConfiguration, historyValue, actions);
2175
- }
2176
-
2177
- // Execute transition content
2178
- actions.push(...filteredTransitions.flatMap(t => t.actions));
2179
-
2180
- // Enter states
2181
- enterStates(event, filteredTransitions, mutConfiguration, actions, internalQueue, currentState, historyValue, isInitial, actorCtx);
2182
- const nextConfiguration = [...mutConfiguration];
2183
- const done = isInFinalState(nextConfiguration);
2184
- if (done) {
2185
- const finalActions = nextConfiguration.sort((a, b) => b.order - a.order).flatMap(state => state.exit);
2186
- actions.push(...finalActions);
2187
- }
2188
- try {
2189
- const nextState = resolveActionsAndContext(actions, event, currentState, actorCtx);
2190
- const output = done ? getOutput(nextConfiguration, nextState.context, event, actorCtx.self) : undefined;
2191
- internalQueue.push(...nextState._internalQueue);
2192
- return cloneState(currentState, {
2193
- configuration: nextConfiguration,
2194
- historyValue,
2195
- _internalQueue: internalQueue,
2196
- context: nextState.context,
2197
- done,
2198
- output,
2199
- children: nextState.children
2200
- });
2201
- } catch (e) {
2202
- // TODO: Refactor this once proper error handling is implemented.
2203
- // See https://github.com/statelyai/rfcs/pull/4
2204
- throw e;
2205
- }
2206
- }
2207
- function enterStates(event, filteredTransitions, mutConfiguration, actions, internalQueue, currentState, historyValue, isInitial, actorContext) {
2208
- const statesToEnter = new Set();
2209
- const statesForDefaultEntry = new Set();
2210
- computeEntrySet(filteredTransitions, historyValue, statesForDefaultEntry, statesToEnter);
2211
-
2212
- // In the initial state, the root state node is "entered".
2213
- if (isInitial) {
2214
- statesForDefaultEntry.add(currentState.machine.root);
2215
- }
2216
- for (const stateNodeToEnter of [...statesToEnter].sort((a, b) => a.order - b.order)) {
2217
- mutConfiguration.add(stateNodeToEnter);
2218
- for (const invokeDef of stateNodeToEnter.invoke) {
2219
- actions.push(invoke(invokeDef));
2220
- }
2221
-
2222
- // Add entry actions
2223
- actions.push(...stateNodeToEnter.entry);
2224
- if (statesForDefaultEntry.has(stateNodeToEnter)) {
2225
- for (const stateNode of statesForDefaultEntry) {
2226
- const initialActions = stateNode.initial.actions;
2227
- actions.push(...initialActions);
2228
- }
2229
- }
2230
- if (stateNodeToEnter.type === 'final') {
2231
- const parent = stateNodeToEnter.parent;
2232
- if (!parent.parent) {
2233
- continue;
2234
- }
2235
- internalQueue.push(done(parent.id, stateNodeToEnter.output ? mapContext(stateNodeToEnter.output, currentState.context, event, actorContext.self) : undefined));
2236
- if (parent.parent) {
2237
- const grandparent = parent.parent;
2238
- if (grandparent.type === 'parallel') {
2239
- if (getChildren(grandparent).every(parentNode => isInFinalState([...mutConfiguration], parentNode))) {
2240
- internalQueue.push(done(grandparent.id));
2241
- }
2242
- }
2243
- }
2244
- }
2245
- }
2246
- }
2247
- function computeEntrySet(transitions, historyValue, statesForDefaultEntry, statesToEnter) {
2248
- for (const t of transitions) {
2249
- for (const s of t.target || []) {
2250
- addDescendantStatesToEnter(s, historyValue, statesForDefaultEntry, statesToEnter);
2251
- }
2252
- const ancestor = getTransitionDomain(t, historyValue);
2253
- const targetStates = getEffectiveTargetStates(t, historyValue);
2254
- for (const s of targetStates) {
2255
- addAncestorStatesToEnter(s, ancestor, statesToEnter, historyValue, statesForDefaultEntry);
2256
- }
2257
- }
2258
- }
2259
- function addDescendantStatesToEnter(stateNode, historyValue, statesForDefaultEntry, statesToEnter) {
2260
- if (isHistoryNode(stateNode)) {
2261
- if (historyValue[stateNode.id]) {
2262
- const historyStateNodes = historyValue[stateNode.id];
2263
- for (const s of historyStateNodes) {
2264
- addDescendantStatesToEnter(s, historyValue, statesForDefaultEntry, statesToEnter);
2265
- }
2266
- for (const s of historyStateNodes) {
2267
- addAncestorStatesToEnter(s, stateNode.parent, statesToEnter, historyValue, statesForDefaultEntry);
2268
- for (const stateForDefaultEntry of statesForDefaultEntry) {
2269
- statesForDefaultEntry.add(stateForDefaultEntry);
2270
- }
2271
- }
2272
- } else {
2273
- const targets = resolveHistoryTarget(stateNode);
2274
- for (const s of targets) {
2275
- addDescendantStatesToEnter(s, historyValue, statesForDefaultEntry, statesToEnter);
2276
- }
2277
- for (const s of targets) {
2278
- addAncestorStatesToEnter(s, stateNode, statesToEnter, historyValue, statesForDefaultEntry);
2279
- for (const stateForDefaultEntry of statesForDefaultEntry) {
2280
- statesForDefaultEntry.add(stateForDefaultEntry);
2281
- }
2282
- }
2283
- }
2284
- } else {
2285
- statesToEnter.add(stateNode);
2286
- if (stateNode.type === 'compound') {
2287
- statesForDefaultEntry.add(stateNode);
2288
- const initialStates = stateNode.initial.target;
2289
- for (const initialState of initialStates) {
2290
- addDescendantStatesToEnter(initialState, historyValue, statesForDefaultEntry, statesToEnter);
2291
- }
2292
- for (const initialState of initialStates) {
2293
- addAncestorStatesToEnter(initialState, stateNode, statesToEnter, historyValue, statesForDefaultEntry);
2294
- }
2295
- } else {
2296
- if (stateNode.type === 'parallel') {
2297
- for (const child of getChildren(stateNode).filter(sn => !isHistoryNode(sn))) {
2298
- if (![...statesToEnter].some(s => isDescendant(s, child))) {
2299
- addDescendantStatesToEnter(child, historyValue, statesForDefaultEntry, statesToEnter);
2300
- }
2301
- }
2302
- }
2303
- }
2304
- }
2305
- }
2306
- function addAncestorStatesToEnter(stateNode, toStateNode, statesToEnter, historyValue, statesForDefaultEntry) {
2307
- const properAncestors = getProperAncestors(stateNode, toStateNode);
2308
- for (const anc of properAncestors) {
2309
- statesToEnter.add(anc);
2310
- if (anc.type === 'parallel') {
2311
- for (const child of getChildren(anc).filter(sn => !isHistoryNode(sn))) {
2312
- if (![...statesToEnter].some(s => isDescendant(s, child))) {
2313
- addDescendantStatesToEnter(child, historyValue, statesForDefaultEntry, statesToEnter);
2314
- }
2315
- }
2316
- }
2317
- }
2318
- }
2319
- function exitStates(transitions, mutConfiguration, historyValue, actions) {
2320
- const statesToExit = computeExitSet(transitions, mutConfiguration, historyValue);
2321
- statesToExit.sort((a, b) => b.order - a.order);
2322
-
2323
- // From SCXML algorithm: https://www.w3.org/TR/scxml/#exitStates
2324
- for (const exitStateNode of statesToExit) {
2325
- for (const historyNode of getHistoryNodes(exitStateNode)) {
2326
- let predicate;
2327
- if (historyNode.history === 'deep') {
2328
- predicate = sn => isAtomicStateNode(sn) && isDescendant(sn, exitStateNode);
2329
- } else {
2330
- predicate = sn => {
2331
- return sn.parent === exitStateNode;
2332
- };
2333
- }
2334
- historyValue[historyNode.id] = Array.from(mutConfiguration).filter(predicate);
2335
- }
2336
- }
2337
- for (const s of statesToExit) {
2338
- actions.push(...s.exit, ...s.invoke.map(def => stop(def.id)));
2339
- mutConfiguration.delete(s);
2340
- }
2341
- }
2342
- function resolveActionsAndContext(actions, event, currentState, actorCtx) {
2343
- const {
2344
- machine
2345
- } = currentState;
2346
- // TODO: this `cloneState` is really just a hack to prevent infinite loops
2347
- // we need to take another look at how internal queue is managed
2348
- let intermediateState = cloneState(currentState, {
2349
- _internalQueue: []
2350
- });
2351
- for (const action of actions) {
2352
- const isInline = typeof action === 'function';
2353
- const resolved = isInline ? action :
2354
- // the existing type of `.actions` assumes non-nullable `TExpressionAction`
2355
- // it's fine to cast this here to get a common type and lack of errors in the rest of the code
2356
- // our logic below makes sure that we call those 2 "variants" correctly
2357
- machine.implementations.actions[typeof action === 'string' ? action : action.type];
2358
- if (!resolved) {
2359
- continue;
2360
- }
2361
- const actionArgs = {
2362
- context: intermediateState.context,
2363
- event,
2364
- self: actorCtx?.self,
2365
- system: actorCtx?.system,
2366
- action: isInline ? undefined : typeof action === 'string' ? {
2367
- type: action
2368
- } : action
2369
- };
2370
- if (!('resolve' in resolved)) {
2371
- if (actorCtx?.self.status === ActorStatus.Running) {
2372
- resolved(actionArgs);
2373
- } else {
2374
- actorCtx?.defer(() => resolved(actionArgs));
2375
- }
2376
- continue;
2377
- }
2378
- const builtinAction = resolved;
2379
- const [nextState, params, actions] = builtinAction.resolve(actorCtx, intermediateState, actionArgs, resolved // this holds all params
2380
- );
2381
-
2382
- intermediateState = nextState;
2383
- if ('execute' in resolved) {
2384
- if (actorCtx?.self.status === ActorStatus.Running) {
2385
- builtinAction.execute(actorCtx, params);
2386
- } else {
2387
- actorCtx?.defer(builtinAction.execute.bind(null, actorCtx, params));
2388
- }
2389
- }
2390
- if (actions) {
2391
- intermediateState = resolveActionsAndContext(actions, event, intermediateState, actorCtx);
2392
- }
2393
- }
2394
- return intermediateState;
2395
- }
2396
- function macrostep(state, event, actorCtx) {
2397
- let nextState = state;
2398
- const states = [];
2399
-
2400
- // Handle stop event
2401
- if (event.type === stopSignalType) {
2402
- nextState = stopStep(event, nextState, actorCtx);
2403
- states.push(nextState);
2404
- return {
2405
- state: nextState,
2406
- microstates: states
2407
- };
2408
- }
2409
- let nextEvent = event;
2410
-
2411
- // Assume the state is at rest (no raised events)
2412
- // Determine the next state based on the next microstep
2413
- if (nextEvent.type !== INIT_TYPE) {
2414
- const transitions = selectTransitions(nextEvent, nextState);
2415
- nextState = microstep(transitions, state, actorCtx, nextEvent, false);
2416
- states.push(nextState);
2417
- }
2418
- while (!nextState.done) {
2419
- let enabledTransitions = selectEventlessTransitions(nextState, nextEvent);
2420
- if (!enabledTransitions.length) {
2421
- if (!nextState._internalQueue.length) {
2422
- break;
2423
- } else {
2424
- nextEvent = nextState._internalQueue[0];
2425
- const transitions = selectTransitions(nextEvent, nextState);
2426
- nextState = microstep(transitions, nextState, actorCtx, nextEvent, false);
2427
- nextState._internalQueue.shift();
2428
- states.push(nextState);
2429
- }
2430
- } else {
2431
- nextState = microstep(enabledTransitions, nextState, actorCtx, nextEvent, false);
2432
- states.push(nextState);
2433
- }
2434
- }
2435
- if (nextState.done) {
2436
- // Perform the stop step to ensure that child actors are stopped
2437
- stopStep(nextEvent, nextState, actorCtx);
2438
- }
2439
- return {
2440
- state: nextState,
2441
- microstates: states
2442
- };
2443
- }
2444
- function stopStep(event, nextState, actorCtx) {
2445
- const actions = [];
2446
- for (const stateNode of nextState.configuration.sort((a, b) => b.order - a.order)) {
2447
- actions.push(...stateNode.exit);
2448
- }
2449
- for (const child of Object.values(nextState.children)) {
2450
- actions.push(stop(child));
2451
- }
2452
- return resolveActionsAndContext(actions, event, nextState, actorCtx);
2453
- }
2454
- function selectTransitions(event, nextState) {
2455
- return nextState.machine.getTransitionData(nextState, event);
2456
- }
2457
- function selectEventlessTransitions(nextState, event) {
2458
- const enabledTransitionSet = new Set();
2459
- const atomicStates = nextState.configuration.filter(isAtomicStateNode);
2460
- for (const stateNode of atomicStates) {
2461
- loop: for (const s of [stateNode].concat(getProperAncestors(stateNode, null))) {
2462
- if (!s.always) {
2463
- continue;
2464
- }
2465
- for (const transition of s.always) {
2466
- if (transition.guard === undefined || evaluateGuard(transition.guard, nextState.context, event, nextState)) {
2467
- enabledTransitionSet.add(transition);
2468
- break loop;
2469
- }
2470
- }
2471
- }
2472
- }
2473
- return removeConflictingTransitions(Array.from(enabledTransitionSet), new Set(nextState.configuration), nextState.historyValue);
2474
- }
2475
-
2476
- /**
2477
- * Resolves a partial state value with its full representation in the state node's machine.
2478
- *
2479
- * @param stateValue The partial state value to resolve.
2480
- */
2481
- function resolveStateValue(rootNode, stateValue) {
2482
- const configuration = getConfiguration(getStateNodes(rootNode, stateValue));
2483
- return getStateValue(rootNode, [...configuration]);
2484
- }
2485
- function getInitialConfiguration(rootNode) {
2486
- const configuration = [];
2487
- const initialTransition = rootNode.initial;
2488
- const statesToEnter = new Set();
2489
- const statesForDefaultEntry = new Set([rootNode]);
2490
- computeEntrySet([initialTransition], {}, statesForDefaultEntry, statesToEnter);
2491
- for (const stateNodeToEnter of [...statesToEnter].sort((a, b) => a.order - b.order)) {
2492
- configuration.push(stateNodeToEnter);
2493
- }
2494
- return configuration;
2495
- }
2496
-
2497
- class State {
2498
- /**
2499
- * Indicates whether the state is a final state.
2500
- */
2501
-
2502
- /**
2503
- * The output data of the top-level finite state.
2504
- */
2505
-
2506
- /**
2507
- * The enabled state nodes representative of the state value.
2508
- */
2509
-
2510
- /**
2511
- * An object mapping actor names to spawned/invoked actors.
2512
- */
2513
-
2514
- /**
2515
- * Creates a new State instance for the given `stateValue` and `context`.
2516
- * @param stateValue
2517
- * @param context
2518
- */
2519
- static from(stateValue, context = {}, machine) {
2520
- if (stateValue instanceof State) {
2521
- if (stateValue.context !== context) {
2522
- return new State({
2523
- value: stateValue.value,
2524
- context,
2525
- meta: {},
2526
- configuration: [],
2527
- // TODO: fix,
2528
- children: {}
2529
- }, machine);
2530
- }
2531
- return stateValue;
2532
- }
2533
- const configuration = getConfiguration(getStateNodes(machine.root, stateValue));
2534
- return new State({
2535
- value: stateValue,
2536
- context,
2537
- meta: undefined,
2538
- configuration: Array.from(configuration),
2539
- children: {}
2540
- }, machine);
2541
- }
2542
-
2543
- /**
2544
- * Creates a new `State` instance that represents the current state of a running machine.
2545
- *
2546
- * @param config
2547
- */
2548
- constructor(config, machine) {
2549
- this.machine = machine;
2550
- this.tags = void 0;
2551
- this.value = void 0;
2552
- this.done = void 0;
2553
- this.output = void 0;
2554
- this.error = void 0;
2555
- this.context = void 0;
2556
- this.historyValue = {};
2557
- this._internalQueue = void 0;
2558
- this.configuration = void 0;
2559
- this.children = void 0;
2560
- this.context = config.context;
2561
- this._internalQueue = config._internalQueue ?? [];
2562
- this.historyValue = config.historyValue || {};
2563
- this.matches = this.matches.bind(this);
2564
- this.toStrings = this.toStrings.bind(this);
2565
- this.configuration = config.configuration ?? Array.from(getConfiguration(getStateNodes(machine.root, config.value)));
2566
- this.children = config.children;
2567
- this.value = getStateValue(machine.root, this.configuration);
2568
- this.tags = new Set(flatten(this.configuration.map(sn => sn.tags)));
2569
- this.done = config.done ?? false;
2570
- this.output = config.output;
2571
- this.error = config.error;
2572
- }
2573
-
2574
- /**
2575
- * Returns an array of all the string leaf state node paths.
2576
- * @param stateValue
2577
- * @param delimiter The character(s) that separate each subpath in the string state node path.
2578
- */
2579
- toStrings(stateValue = this.value) {
2580
- if (typeof stateValue === 'string') {
2581
- return [stateValue];
2582
- }
2583
- const valueKeys = Object.keys(stateValue);
2584
- return valueKeys.concat(...valueKeys.map(key => this.toStrings(stateValue[key]).map(s => key + STATE_DELIMITER + s)));
2585
- }
2586
- toJSON() {
2587
- const {
2588
- configuration,
2589
- tags,
2590
- machine,
2591
- ...jsonValues
2592
- } = this;
2593
- return {
2594
- ...jsonValues,
2595
- tags: Array.from(tags),
2596
- meta: this.meta
2597
- };
2598
- }
2599
-
2600
- /**
2601
- * Whether the current state value is a subset of the given parent state value.
2602
- * @param parentStateValue
2603
- */
2604
- matches(parentStateValue) {
2605
- return matchesState(parentStateValue, this.value);
2606
- }
2607
-
2608
- /**
2609
- * Whether the current state configuration has a state node with the specified `tag`.
2610
- * @param tag
2611
- */
2612
- hasTag(tag) {
2613
- return this.tags.has(tag);
2614
- }
2615
-
2616
- /**
2617
- * Determines whether sending the `event` will cause a non-forbidden transition
2618
- * to be selected, even if the transitions have no actions nor
2619
- * change the state value.
2620
- *
2621
- * @param event The event to test
2622
- * @returns Whether the event will cause a transition
2623
- */
2624
- can(event) {
2625
- const transitionData = this.machine.getTransitionData(this, event);
2626
- return !!transitionData?.length &&
2627
- // Check that at least one transition is not forbidden
2628
- transitionData.some(t => t.target !== undefined || t.actions.length);
2629
- }
2630
-
2631
- /**
2632
- * The next events that will cause a transition from the current state.
2633
- */
2634
- get nextEvents() {
2635
- return memo(this, 'nextEvents', () => {
2636
- return [...new Set(flatten([...this.configuration.map(sn => sn.ownEvents)]))];
2637
- });
2638
- }
2639
- get meta() {
2640
- return this.configuration.reduce((acc, stateNode) => {
2641
- if (stateNode.meta !== undefined) {
2642
- acc[stateNode.id] = stateNode.meta;
2643
- }
2644
- return acc;
2645
- }, {});
2646
- }
2647
- }
2648
- function cloneState(state, config = {}) {
2649
- return new State({
2650
- ...state,
2651
- ...config
2652
- }, state.machine);
2653
- }
2654
- function getPersistedState(state) {
2655
- const {
2656
- configuration,
2657
- tags,
2658
- machine,
2659
- children,
2660
- ...jsonValues
2661
- } = state;
2662
- const childrenJson = {};
2663
- for (const id in children) {
2664
- childrenJson[id] = {
2665
- state: children[id].getPersistedState?.(),
2666
- src: children[id].src
2667
- };
2668
- }
2669
- return {
2670
- ...jsonValues,
2671
- children: childrenJson
2672
- };
2673
- }
2674
-
2675
- function resolve$5(_, state, args, {
2676
- actorRef
2677
- }) {
2678
- const actorRefOrString = typeof actorRef === 'function' ? actorRef(args) : actorRef;
2679
- const resolvedActorRef = typeof actorRefOrString === 'string' ? state.children[actorRefOrString] : actorRefOrString;
2680
- let children = state.children;
2681
- if (resolvedActorRef) {
2682
- children = {
2683
- ...children
2684
- };
2685
- delete children[resolvedActorRef.id];
2686
- }
2687
- return [cloneState(state, {
2688
- children
2689
- }), resolvedActorRef];
2690
- }
2691
- function execute$2(actorContext, actorRef) {
2692
- if (!actorRef) {
2693
- return;
2694
- }
2695
- if (actorRef.status !== ActorStatus.Running) {
2696
- actorContext.stopChild(actorRef);
2697
- return;
2698
- }
2699
- // TODO: recheck why this one has to be deferred
2700
- actorContext.defer(() => {
2701
- actorContext.stopChild(actorRef);
2702
- });
2703
- }
2704
-
2705
- /**
2706
- * Stops an actor.
2707
- *
2708
- * @param actorRef The actor to stop.
2709
- */
2710
-
2711
- function stop(actorRef) {
2712
- function stop(_) {
2713
- }
2714
- stop.type = 'xstate.stop';
2715
- stop.actorRef = actorRef;
2716
- stop.resolve = resolve$5;
2717
- stop.execute = execute$2;
2718
- return stop;
2719
- }
2720
-
2721
- function resolve$4(_, state, actionArgs, {
2722
- value,
2723
- label
2724
- }) {
2725
- return [state, {
2726
- value: typeof value === 'function' ? value(actionArgs) : value,
2727
- label
2728
- }];
2729
- }
2730
- function execute$1({
2731
- logger
2732
- }, {
2733
- value,
2734
- label
2735
- }) {
2736
- if (label) {
2737
- logger(label, value);
2738
- } else {
2739
- logger(value);
2740
- }
2741
- }
2742
-
2743
- /**
2744
- *
2745
- * @param expr The expression function to evaluate which will be logged.
2746
- * Takes in 2 arguments:
2747
- * - `ctx` - the current state context
2748
- * - `event` - the event that caused this action to be executed.
2749
- * @param label The label to give to the logged expression.
2750
- */
2751
- function log(value = ({
2752
- context,
2753
- event
2754
- }) => ({
2755
- context,
2756
- event
2757
- }), label) {
2758
- function log(_) {
2759
- }
2760
- log.type = 'xstate.log';
2761
- log.value = value;
2762
- log.label = label;
2763
- log.resolve = resolve$4;
2764
- log.execute = execute$1;
2765
- return log;
2766
- }
2767
-
2768
- function createSpawner(actorContext, {
2769
- machine,
2770
- context
2771
- }, event, spawnedChildren) {
2772
- const spawn = (src, options = {}) => {
2773
- const {
2774
- systemId
2775
- } = options;
2776
- if (typeof src === 'string') {
2777
- const referenced = resolveReferencedActor(machine.implementations.actors[src]);
2778
- if (!referenced) {
2779
- throw new Error(`Actor logic '${src}' not implemented in machine '${machine.id}'`);
2780
- }
2781
- const input = 'input' in options ? options.input : referenced.input;
2782
-
2783
- // TODO: this should also receive `src`
2784
- const actor = createActor(referenced.src, {
2785
- id: options.id,
2786
- parent: actorContext.self,
2787
- input: typeof input === 'function' ? input({
2788
- context,
2789
- event,
2790
- self: actorContext.self
2791
- }) : input,
2792
- systemId
2793
- });
2794
- spawnedChildren[actor.id] = actor;
2795
- return actor;
2796
- } else {
2797
- // TODO: this should also receive `src`
2798
- return createActor(src, {
2799
- id: options.id,
2800
- parent: actorContext.self,
2801
- input: options.input,
2802
- systemId
2803
- });
2804
- }
2805
- };
2806
- return (src, options) => {
2807
- const actorRef = spawn(src, options); // TODO: fix types
2808
- spawnedChildren[actorRef.id] = actorRef;
2809
- actorContext.defer(() => {
2810
- if (actorRef.status === ActorStatus.Stopped) {
2811
- return;
2812
- }
2813
- try {
2814
- actorRef.start?.();
2815
- } catch (err) {
2816
- actorContext.self.send(error(actorRef.id, err));
2817
- return;
2818
- }
2819
- });
2820
- return actorRef;
2821
- };
2822
- }
2823
-
2824
- function resolve$3(actorContext, state, actionArgs, {
2825
- assignment
2826
- }) {
2827
- if (!state.context) {
2828
- throw new Error('Cannot assign to undefined `context`. Ensure that `context` is defined in the machine config.');
2829
- }
2830
- const spawnedChildren = {};
2831
- const assignArgs = {
2832
- context: state.context,
2833
- event: actionArgs.event,
2834
- action: actionArgs.action,
2835
- spawn: createSpawner(actorContext, state, actionArgs.event, spawnedChildren),
2836
- self: actorContext?.self,
2837
- system: actorContext?.system
2838
- };
2839
- let partialUpdate = {};
2840
- if (typeof assignment === 'function') {
2841
- partialUpdate = assignment(assignArgs);
2842
- } else {
2843
- for (const key of Object.keys(assignment)) {
2844
- const propAssignment = assignment[key];
2845
- partialUpdate[key] = typeof propAssignment === 'function' ? propAssignment(assignArgs) : propAssignment;
2846
- }
2847
- }
2848
- const updatedContext = Object.assign({}, state.context, partialUpdate);
2849
- return [cloneState(state, {
2850
- context: updatedContext,
2851
- children: Object.keys(spawnedChildren).length ? {
2852
- ...state.children,
2853
- ...spawnedChildren
2854
- } : state.children
2855
- })];
2856
- }
2857
-
2858
- /**
2859
- * Updates the current context of the machine.
2860
- *
2861
- * @param assignment An object that represents the partial context to update.
2862
- */
2863
- function assign(assignment) {
2864
- function assign(_) {
2865
- }
2866
- assign.type = 'xstate.assign';
2867
- assign.assignment = assignment;
2868
- assign.resolve = resolve$3;
2869
- return assign;
2870
- }
2871
-
2872
- function resolve$2(_, state, args, {
2873
- event: eventOrExpr,
2874
- id,
2875
- delay
2876
- }) {
2877
- const delaysMap = state.machine.implementations.delays;
2878
- if (typeof eventOrExpr === 'string') {
2879
- throw new Error(`Only event objects may be used with raise; use raise({ type: "${eventOrExpr}" }) instead`);
2880
- }
2881
- const resolvedEvent = typeof eventOrExpr === 'function' ? eventOrExpr(args) : eventOrExpr;
2882
- let resolvedDelay;
2883
- if (typeof delay === 'string') {
2884
- const configDelay = delaysMap && delaysMap[delay];
2885
- resolvedDelay = typeof configDelay === 'function' ? configDelay(args) : configDelay;
2886
- } else {
2887
- resolvedDelay = typeof delay === 'function' ? delay(args) : delay;
2888
- }
2889
- return [typeof resolvedDelay !== 'number' ? cloneState(state, {
2890
- _internalQueue: state._internalQueue.concat(resolvedEvent)
2891
- }) : state, {
2892
- event: resolvedEvent,
2893
- id,
2894
- delay: resolvedDelay
2895
- }];
2896
- }
2897
- function execute(actorContext, params) {
2898
- if (typeof params.delay === 'number') {
2899
- actorContext.self.delaySend(params);
2900
- return;
2901
- }
2902
- }
2903
-
2904
- /**
2905
- * Raises an event. This places the event in the internal event queue, so that
2906
- * the event is immediately consumed by the machine in the current step.
2907
- *
2908
- * @param eventType The event to raise.
2909
- */
2910
-
2911
- function raise(eventOrExpr, options) {
2912
- function raise(_) {
2913
- }
2914
- raise.type = 'xstate.raise';
2915
- raise.event = eventOrExpr;
2916
- raise.id = options?.id;
2917
- raise.delay = options?.delay;
2918
- raise.resolve = resolve$2;
2919
- raise.execute = execute;
2920
- return raise;
2921
- }
2922
-
2923
- function resolve$1(_, state, actionArgs, {
2924
- branches
2925
- }) {
2926
- const matchedActions = branches.find(condition => {
2927
- return !condition.guard || evaluateGuard(condition.guard, state.context, actionArgs.event, state);
2928
- })?.actions;
2929
- return [state, undefined, toArray(matchedActions)];
2930
- }
2931
- function choose(branches) {
2932
- function choose(_) {
2933
- }
2934
- choose.type = 'xstate.choose';
2935
- choose.branches = branches;
2936
- choose.resolve = resolve$1;
2937
- return choose;
2938
- }
2939
-
2940
- function resolve(_, state, args, {
2941
- get
2942
- }) {
2943
- return [state, undefined, toArray(get({
2944
- context: args.context,
2945
- event: args.event
2946
- }))];
2947
- }
2948
- function pure(getActions) {
2949
- function pure(_) {
2950
- }
2951
- pure.type = 'xstate.pure';
2952
- pure.get = getActions;
2953
- pure.resolve = resolve;
2954
- return pure;
2955
- }
2956
-
2957
- /**
2958
- * Returns an event type that represents an implicit event that
2959
- * is sent after the specified `delay`.
2960
- *
2961
- * @param delayRef The delay in milliseconds
2962
- * @param id The state node ID where this event is handled
2963
- */
2964
- function after(delayRef, id) {
2965
- const idSuffix = id ? `#${id}` : '';
2966
- return `${ConstantPrefix.After}(${delayRef})${idSuffix}`;
2967
- }
2968
-
2969
- /**
2970
- * Returns an event that represents that a final state node
2971
- * has been reached in the parent state node.
2972
- *
2973
- * @param id The final state node's parent state node `id`
2974
- * @param output The data to pass into the event
2975
- */
2976
- function done(id, output) {
2977
- const type = `${ConstantPrefix.DoneState}.${id}`;
2978
- const eventObject = {
2979
- type,
2980
- output
2981
- };
2982
- eventObject.toString = () => type;
2983
- return eventObject;
2984
- }
2985
-
2986
- /**
2987
- * Returns an event that represents that an invoked service has terminated.
2988
- *
2989
- * An invoked service is terminated when it has reached a top-level final state node,
2990
- * but not when it is canceled.
2991
- *
2992
- * @param invokeId The invoked service ID
2993
- * @param output The data to pass into the event
2994
- */
2995
- function doneInvoke(invokeId, output) {
2996
- const type = `${ConstantPrefix.DoneInvoke}.${invokeId}`;
2997
- const eventObject = {
2998
- type,
2999
- output
3000
- };
3001
- eventObject.toString = () => type;
3002
- return eventObject;
3003
- }
3004
- function error(id, data) {
3005
- const type = `${ConstantPrefix.ErrorPlatform}.${id}`;
3006
- const eventObject = {
3007
- type,
3008
- data
3009
- };
3010
- eventObject.toString = () => type;
3011
- return eventObject;
3012
- }
3013
- function createInitEvent(input) {
3014
- return {
3015
- type: INIT_TYPE,
3016
- input
3017
- };
3018
- }
3019
-
3020
- exports.Actor = Actor;
3021
- exports.ActorStatus = ActorStatus;
3022
- exports.ConstantPrefix = ConstantPrefix;
3023
- exports.InterpreterStatus = InterpreterStatus;
3024
- exports.NULL_EVENT = NULL_EVENT;
3025
- exports.STATE_DELIMITER = STATE_DELIMITER;
3026
- exports.SpecialTargets = SpecialTargets;
3027
- exports.State = State;
3028
- exports.after = after;
3029
- exports.and = and;
3030
- exports.assign = assign;
3031
- exports.cancel = cancel;
3032
- exports.choose = choose;
3033
- exports.cloneState = cloneState;
3034
- exports.constantPrefixes = constantPrefixes;
3035
- exports.createActor = createActor;
3036
- exports.createEmptyActor = createEmptyActor;
3037
- exports.createInitEvent = createInitEvent;
3038
- exports.createInvokeId = createInvokeId;
3039
- exports.done = done;
3040
- exports.doneInvoke = doneInvoke;
3041
- exports.error = error;
3042
- exports.escalate = escalate;
3043
- exports.evaluateGuard = evaluateGuard;
3044
- exports.flatten = flatten;
3045
- exports.formatInitialTransition = formatInitialTransition;
3046
- exports.formatTransition = formatTransition;
3047
- exports.formatTransitions = formatTransitions;
3048
- exports.forwardTo = forwardTo;
3049
- exports.fromCallback = fromCallback;
3050
- exports.fromEventObservable = fromEventObservable;
3051
- exports.fromObservable = fromObservable;
3052
- exports.fromPromise = fromPromise;
3053
- exports.fromTransition = fromTransition;
3054
- exports.getCandidates = getCandidates;
3055
- exports.getConfiguration = getConfiguration;
3056
- exports.getDelayedTransitions = getDelayedTransitions;
3057
- exports.getInitialConfiguration = getInitialConfiguration;
3058
- exports.getPersistedState = getPersistedState;
3059
- exports.getStateNodeByPath = getStateNodeByPath;
3060
- exports.getStateNodes = getStateNodes;
3061
- exports.interpret = interpret;
3062
- exports.isActorRef = isActorRef;
3063
- exports.isAtomicStateNode = isAtomicStateNode;
3064
- exports.isErrorEvent = isErrorEvent;
3065
- exports.isInFinalState = isInFinalState;
3066
- exports.isSignal = isSignal;
3067
- exports.isStateId = isStateId;
3068
- exports.log = log;
3069
- exports.macrostep = macrostep;
3070
- exports.mapValues = mapValues;
3071
- exports.matchesState = matchesState;
3072
- exports.memo = memo;
3073
- exports.microstep = microstep;
3074
- exports.not = not;
3075
- exports.or = or;
3076
- exports.pathToStateValue = pathToStateValue;
3077
- exports.pure = pure;
3078
- exports.raise = raise;
3079
- exports.resolveActionsAndContext = resolveActionsAndContext;
3080
- exports.resolveReferencedActor = resolveReferencedActor;
3081
- exports.resolveStateValue = resolveStateValue;
3082
- exports.sendParent = sendParent;
3083
- exports.sendTo = sendTo;
3084
- exports.startSignal = startSignal;
3085
- exports.startSignalType = startSignalType;
3086
- exports.stateIn = stateIn;
3087
- exports.stop = stop;
3088
- exports.stopSignal = stopSignal;
3089
- exports.stopSignalType = stopSignalType;
3090
- exports.toActorRef = toActorRef;
3091
- exports.toArray = toArray;
3092
- exports.toInvokeConfig = toInvokeConfig;
3093
- exports.toObserver = toObserver;
3094
- exports.toTransitionConfigArray = toTransitionConfigArray;
3095
- exports.transitionNode = transitionNode;