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