xstate 5.0.0-beta.10 → 5.0.0-beta.12

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 (57) hide show
  1. package/actions/dist/xstate-actions.cjs.js +29 -5
  2. package/actions/dist/{xstate-actions.cjs.dev.js → xstate-actions.development.cjs.js} +2 -2
  3. package/actions/dist/xstate-actions.development.esm.js +2 -0
  4. package/actions/dist/xstate-actions.esm.js +2 -2
  5. package/actions/dist/xstate-actions.umd.min.js +1 -1
  6. package/actions/dist/xstate-actions.umd.min.js.map +1 -1
  7. package/actors/dist/xstate-actors.cjs.js +20 -5
  8. package/actors/dist/{xstate-actors.cjs.dev.js → xstate-actors.development.cjs.js} +2 -2
  9. package/actors/dist/xstate-actors.development.esm.js +2 -0
  10. package/actors/dist/xstate-actors.esm.js +2 -2
  11. package/actors/dist/xstate-actors.umd.min.js +1 -1
  12. package/actors/dist/xstate-actors.umd.min.js.map +1 -1
  13. package/dev/dist/xstate-dev.cjs.js +45 -4
  14. package/{dist/index-0f3fdf0c.cjs.prod.js → dev/dist/xstate-dev.development.cjs.js} +6 -7
  15. package/{dist/index-50bd0aff.esm.js → dev/dist/xstate-dev.development.esm.js} +6 -8
  16. package/dev/dist/xstate-dev.esm.js +42 -1
  17. package/dev/dist/xstate-dev.umd.min.js +1 -1
  18. package/dev/dist/xstate-dev.umd.min.js.map +1 -1
  19. package/dist/actions-b34f6ce7.esm.js +3292 -0
  20. package/dist/actions-c8b9504d.development.esm.js +3327 -0
  21. package/dist/actions-d9c19f35.development.cjs.js +3409 -0
  22. package/dist/actions-e4c704f3.cjs.js +3374 -0
  23. package/dist/declarations/src/interpreter.d.ts +1 -6
  24. package/dist/declarations/src/types.d.ts +1 -0
  25. package/dist/declarations/src/utils.d.ts +0 -1
  26. package/dist/declarations/src/waitFor.d.ts +1 -1
  27. package/dist/xstate.cjs.js +802 -4
  28. package/dist/xstate.development.cjs.js +808 -0
  29. package/dist/xstate.development.esm.js +770 -0
  30. package/dist/xstate.esm.js +543 -662
  31. package/dist/xstate.umd.min.js +1 -1
  32. package/dist/xstate.umd.min.js.map +1 -1
  33. package/guards/dist/xstate-guards.cjs.js +13 -5
  34. package/guards/dist/{xstate-guards.cjs.prod.js → xstate-guards.development.cjs.js} +2 -2
  35. package/guards/dist/xstate-guards.development.esm.js +2 -0
  36. package/guards/dist/xstate-guards.esm.js +2 -2
  37. package/guards/dist/xstate-guards.umd.min.js +1 -1
  38. package/guards/dist/xstate-guards.umd.min.js.map +1 -1
  39. package/package.json +52 -1
  40. package/actions/dist/xstate-actions.cjs.prod.js +0 -31
  41. package/actors/dist/xstate-actors.cjs.prod.js +0 -22
  42. package/dev/dist/xstate-dev.cjs.dev.js +0 -11
  43. package/dev/dist/xstate-dev.cjs.prod.js +0 -11
  44. package/dist/actions-109712d3.cjs.dev.js +0 -4357
  45. package/dist/actions-67f1d04e.esm.js +0 -4270
  46. package/dist/actions-d0262a43.cjs.prod.js +0 -4333
  47. package/dist/declarations/actions/dynamicAction.d.ts +0 -5
  48. package/dist/declarations/src/Mailbox.d.ts +0 -12
  49. package/dist/declarations/src/actions/invoke.d.ts +0 -3
  50. package/dist/declarations/src/environment.d.ts +0 -1
  51. package/dist/declarations/src/memo.d.ts +0 -2
  52. package/dist/declarations/src/spawn.d.ts +0 -2
  53. package/dist/declarations/src/system.d.ts +0 -2
  54. package/dist/index-ebaab3c9.cjs.dev.js +0 -52
  55. package/dist/xstate.cjs.dev.js +0 -933
  56. package/dist/xstate.cjs.prod.js +0 -930
  57. package/guards/dist/xstate-guards.cjs.dev.js +0 -15
@@ -1,4270 +0,0 @@
1
- import { I as IS_PRODUCTION, d as devToolsAdapter } from './index-50bd0aff.esm.js';
2
-
3
- // https://github.com/microsoft/TypeScript/issues/23182#issuecomment-379091887
4
-
5
- // TODO: replace in v5 with:
6
- // export type IndexByType<T extends { type: string }> = { [E in T as E['type']]: E; };
7
-
8
- /**
9
- * The full definition of an event, with a string `type`.
10
- */
11
-
12
- // TODO: do not accept machines without all implementations
13
- // we should also accept a raw machine as a behavior here
14
- // or just make machine a behavior
15
-
16
- // TODO: narrow this to behaviors from machine
17
-
18
- // TODO: fix last param
19
-
20
- /**
21
- * Extracts action objects that have no extra properties.
22
- */
23
-
24
- /**
25
- * The string or object representing the state value relative to the parent state node.
26
- *
27
- * - For a child atomic state node, this is a string, e.g., `"pending"`.
28
- * - For complex state nodes, this is an object, e.g., `{ success: "someChildState" }`.
29
- */
30
-
31
- // TODO: remove once TS fixes this type-widening issue
32
-
33
- // TODO: possibly refactor this somehow, use even a simpler type, and maybe even make `machine.options` private or something
34
-
35
- var ActionTypes;
36
- (function (ActionTypes) {
37
- ActionTypes["Stop"] = "xstate.stop";
38
- ActionTypes["Raise"] = "xstate.raise";
39
- ActionTypes["Send"] = "xstate.send";
40
- ActionTypes["Cancel"] = "xstate.cancel";
41
- ActionTypes["Assign"] = "xstate.assign";
42
- ActionTypes["After"] = "xstate.after";
43
- ActionTypes["DoneState"] = "done.state";
44
- ActionTypes["DoneInvoke"] = "done.invoke";
45
- ActionTypes["Log"] = "xstate.log";
46
- ActionTypes["Init"] = "xstate.init";
47
- ActionTypes["Invoke"] = "xstate.invoke";
48
- ActionTypes["ErrorExecution"] = "error.execution";
49
- ActionTypes["ErrorCommunication"] = "error.communication";
50
- ActionTypes["ErrorPlatform"] = "error.platform";
51
- ActionTypes["ErrorCustom"] = "xstate.error";
52
- ActionTypes["Pure"] = "xstate.pure";
53
- ActionTypes["Choose"] = "xstate.choose";
54
- })(ActionTypes || (ActionTypes = {}));
55
- var SpecialTargets;
56
- (function (SpecialTargets) {
57
- SpecialTargets["Parent"] = "#_parent";
58
- SpecialTargets["Internal"] = "#_internal";
59
- })(SpecialTargets || (SpecialTargets = {}));
60
-
61
- // xstate-specific action types
62
- var stop$1 = ActionTypes.Stop;
63
- var raise$1 = ActionTypes.Raise;
64
- var send$1 = ActionTypes.Send;
65
- var cancel$1 = ActionTypes.Cancel;
66
- var assign$1 = ActionTypes.Assign;
67
- var after$1 = ActionTypes.After;
68
- var doneState = ActionTypes.DoneState;
69
- var log$1 = ActionTypes.Log;
70
- var init = ActionTypes.Init;
71
- var invoke$1 = ActionTypes.Invoke;
72
- var errorExecution = ActionTypes.ErrorExecution;
73
- var errorPlatform = ActionTypes.ErrorPlatform;
74
- var error$1 = ActionTypes.ErrorCustom;
75
- var choose$1 = ActionTypes.Choose;
76
- var pure$1 = ActionTypes.Pure;
77
-
78
- var actionTypes = /*#__PURE__*/Object.freeze({
79
- __proto__: null,
80
- stop: stop$1,
81
- raise: raise$1,
82
- send: send$1,
83
- cancel: cancel$1,
84
- assign: assign$1,
85
- after: after$1,
86
- doneState: doneState,
87
- log: log$1,
88
- init: init,
89
- invoke: invoke$1,
90
- errorExecution: errorExecution,
91
- errorPlatform: errorPlatform,
92
- error: error$1,
93
- choose: choose$1,
94
- pure: pure$1
95
- });
96
-
97
- function _toPrimitive(input, hint) {
98
- if (typeof input !== "object" || input === null) return input;
99
- var prim = input[Symbol.toPrimitive];
100
- if (prim !== undefined) {
101
- var res = prim.call(input, hint || "default");
102
- if (typeof res !== "object") return res;
103
- throw new TypeError("@@toPrimitive must return a primitive value.");
104
- }
105
- return (hint === "string" ? String : Number)(input);
106
- }
107
-
108
- function _toPropertyKey(arg) {
109
- var key = _toPrimitive(arg, "string");
110
- return typeof key === "symbol" ? key : String(key);
111
- }
112
-
113
- function _defineProperty(obj, key, value) {
114
- key = _toPropertyKey(key);
115
- if (key in obj) {
116
- Object.defineProperty(obj, key, {
117
- value: value,
118
- enumerable: true,
119
- configurable: true,
120
- writable: true
121
- });
122
- } else {
123
- obj[key] = value;
124
- }
125
- return obj;
126
- }
127
-
128
- function ownKeys(object, enumerableOnly) {
129
- var keys = Object.keys(object);
130
- if (Object.getOwnPropertySymbols) {
131
- var symbols = Object.getOwnPropertySymbols(object);
132
- enumerableOnly && (symbols = symbols.filter(function (sym) {
133
- return Object.getOwnPropertyDescriptor(object, sym).enumerable;
134
- })), keys.push.apply(keys, symbols);
135
- }
136
- return keys;
137
- }
138
- function _objectSpread2(target) {
139
- for (var i = 1; i < arguments.length; i++) {
140
- var source = null != arguments[i] ? arguments[i] : {};
141
- i % 2 ? ownKeys(Object(source), !0).forEach(function (key) {
142
- _defineProperty(target, key, source[key]);
143
- }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) {
144
- Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
145
- });
146
- }
147
- return target;
148
- }
149
-
150
- function _arrayWithHoles(arr) {
151
- if (Array.isArray(arr)) return arr;
152
- }
153
-
154
- function _iterableToArrayLimit(arr, i) {
155
- var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"];
156
- if (null != _i) {
157
- var _s,
158
- _e,
159
- _x,
160
- _r,
161
- _arr = [],
162
- _n = !0,
163
- _d = !1;
164
- try {
165
- if (_x = (_i = _i.call(arr)).next, 0 === i) {
166
- if (Object(_i) !== _i) return;
167
- _n = !1;
168
- } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0);
169
- } catch (err) {
170
- _d = !0, _e = err;
171
- } finally {
172
- try {
173
- if (!_n && null != _i.return && (_r = _i.return(), Object(_r) !== _r)) return;
174
- } finally {
175
- if (_d) throw _e;
176
- }
177
- }
178
- return _arr;
179
- }
180
- }
181
-
182
- function _arrayLikeToArray(arr, len) {
183
- if (len == null || len > arr.length) len = arr.length;
184
- for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
185
- return arr2;
186
- }
187
-
188
- function _unsupportedIterableToArray(o, minLen) {
189
- if (!o) return;
190
- if (typeof o === "string") return _arrayLikeToArray(o, minLen);
191
- var n = Object.prototype.toString.call(o).slice(8, -1);
192
- if (n === "Object" && o.constructor) n = o.constructor.name;
193
- if (n === "Map" || n === "Set") return Array.from(o);
194
- if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
195
- }
196
-
197
- function _nonIterableRest() {
198
- throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
199
- }
200
-
201
- function _slicedToArray(arr, i) {
202
- return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest();
203
- }
204
-
205
- function _arrayWithoutHoles(arr) {
206
- if (Array.isArray(arr)) return _arrayLikeToArray(arr);
207
- }
208
-
209
- function _iterableToArray(iter) {
210
- if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
211
- }
212
-
213
- function _nonIterableSpread() {
214
- throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
215
- }
216
-
217
- function _toConsumableArray(arr) {
218
- return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();
219
- }
220
-
221
- function _createForOfIteratorHelper(o, allowArrayLike) {
222
- var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"];
223
- if (!it) {
224
- if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") {
225
- if (it) o = it;
226
- var i = 0;
227
- var F = function () {};
228
- return {
229
- s: F,
230
- n: function () {
231
- if (i >= o.length) return {
232
- done: true
233
- };
234
- return {
235
- done: false,
236
- value: o[i++]
237
- };
238
- },
239
- e: function (e) {
240
- throw e;
241
- },
242
- f: F
243
- };
244
- }
245
- throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
246
- }
247
- var normalCompletion = true,
248
- didErr = false,
249
- err;
250
- return {
251
- s: function () {
252
- it = it.call(o);
253
- },
254
- n: function () {
255
- var step = it.next();
256
- normalCompletion = step.done;
257
- return step;
258
- },
259
- e: function (e) {
260
- didErr = true;
261
- err = e;
262
- },
263
- f: function () {
264
- try {
265
- if (!normalCompletion && it.return != null) it.return();
266
- } finally {
267
- if (didErr) throw err;
268
- }
269
- }
270
- };
271
- }
272
-
273
- function _typeof(obj) {
274
- "@babel/helpers - typeof";
275
-
276
- return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) {
277
- return typeof obj;
278
- } : function (obj) {
279
- return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
280
- }, _typeof(obj);
281
- }
282
-
283
- var STATE_DELIMITER = '.';
284
- var TARGETLESS_KEY = '';
285
- var NULL_EVENT = '';
286
- var STATE_IDENTIFIER = '#';
287
- var WILDCARD = '*';
288
-
289
- function matchesState(parentStateId, childStateId) {
290
- var delimiter = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : STATE_DELIMITER;
291
- var parentStateValue = toStateValue(parentStateId, delimiter);
292
- var childStateValue = toStateValue(childStateId, delimiter);
293
- if (isString(childStateValue)) {
294
- if (isString(parentStateValue)) {
295
- return childStateValue === parentStateValue;
296
- }
297
-
298
- // Parent more specific than child
299
- return false;
300
- }
301
- if (isString(parentStateValue)) {
302
- return parentStateValue in childStateValue;
303
- }
304
- return Object.keys(parentStateValue).every(function (key) {
305
- if (!(key in childStateValue)) {
306
- return false;
307
- }
308
- return matchesState(parentStateValue[key], childStateValue[key]);
309
- });
310
- }
311
- function toStatePath(stateId, delimiter) {
312
- try {
313
- if (isArray(stateId)) {
314
- return stateId;
315
- }
316
- return stateId.toString().split(delimiter);
317
- } catch (e) {
318
- throw new Error("'".concat(stateId, "' is not a valid state path."));
319
- }
320
- }
321
- function isStateLike(state) {
322
- return _typeof(state) === 'object' && 'value' in state && 'context' in state && 'event' in state;
323
- }
324
- function toStateValue(stateValue, delimiter) {
325
- if (isStateLike(stateValue)) {
326
- return stateValue.value;
327
- }
328
- if (isArray(stateValue)) {
329
- return pathToStateValue(stateValue);
330
- }
331
- if (typeof stateValue !== 'string') {
332
- return stateValue;
333
- }
334
- var statePath = toStatePath(stateValue, delimiter);
335
- return pathToStateValue(statePath);
336
- }
337
- function pathToStateValue(statePath) {
338
- if (statePath.length === 1) {
339
- return statePath[0];
340
- }
341
- var value = {};
342
- var marker = value;
343
- for (var _i = 0; _i < statePath.length - 1; _i++) {
344
- if (_i === statePath.length - 2) {
345
- marker[statePath[_i]] = statePath[_i + 1];
346
- } else {
347
- marker[statePath[_i]] = {};
348
- marker = marker[statePath[_i]];
349
- }
350
- }
351
- return value;
352
- }
353
- function mapValues(collection, iteratee) {
354
- var result = {};
355
- var collectionKeys = Object.keys(collection);
356
- for (var _i2 = 0; _i2 < collectionKeys.length; _i2++) {
357
- var _key = collectionKeys[_i2];
358
- result[_key] = iteratee(collection[_key], _key, collection, _i2);
359
- }
360
- return result;
361
- }
362
- function flatten(array) {
363
- var _ref;
364
- return (_ref = []).concat.apply(_ref, _toConsumableArray(array));
365
- }
366
- function toArrayStrict(value) {
367
- if (isArray(value)) {
368
- return value;
369
- }
370
- return [value];
371
- }
372
- function toArray(value) {
373
- if (value === undefined) {
374
- return [];
375
- }
376
- return toArrayStrict(value);
377
- }
378
- function mapContext(mapper, context, event) {
379
- if (isFunction(mapper)) {
380
- return mapper({
381
- context: context,
382
- event: event
383
- });
384
- }
385
- var result = {};
386
- var args = {
387
- context: context,
388
- event: event
389
- };
390
- for (var _i4 = 0, _Object$keys2 = Object.keys(mapper); _i4 < _Object$keys2.length; _i4++) {
391
- var _key3 = _Object$keys2[_i4];
392
- var subMapper = mapper[_key3];
393
- if (isFunction(subMapper)) {
394
- result[_key3] = subMapper(args);
395
- } else {
396
- result[_key3] = subMapper;
397
- }
398
- }
399
- return result;
400
- }
401
- function isPromiseLike(value) {
402
- if (value instanceof Promise) {
403
- return true;
404
- }
405
- // Check if shape matches the Promise/A+ specification for a "thenable".
406
- if (value !== null && (isFunction(value) || _typeof(value) === 'object') && isFunction(value.then)) {
407
- return true;
408
- }
409
- return false;
410
- }
411
-
412
- // tslint:disable-next-line:no-empty
413
- var warn = function warn() {};
414
- if (!IS_PRODUCTION) {
415
- warn = function warn(condition, message) {
416
- var error = condition instanceof Error ? condition : undefined;
417
- if (!error && condition) {
418
- return;
419
- }
420
- if (console !== undefined) {
421
- var args = ["Warning: ".concat(message)];
422
- if (error) {
423
- args.push(error);
424
- }
425
- // tslint:disable-next-line:no-console
426
- console.warn.apply(console, args);
427
- }
428
- };
429
- }
430
- function isArray(value) {
431
- return Array.isArray(value);
432
- }
433
-
434
- // tslint:disable-next-line:ban-types
435
- function isFunction(value) {
436
- return typeof value === 'function';
437
- }
438
- function isString(value) {
439
- return typeof value === 'string';
440
- }
441
- function isErrorEvent(event) {
442
- return typeof event.type === 'string' && (event.type === errorExecution || event.type.startsWith(errorPlatform));
443
- }
444
- function toTransitionConfigArray(event, configLike) {
445
- var transitions = toArrayStrict(configLike).map(function (transitionLike) {
446
- if (typeof transitionLike === 'undefined' || typeof transitionLike === 'string') {
447
- return {
448
- target: transitionLike,
449
- event: event
450
- };
451
- }
452
- return _objectSpread2(_objectSpread2({}, transitionLike), {}, {
453
- event: event
454
- });
455
- });
456
- return transitions;
457
- }
458
- function normalizeTarget(target) {
459
- if (target === undefined || target === TARGETLESS_KEY) {
460
- return undefined;
461
- }
462
- return toArray(target);
463
- }
464
- function toInvokeConfig(invocable, id) {
465
- if (_typeof(invocable) === 'object') {
466
- if ('src' in invocable) {
467
- return invocable;
468
- }
469
- if ('transition' in invocable) {
470
- return {
471
- id: id,
472
- src: invocable
473
- };
474
- }
475
- }
476
- return {
477
- id: id,
478
- src: invocable
479
- };
480
- }
481
- function toObserver(nextHandler, errorHandler, completionHandler) {
482
- var noop = function noop() {};
483
- var isObserver = _typeof(nextHandler) === 'object';
484
- var self = isObserver ? nextHandler : null;
485
- return {
486
- next: ((isObserver ? nextHandler.next : nextHandler) || noop).bind(self),
487
- error: ((isObserver ? nextHandler.error : errorHandler) || noop).bind(self),
488
- complete: ((isObserver ? nextHandler.complete : completionHandler) || noop).bind(self)
489
- };
490
- }
491
- function createInvokeId(stateNodeId, index) {
492
- return "".concat(stateNodeId, ":invocation[").concat(index, "]");
493
- }
494
- function resolveReferencedActor(referenced) {
495
- return referenced ? 'transition' in referenced ? {
496
- src: referenced,
497
- input: undefined
498
- } : referenced : undefined;
499
- }
500
-
501
- function createDynamicAction(action, resolve) {
502
- return {
503
- type: action.type,
504
- params: action.params,
505
- resolve: resolve
506
- };
507
- }
508
- function isDynamicAction(action) {
509
- return _typeof(action) === 'object' && action !== null && 'resolve' in action;
510
- }
511
-
512
- /**
513
- * Sends an event. This returns an action that will be read by an interpreter to
514
- * send the event in the next step, after the current step is finished executing.
515
- *
516
- * @deprecated Use the `sendTo(...)` action creator instead.
517
- *
518
- * @param eventOrExpr The event to send.
519
- * @param options Options to pass into the send event:
520
- * - `id` - The unique send event identifier (used with `cancel()`).
521
- * - `delay` - The number of milliseconds to delay the sending of the event.
522
- * - `to` - The target of this event (by default, the machine the event was sent from).
523
- */
524
- function send(eventOrExpr, options) {
525
- return createDynamicAction({
526
- type: send$1,
527
- params: {
528
- to: options ? options.to : undefined,
529
- delay: options ? options.delay : undefined,
530
- event: eventOrExpr,
531
- id: options && options.id !== undefined ? options.id : isFunction(eventOrExpr) ? eventOrExpr.name : eventOrExpr.type
532
- }
533
- }, function (event, _ref) {
534
- var _actorContext$self;
535
- var actorContext = _ref.actorContext,
536
- state = _ref.state;
537
- var params = {
538
- to: options ? options.to : undefined,
539
- delay: options ? options.delay : undefined,
540
- event: eventOrExpr,
541
- // TODO: don't auto-generate IDs here like that
542
- // there is too big chance of the ID collision
543
- id: options && options.id !== undefined ? options.id : isFunction(eventOrExpr) ? eventOrExpr.name : eventOrExpr.type
544
- };
545
- var args = {
546
- context: state.context,
547
- event: event,
548
- self: (_actorContext$self = actorContext === null || actorContext === void 0 ? void 0 : actorContext.self) !== null && _actorContext$self !== void 0 ? _actorContext$self : null,
549
- system: actorContext === null || actorContext === void 0 ? void 0 : actorContext.system
550
- };
551
- var delaysMap = state.machine.options.delays;
552
-
553
- // TODO: helper function for resolving Expr
554
- if (typeof eventOrExpr === 'string') {
555
- throw new Error("Only event objects may be used with sendTo; use sendTo({ type: \"".concat(eventOrExpr, "\" }) instead"));
556
- }
557
- var resolvedEvent = isFunction(eventOrExpr) ? eventOrExpr(args) : eventOrExpr;
558
- var resolvedDelay;
559
- if (isString(params.delay)) {
560
- var configDelay = delaysMap && delaysMap[params.delay];
561
- resolvedDelay = isFunction(configDelay) ? configDelay(args) : configDelay;
562
- } else {
563
- resolvedDelay = isFunction(params.delay) ? params.delay(args) : params.delay;
564
- }
565
- var resolvedTarget = isFunction(params.to) ? params.to(args) : params.to;
566
- var targetActorRef;
567
- if (typeof resolvedTarget === 'string') {
568
- if (resolvedTarget === SpecialTargets.Parent) {
569
- targetActorRef = actorContext === null || actorContext === void 0 ? void 0 : actorContext.self._parent;
570
- } else if (resolvedTarget === SpecialTargets.Internal) {
571
- targetActorRef = actorContext === null || actorContext === void 0 ? void 0 : actorContext.self;
572
- } else if (resolvedTarget.startsWith('#_')) {
573
- // SCXML compatibility: https://www.w3.org/TR/scxml/#SCXMLEventProcessor
574
- // #_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.
575
- targetActorRef = state.children[resolvedTarget.slice(2)];
576
- } else {
577
- targetActorRef = state.children[resolvedTarget];
578
- }
579
- if (!targetActorRef) {
580
- throw new Error("Unable to send event to actor '".concat(resolvedTarget, "' from machine '").concat(state.machine.id, "'."));
581
- }
582
- } else {
583
- targetActorRef = resolvedTarget || (actorContext === null || actorContext === void 0 ? void 0 : actorContext.self);
584
- }
585
- var resolvedAction = {
586
- type: send$1,
587
- params: _objectSpread2(_objectSpread2({}, params), {}, {
588
- to: targetActorRef,
589
- event: resolvedEvent,
590
- delay: resolvedDelay,
591
- internal: resolvedTarget === SpecialTargets.Internal
592
- }),
593
- execute: function execute(actorCtx) {
594
- var sendAction = resolvedAction;
595
- if (typeof sendAction.params.delay === 'number') {
596
- actorCtx.self.delaySend(sendAction);
597
- return;
598
- } else {
599
- var target = sendAction.params.to;
600
- var sentEvent = sendAction.params.event;
601
- actorCtx.defer(function () {
602
- target.send(sentEvent.type === error$1 ? {
603
- type: "".concat(error(actorCtx.self.id)),
604
- data: sentEvent.data
605
- } : sendAction.params.event);
606
- });
607
- }
608
- }
609
- };
610
- return [state, resolvedAction];
611
- });
612
- }
613
-
614
- /**
615
- * Sends an event to this machine's parent.
616
- *
617
- * @param event The event to send to the parent machine.
618
- * @param options Options to pass into the send event.
619
- */
620
- function sendParent(event, options) {
621
- return send(event, _objectSpread2(_objectSpread2({}, options), {}, {
622
- to: SpecialTargets.Parent
623
- }));
624
- }
625
-
626
- /**
627
- * Forwards (sends) an event to a specified service.
628
- *
629
- * @param target The target service to forward the event to.
630
- * @param options Options to pass into the send action creator.
631
- */
632
- function forwardTo(target, options) {
633
- if (process.env.NODE_ENV !== 'production' && (!target || typeof target === 'function')) {
634
- var originalTarget = target;
635
- target = function target() {
636
- var resolvedTarget = typeof originalTarget === 'function' ? originalTarget.apply(void 0, arguments) : originalTarget;
637
- if (!resolvedTarget) {
638
- throw new Error("Attempted to forward event to undefined actor. This risks an infinite loop in the sender.");
639
- }
640
- return resolvedTarget;
641
- };
642
- }
643
- return send(function (_ref2) {
644
- var event = _ref2.event;
645
- return event;
646
- }, _objectSpread2(_objectSpread2({}, options), {}, {
647
- to: target
648
- }));
649
- }
650
-
651
- /**
652
- * Escalates an error by sending it as an event to this machine's parent.
653
- *
654
- * @param errorData The error data to send, or the expression function that
655
- * takes in the `context`, `event`, and `meta`, and returns the error data to send.
656
- * @param options Options to pass into the send action creator.
657
- */
658
- function escalate(errorData, options) {
659
- return sendParent(function (arg) {
660
- return {
661
- type: error$1,
662
- data: isFunction(errorData) ? errorData(arg) : errorData
663
- };
664
- }, _objectSpread2(_objectSpread2({}, options), {}, {
665
- to: SpecialTargets.Parent
666
- }));
667
- }
668
-
669
- /**
670
- * Sends an event to an actor.
671
- *
672
- * @param actor The `ActorRef` to send the event to.
673
- * @param event The event to send, or an expression that evaluates to the event to send
674
- * @param options Send action options
675
- * @returns An XState send action object
676
- */
677
- function sendTo(actor, event, options) {
678
- return send(event, _objectSpread2(_objectSpread2({}, options), {}, {
679
- to: actor
680
- }));
681
- }
682
-
683
- function _classCallCheck(instance, Constructor) {
684
- if (!(instance instanceof Constructor)) {
685
- throw new TypeError("Cannot call a class as a function");
686
- }
687
- }
688
-
689
- function _defineProperties(target, props) {
690
- for (var i = 0; i < props.length; i++) {
691
- var descriptor = props[i];
692
- descriptor.enumerable = descriptor.enumerable || false;
693
- descriptor.configurable = true;
694
- if ("value" in descriptor) descriptor.writable = true;
695
- Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor);
696
- }
697
- }
698
- function _createClass(Constructor, protoProps, staticProps) {
699
- if (protoProps) _defineProperties(Constructor.prototype, protoProps);
700
- if (staticProps) _defineProperties(Constructor, staticProps);
701
- Object.defineProperty(Constructor, "prototype", {
702
- writable: false
703
- });
704
- return Constructor;
705
- }
706
-
707
- var Mailbox = /*#__PURE__*/function () {
708
- function Mailbox(_process) {
709
- _classCallCheck(this, Mailbox);
710
- this._process = _process;
711
- _defineProperty(this, "_active", false);
712
- _defineProperty(this, "_current", null);
713
- _defineProperty(this, "_last", null);
714
- }
715
- _createClass(Mailbox, [{
716
- key: "start",
717
- value: function start() {
718
- this._active = true;
719
- this.flush();
720
- }
721
- }, {
722
- key: "clear",
723
- value: function clear() {
724
- // we can't set _current to null because we might be currently processing
725
- // and enqueue following clear shouldnt start processing the enqueued item immediately
726
- if (this._current) {
727
- this._current.next = null;
728
- this._last = this._current;
729
- }
730
- }
731
-
732
- // TODO: rethink this design
733
- }, {
734
- key: "prepend",
735
- value: function prepend(event) {
736
- if (!this._current) {
737
- this.enqueue(event);
738
- return;
739
- }
740
-
741
- // we know that something is already queued up
742
- // so the mailbox is already flushing or it's inactive
743
- // therefore the only thing that we need to do is to reassign `this._current`
744
- this._current = {
745
- value: event,
746
- next: this._current
747
- };
748
- }
749
- }, {
750
- key: "enqueue",
751
- value: function enqueue(event) {
752
- var enqueued = {
753
- value: event,
754
- next: null
755
- };
756
- if (this._current) {
757
- this._last.next = enqueued;
758
- this._last = enqueued;
759
- return;
760
- }
761
- this._current = enqueued;
762
- this._last = enqueued;
763
- if (this._active) {
764
- this.flush();
765
- }
766
- }
767
- }, {
768
- key: "flush",
769
- value: function flush() {
770
- while (this._current) {
771
- // atm the given _process is responsible for implementing proper try/catch handling
772
- // we assume here that this won't throw in a way that can affect this mailbox
773
- var consumed = this._current;
774
- this._process(consumed.value);
775
- // something could have been prepended in the meantime
776
- // so we need to be defensive here to avoid skipping over a prepended item
777
- if (consumed === this._current) {
778
- this._current = this._current.next;
779
- }
780
- }
781
- this._last = null;
782
- }
783
- }]);
784
- return Mailbox;
785
- }();
786
-
787
- var symbolObservable = function () {
788
- return typeof Symbol === 'function' && Symbol.observable || '@@observable';
789
- }();
790
-
791
- /**
792
- * Returns an actor behavior from a transition function and its initial state.
793
- *
794
- * A transition function is a function that takes the current state and an event and returns the next state.
795
- *
796
- * @param transition The transition function that returns the next state given the current state and event.
797
- * @param initialState The initial state of the transition function.
798
- * @returns An actor behavior
799
- */
800
- function fromTransition(_transition, initialState) {
801
- var behavior = {
802
- config: _transition,
803
- transition: function transition(state, event, actorContext) {
804
- return _transition(state, event, actorContext);
805
- },
806
- getInitialState: function getInitialState(_, input) {
807
- return typeof initialState === 'function' ? initialState({
808
- input: input
809
- }) : initialState;
810
- },
811
- getSnapshot: function getSnapshot(state) {
812
- return state;
813
- },
814
- getPersistedState: function getPersistedState(state) {
815
- return state;
816
- },
817
- restoreState: function restoreState(state) {
818
- return state;
819
- }
820
- };
821
- return behavior;
822
- }
823
-
824
- function fromPromise(
825
- // TODO: add types
826
- promiseCreator) {
827
- var resolveEventType = '$$xstate.resolve';
828
- var rejectEventType = '$$xstate.reject';
829
-
830
- // TODO: add event types
831
- var behavior = {
832
- config: promiseCreator,
833
- transition: function transition(state, event) {
834
- if (state.status !== 'active') {
835
- return state;
836
- }
837
- switch (event.type) {
838
- case resolveEventType:
839
- return _objectSpread2(_objectSpread2({}, state), {}, {
840
- status: 'done',
841
- data: event.data,
842
- input: undefined
843
- });
844
- case rejectEventType:
845
- return _objectSpread2(_objectSpread2({}, state), {}, {
846
- status: 'error',
847
- data: event.data,
848
- input: undefined
849
- });
850
- case stopSignalType:
851
- return _objectSpread2(_objectSpread2({}, state), {}, {
852
- status: 'canceled',
853
- input: undefined
854
- });
855
- default:
856
- return state;
857
- }
858
- },
859
- start: function start(state, _ref) {
860
- var self = _ref.self;
861
- // TODO: determine how to allow customizing this so that promises
862
- // can be restarted if necessary
863
- if (state.status !== 'active') {
864
- return;
865
- }
866
- var resolvedPromise = Promise.resolve(promiseCreator({
867
- input: state.input
868
- }));
869
- resolvedPromise.then(function (response) {
870
- // TODO: remove this condition once dead letter queue lands
871
- if (self._state.status !== 'active') {
872
- return;
873
- }
874
- self.send({
875
- type: resolveEventType,
876
- data: response
877
- });
878
- }, function (errorData) {
879
- // TODO: remove this condition once dead letter queue lands
880
- if (self._state.status !== 'active') {
881
- return;
882
- }
883
- self.send({
884
- type: rejectEventType,
885
- data: errorData
886
- });
887
- });
888
- },
889
- getInitialState: function getInitialState(_, input) {
890
- return {
891
- status: 'active',
892
- data: undefined,
893
- input: input
894
- };
895
- },
896
- getSnapshot: function getSnapshot(state) {
897
- return state.data;
898
- },
899
- getStatus: function getStatus(state) {
900
- return state;
901
- },
902
- getPersistedState: function getPersistedState(state) {
903
- return state;
904
- },
905
- restoreState: function restoreState(state) {
906
- return state;
907
- }
908
- };
909
- return behavior;
910
- }
911
-
912
- // TODO: this likely shouldn't accept TEvent, observable actor doesn't accept external events
913
- function fromObservable(observableCreator) {
914
- var nextEventType = '$$xstate.next';
915
- var errorEventType = '$$xstate.error';
916
- var completeEventType = '$$xstate.complete';
917
-
918
- // TODO: add event types
919
- var behavior = {
920
- config: observableCreator,
921
- transition: function transition(state, event, _ref) {
922
- var self = _ref.self,
923
- id = _ref.id,
924
- defer = _ref.defer;
925
- if (state.status !== 'active') {
926
- return state;
927
- }
928
- switch (event.type) {
929
- case nextEventType:
930
- // match the exact timing of events sent by machines
931
- // send actions are not executed immediately
932
- defer(function () {
933
- var _self$_parent;
934
- (_self$_parent = self._parent) === null || _self$_parent === void 0 ? void 0 : _self$_parent.send({
935
- type: "xstate.snapshot.".concat(id),
936
- data: event.data
937
- });
938
- });
939
- return _objectSpread2(_objectSpread2({}, state), {}, {
940
- data: event.data
941
- });
942
- case errorEventType:
943
- return _objectSpread2(_objectSpread2({}, state), {}, {
944
- status: 'error',
945
- input: undefined,
946
- data: event.data,
947
- subscription: undefined
948
- });
949
- case completeEventType:
950
- return _objectSpread2(_objectSpread2({}, state), {}, {
951
- status: 'done',
952
- input: undefined,
953
- subscription: undefined
954
- });
955
- case stopSignalType:
956
- state.subscription.unsubscribe();
957
- return _objectSpread2(_objectSpread2({}, state), {}, {
958
- status: 'canceled',
959
- input: undefined,
960
- subscription: undefined
961
- });
962
- default:
963
- return state;
964
- }
965
- },
966
- getInitialState: function getInitialState(_, input) {
967
- return {
968
- subscription: undefined,
969
- status: 'active',
970
- data: undefined,
971
- input: input
972
- };
973
- },
974
- start: function start(state, _ref2) {
975
- var self = _ref2.self;
976
- if (state.status === 'done') {
977
- // Do not restart a completed observable
978
- return;
979
- }
980
- state.subscription = observableCreator({
981
- input: state.input
982
- }).subscribe({
983
- next: function next(value) {
984
- self.send({
985
- type: nextEventType,
986
- data: value
987
- });
988
- },
989
- error: function error(err) {
990
- self.send({
991
- type: errorEventType,
992
- data: err
993
- });
994
- },
995
- complete: function complete() {
996
- self.send({
997
- type: completeEventType
998
- });
999
- }
1000
- });
1001
- },
1002
- getSnapshot: function getSnapshot(state) {
1003
- return state.data;
1004
- },
1005
- getPersistedState: function getPersistedState(_ref3) {
1006
- var status = _ref3.status,
1007
- data = _ref3.data,
1008
- input = _ref3.input;
1009
- return {
1010
- status: status,
1011
- data: data,
1012
- input: input
1013
- };
1014
- },
1015
- getStatus: function getStatus(state) {
1016
- return state;
1017
- },
1018
- restoreState: function restoreState(state) {
1019
- return _objectSpread2(_objectSpread2({}, state), {}, {
1020
- subscription: undefined
1021
- });
1022
- }
1023
- };
1024
- return behavior;
1025
- }
1026
-
1027
- /**
1028
- * Creates an event observable behavior that listens to an observable
1029
- * that delivers event objects.
1030
- *
1031
- *
1032
- * @param lazyObservable A function that creates an observable
1033
- * @returns An event observable behavior
1034
- */
1035
-
1036
- function fromEventObservable(lazyObservable) {
1037
- var errorEventType = '$$xstate.error';
1038
- var completeEventType = '$$xstate.complete';
1039
-
1040
- // TODO: event types
1041
- var behavior = {
1042
- config: lazyObservable,
1043
- transition: function transition(state, event) {
1044
- if (state.status !== 'active') {
1045
- return state;
1046
- }
1047
- switch (event.type) {
1048
- case errorEventType:
1049
- return _objectSpread2(_objectSpread2({}, state), {}, {
1050
- status: 'error',
1051
- input: undefined,
1052
- data: event.data,
1053
- subscription: undefined
1054
- });
1055
- case completeEventType:
1056
- return _objectSpread2(_objectSpread2({}, state), {}, {
1057
- status: 'done',
1058
- input: undefined,
1059
- subscription: undefined
1060
- });
1061
- case stopSignalType:
1062
- state.subscription.unsubscribe();
1063
- return _objectSpread2(_objectSpread2({}, state), {}, {
1064
- status: 'canceled',
1065
- input: undefined,
1066
- subscription: undefined
1067
- });
1068
- default:
1069
- return state;
1070
- }
1071
- },
1072
- getInitialState: function getInitialState() {
1073
- return {
1074
- subscription: undefined,
1075
- status: 'active',
1076
- data: undefined
1077
- };
1078
- },
1079
- start: function start(state, _ref4) {
1080
- var self = _ref4.self;
1081
- if (state.status === 'done') {
1082
- // Do not restart a completed observable
1083
- return;
1084
- }
1085
- state.subscription = lazyObservable({
1086
- input: state.input
1087
- }).subscribe({
1088
- next: function next(value) {
1089
- var _self$_parent2;
1090
- (_self$_parent2 = self._parent) === null || _self$_parent2 === void 0 ? void 0 : _self$_parent2.send(value);
1091
- },
1092
- error: function error(err) {
1093
- self.send({
1094
- type: errorEventType,
1095
- data: err
1096
- });
1097
- },
1098
- complete: function complete() {
1099
- self.send({
1100
- type: completeEventType
1101
- });
1102
- }
1103
- });
1104
- },
1105
- getSnapshot: function getSnapshot(_) {
1106
- return undefined;
1107
- },
1108
- getPersistedState: function getPersistedState(_ref5) {
1109
- var status = _ref5.status,
1110
- data = _ref5.data,
1111
- input = _ref5.input;
1112
- return {
1113
- status: status,
1114
- data: data,
1115
- input: input
1116
- };
1117
- },
1118
- getStatus: function getStatus(state) {
1119
- return state;
1120
- },
1121
- restoreState: function restoreState(state) {
1122
- return _objectSpread2(_objectSpread2({}, state), {}, {
1123
- subscription: undefined
1124
- });
1125
- }
1126
- };
1127
- return behavior;
1128
- }
1129
-
1130
- function fromCallback(invokeCallback) {
1131
- var behavior = {
1132
- config: invokeCallback,
1133
- start: function start(_state, _ref) {
1134
- var self = _ref.self;
1135
- self.send({
1136
- type: startSignalType
1137
- });
1138
- },
1139
- transition: function transition(state, event, _ref2) {
1140
- var self = _ref2.self,
1141
- id = _ref2.id;
1142
- if (event.type === startSignalType) {
1143
- var sender = function sender(eventForParent) {
1144
- var _self$_parent;
1145
- if (state.canceled) {
1146
- return;
1147
- }
1148
- (_self$_parent = self._parent) === null || _self$_parent === void 0 ? void 0 : _self$_parent.send(eventForParent);
1149
- };
1150
- var receiver = function receiver(newListener) {
1151
- state.receivers.add(newListener);
1152
- };
1153
- state.dispose = invokeCallback(sender, receiver, {
1154
- input: state.input
1155
- });
1156
- if (isPromiseLike(state.dispose)) {
1157
- state.dispose.then(function (resolved) {
1158
- var _self$_parent2;
1159
- (_self$_parent2 = self._parent) === null || _self$_parent2 === void 0 ? void 0 : _self$_parent2.send(doneInvoke(id, resolved));
1160
- state.canceled = true;
1161
- }, function (errorData) {
1162
- var _self$_parent3;
1163
- state.canceled = true;
1164
- (_self$_parent3 = self._parent) === null || _self$_parent3 === void 0 ? void 0 : _self$_parent3.send(error(id, errorData));
1165
- });
1166
- }
1167
- return state;
1168
- }
1169
- if (event.type === stopSignalType) {
1170
- state.canceled = true;
1171
- if (isFunction(state.dispose)) {
1172
- state.dispose();
1173
- }
1174
- return state;
1175
- }
1176
- if (isSignal(event.type)) {
1177
- // TODO: unrecognized signal
1178
- return state;
1179
- }
1180
- if (!isSignal(event.type)) {
1181
- state.receivers.forEach(function (receiver) {
1182
- return receiver(event);
1183
- });
1184
- }
1185
- return state;
1186
- },
1187
- getInitialState: function getInitialState(_, input) {
1188
- return {
1189
- canceled: false,
1190
- receivers: new Set(),
1191
- dispose: undefined,
1192
- input: input
1193
- };
1194
- },
1195
- getSnapshot: function getSnapshot() {
1196
- return undefined;
1197
- },
1198
- getPersistedState: function getPersistedState(_ref3) {
1199
- var input = _ref3.input;
1200
- return input;
1201
- }
1202
- };
1203
- return behavior;
1204
- }
1205
-
1206
- var startSignalType = 'xstate.init';
1207
- var stopSignalType = 'xstate.stop';
1208
- var startSignal = {
1209
- type: 'xstate.init'
1210
- };
1211
- var stopSignal = {
1212
- type: 'xstate.stop'
1213
- };
1214
- /**
1215
- * An object that expresses the behavior of an actor in reaction to received events,
1216
- * as well as an optionally emitted stream of values.
1217
- *
1218
- * @template TReceived The received event
1219
- * @template TSnapshot The emitted value
1220
- */
1221
-
1222
- function isSignal(eventType) {
1223
- return eventType === startSignalType || eventType === stopSignalType;
1224
- }
1225
- function isActorRef(item) {
1226
- return !!item && _typeof(item) === 'object' && typeof item.send === 'function';
1227
- }
1228
-
1229
- // TODO: refactor the return type, this could be written in a better way
1230
- // but it's best to avoid unneccessary breaking changes now
1231
- // @deprecated use `interpret(behavior)` instead
1232
- function toActorRef(actorRefLike) {
1233
- var _objectSpread2$1;
1234
- return _objectSpread2((_objectSpread2$1 = {
1235
- subscribe: function subscribe() {
1236
- return {
1237
- unsubscribe: function unsubscribe() {
1238
- return void 0;
1239
- }
1240
- };
1241
- },
1242
- id: 'anonymous',
1243
- sessionId: '',
1244
- getSnapshot: function getSnapshot() {
1245
- return undefined;
1246
- }
1247
- }, _defineProperty(_objectSpread2$1, symbolObservable, function () {
1248
- return this;
1249
- }), _defineProperty(_objectSpread2$1, "status", ActorStatus.Running), _defineProperty(_objectSpread2$1, "stop", function stop() {
1250
- return void 0;
1251
- }), _objectSpread2$1), actorRefLike);
1252
- }
1253
- var emptyBehavior = fromTransition(function (_) {
1254
- return undefined;
1255
- }, undefined);
1256
- function createEmptyActor() {
1257
- return interpret(emptyBehavior);
1258
- }
1259
-
1260
- function createSystem() {
1261
- var sessionIdCounter = 0;
1262
- var children = new Map();
1263
- var keyedActors = new Map();
1264
- var reverseKeyedActors = new WeakMap();
1265
- var system = {
1266
- _bookId: function _bookId() {
1267
- return "x:".concat(sessionIdCounter++);
1268
- },
1269
- _register: function _register(sessionId, actorRef) {
1270
- children.set(sessionId, actorRef);
1271
- return sessionId;
1272
- },
1273
- _unregister: function _unregister(actorRef) {
1274
- children["delete"](actorRef.sessionId);
1275
- var systemId = reverseKeyedActors.get(actorRef);
1276
- if (systemId !== undefined) {
1277
- keyedActors["delete"](systemId);
1278
- reverseKeyedActors["delete"](actorRef);
1279
- }
1280
- },
1281
- get: function get(systemId) {
1282
- return keyedActors.get(systemId);
1283
- },
1284
- _set: function _set(systemId, actorRef) {
1285
- var existing = keyedActors.get(systemId);
1286
- if (existing && existing !== actorRef) {
1287
- throw new Error("Actor with system ID '".concat(systemId, "' already exists."));
1288
- }
1289
- keyedActors.set(systemId, actorRef);
1290
- reverseKeyedActors.set(actorRef, systemId);
1291
- }
1292
- };
1293
- return system;
1294
- }
1295
-
1296
- var ActorStatus;
1297
- (function (ActorStatus) {
1298
- ActorStatus[ActorStatus["NotStarted"] = 0] = "NotStarted";
1299
- ActorStatus[ActorStatus["Running"] = 1] = "Running";
1300
- ActorStatus[ActorStatus["Stopped"] = 2] = "Stopped";
1301
- })(ActorStatus || (ActorStatus = {}));
1302
- var defaultOptions = {
1303
- deferEvents: true,
1304
- clock: {
1305
- setTimeout: function (_setTimeout) {
1306
- function setTimeout(_x, _x2) {
1307
- return _setTimeout.apply(this, arguments);
1308
- }
1309
- setTimeout.toString = function () {
1310
- return _setTimeout.toString();
1311
- };
1312
- return setTimeout;
1313
- }(function (fn, ms) {
1314
- return setTimeout(fn, ms);
1315
- }),
1316
- clearTimeout: function (_clearTimeout) {
1317
- function clearTimeout(_x3) {
1318
- return _clearTimeout.apply(this, arguments);
1319
- }
1320
- clearTimeout.toString = function () {
1321
- return _clearTimeout.toString();
1322
- };
1323
- return clearTimeout;
1324
- }(function (id) {
1325
- return clearTimeout(id);
1326
- })
1327
- },
1328
- logger: console.log.bind(console),
1329
- devTools: false
1330
- };
1331
- var Interpreter = /*#__PURE__*/function () {
1332
- /**
1333
- * The current state of the interpreted behavior.
1334
- */
1335
-
1336
- /**
1337
- * The clock that is responsible for setting and clearing timeouts, such as delayed events and transitions.
1338
- */
1339
-
1340
- /**
1341
- * The unique identifier for this actor relative to its parent.
1342
- */
1343
-
1344
- /**
1345
- * Whether the service is started.
1346
- */
1347
-
1348
- // Actor Ref
1349
-
1350
- // TODO: add typings for system
1351
-
1352
- /**
1353
- * The globally unique process ID for this invocation.
1354
- */
1355
-
1356
- /**
1357
- * Creates a new Interpreter instance (i.e., service) for the given behavior with the provided options, if any.
1358
- *
1359
- * @param behavior The behavior to be interpreted
1360
- * @param options Interpreter options
1361
- */
1362
- function Interpreter(behavior, options) {
1363
- var _parent$system,
1364
- _this = this;
1365
- _classCallCheck(this, Interpreter);
1366
- this.behavior = behavior;
1367
- _defineProperty(this, "_state", void 0);
1368
- _defineProperty(this, "clock", void 0);
1369
- _defineProperty(this, "options", void 0);
1370
- _defineProperty(this, "id", void 0);
1371
- _defineProperty(this, "mailbox", new Mailbox(this._process.bind(this)));
1372
- _defineProperty(this, "delayedEventsMap", {});
1373
- _defineProperty(this, "observers", new Set());
1374
- _defineProperty(this, "logger", void 0);
1375
- _defineProperty(this, "status", ActorStatus.NotStarted);
1376
- _defineProperty(this, "_parent", void 0);
1377
- _defineProperty(this, "ref", void 0);
1378
- _defineProperty(this, "_actorContext", void 0);
1379
- _defineProperty(this, "_systemId", void 0);
1380
- _defineProperty(this, "sessionId", void 0);
1381
- _defineProperty(this, "system", void 0);
1382
- _defineProperty(this, "_doneEvent", void 0);
1383
- _defineProperty(this, "src", void 0);
1384
- _defineProperty(this, "_deferred", []);
1385
- var resolvedOptions = _objectSpread2(_objectSpread2({}, defaultOptions), options);
1386
- var clock = resolvedOptions.clock,
1387
- logger = resolvedOptions.logger,
1388
- parent = resolvedOptions.parent,
1389
- id = resolvedOptions.id,
1390
- systemId = resolvedOptions.systemId;
1391
- var self = this;
1392
- this.system = (_parent$system = parent === null || parent === void 0 ? void 0 : parent.system) !== null && _parent$system !== void 0 ? _parent$system : createSystem();
1393
- if (systemId) {
1394
- this._systemId = systemId;
1395
- this.system._set(systemId, this);
1396
- }
1397
- this.sessionId = this.system._bookId();
1398
- this.id = id !== null && id !== void 0 ? id : this.sessionId;
1399
- this.logger = logger;
1400
- this.clock = clock;
1401
- this._parent = parent;
1402
- this.options = resolvedOptions;
1403
- this.src = resolvedOptions.src;
1404
- this.ref = this;
1405
- this._actorContext = {
1406
- self: self,
1407
- id: this.id,
1408
- sessionId: this.sessionId,
1409
- logger: this.logger,
1410
- defer: function defer(fn) {
1411
- _this._deferred.push(fn);
1412
- },
1413
- system: this.system,
1414
- stopChild: function stopChild(child) {
1415
- if (child._parent !== _this) {
1416
- throw new Error("Cannot stop child actor ".concat(child.id, " of ").concat(_this.id, " because it is not a child"));
1417
- }
1418
- child._stop();
1419
- }
1420
- };
1421
-
1422
- // Ensure that the send method is bound to this interpreter instance
1423
- // if destructured
1424
- this.send = this.send.bind(this);
1425
- this._initState();
1426
- }
1427
- _createClass(Interpreter, [{
1428
- key: "_initState",
1429
- value: function _initState() {
1430
- var _this$options;
1431
- this._state = this.options.state ? this.behavior.restoreState ? this.behavior.restoreState(this.options.state, this._actorContext) : this.options.state : this.behavior.getInitialState(this._actorContext, (_this$options = this.options) === null || _this$options === void 0 ? void 0 : _this$options.input);
1432
- }
1433
-
1434
- // array of functions to defer
1435
- }, {
1436
- key: "update",
1437
- value: function update(state) {
1438
- var _this$behavior$getSta, _this$behavior, _this$_parent, _this$_parent2;
1439
- // Update state
1440
- this._state = state;
1441
- var snapshot = this.getSnapshot();
1442
-
1443
- // Execute deferred effects
1444
- var deferredFn;
1445
- while (deferredFn = this._deferred.shift()) {
1446
- deferredFn(state);
1447
- }
1448
- var _iterator = _createForOfIteratorHelper(this.observers),
1449
- _step;
1450
- try {
1451
- for (_iterator.s(); !(_step = _iterator.n()).done;) {
1452
- var _observer$next;
1453
- var _observer = _step.value;
1454
- (_observer$next = _observer.next) === null || _observer$next === void 0 ? void 0 : _observer$next.call(_observer, snapshot);
1455
- }
1456
- } catch (err) {
1457
- _iterator.e(err);
1458
- } finally {
1459
- _iterator.f();
1460
- }
1461
- var status = (_this$behavior$getSta = (_this$behavior = this.behavior).getStatus) === null || _this$behavior$getSta === void 0 ? void 0 : _this$behavior$getSta.call(_this$behavior, state);
1462
- switch (status === null || status === void 0 ? void 0 : status.status) {
1463
- case 'done':
1464
- this._stopProcedure();
1465
- this._doneEvent = doneInvoke(this.id, status.data);
1466
- (_this$_parent = this._parent) === null || _this$_parent === void 0 ? void 0 : _this$_parent.send(this._doneEvent);
1467
- this._complete();
1468
- break;
1469
- case 'error':
1470
- this._stopProcedure();
1471
- (_this$_parent2 = this._parent) === null || _this$_parent2 === void 0 ? void 0 : _this$_parent2.send(error(this.id, status.data));
1472
- this._error(status.data);
1473
- break;
1474
- }
1475
- }
1476
- }, {
1477
- key: "subscribe",
1478
- value: function subscribe(nextListenerOrObserver, errorListener, completeListener) {
1479
- var _this2 = this;
1480
- var observer = toObserver(nextListenerOrObserver, errorListener, completeListener);
1481
- this.observers.add(observer);
1482
- if (this.status === ActorStatus.Stopped) {
1483
- var _observer$complete;
1484
- (_observer$complete = observer.complete) === null || _observer$complete === void 0 ? void 0 : _observer$complete.call(observer);
1485
- this.observers["delete"](observer);
1486
- }
1487
- return {
1488
- unsubscribe: function unsubscribe() {
1489
- _this2.observers["delete"](observer);
1490
- }
1491
- };
1492
- }
1493
-
1494
- /**
1495
- * Adds a state listener that is notified when the statechart has reached its final state.
1496
- * @param listener The state listener
1497
- */
1498
- }, {
1499
- key: "onDone",
1500
- value: function onDone(listener) {
1501
- var _this3 = this;
1502
- if (this.status === ActorStatus.Stopped && this._doneEvent) {
1503
- listener(this._doneEvent);
1504
- } else {
1505
- this.observers.add({
1506
- complete: function complete() {
1507
- if (_this3._doneEvent) {
1508
- listener(_this3._doneEvent);
1509
- }
1510
- }
1511
- });
1512
- }
1513
- return this;
1514
- }
1515
-
1516
- /**
1517
- * Starts the interpreter from the initial state
1518
- */
1519
- }, {
1520
- key: "start",
1521
- value: function start() {
1522
- if (this.status === ActorStatus.Running) {
1523
- // Do not restart the service if it is already started
1524
- return this;
1525
- }
1526
- this.system._register(this.sessionId, this);
1527
- if (this._systemId) {
1528
- this.system._set(this._systemId, this);
1529
- }
1530
- this.status = ActorStatus.Running;
1531
- if (this.behavior.start) {
1532
- this.behavior.start(this._state, this._actorContext);
1533
- }
1534
-
1535
- // TODO: this notifies all subscribers but usually this is redundant
1536
- // there is no real change happening here
1537
- // we need to rethink if this needs to be refactored
1538
- this.update(this._state);
1539
- if (this.options.devTools) {
1540
- this.attachDevTools();
1541
- }
1542
- this.mailbox.start();
1543
- return this;
1544
- }
1545
- }, {
1546
- key: "_process",
1547
- value: function _process(event) {
1548
- try {
1549
- var nextState = this.behavior.transition(this._state, event, this._actorContext);
1550
- this.update(nextState);
1551
- if (event.type === stopSignalType) {
1552
- this._stopProcedure();
1553
- this._complete();
1554
- }
1555
- } catch (err) {
1556
- // TODO: properly handle errors
1557
- if (this.observers.size > 0) {
1558
- this.observers.forEach(function (observer) {
1559
- var _observer$error;
1560
- (_observer$error = observer.error) === null || _observer$error === void 0 ? void 0 : _observer$error.call(observer, err);
1561
- });
1562
- this.stop();
1563
- } else {
1564
- throw err;
1565
- }
1566
- }
1567
- }
1568
- }, {
1569
- key: "_stop",
1570
- value: function _stop() {
1571
- if (this.status === ActorStatus.Stopped) {
1572
- return this;
1573
- }
1574
- this.mailbox.clear();
1575
- if (this.status === ActorStatus.NotStarted) {
1576
- this.status = ActorStatus.Stopped;
1577
- return this;
1578
- }
1579
- this.mailbox.enqueue({
1580
- type: stopSignalType
1581
- });
1582
- return this;
1583
- }
1584
-
1585
- /**
1586
- * Stops the interpreter and unsubscribe all listeners.
1587
- */
1588
- }, {
1589
- key: "stop",
1590
- value: function stop() {
1591
- if (this._parent) {
1592
- throw new Error('A non-root actor cannot be stopped directly.');
1593
- }
1594
- return this._stop();
1595
- }
1596
- }, {
1597
- key: "_complete",
1598
- value: function _complete() {
1599
- var _iterator2 = _createForOfIteratorHelper(this.observers),
1600
- _step2;
1601
- try {
1602
- for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
1603
- var _observer2$complete;
1604
- var _observer2 = _step2.value;
1605
- (_observer2$complete = _observer2.complete) === null || _observer2$complete === void 0 ? void 0 : _observer2$complete.call(_observer2);
1606
- }
1607
- } catch (err) {
1608
- _iterator2.e(err);
1609
- } finally {
1610
- _iterator2.f();
1611
- }
1612
- this.observers.clear();
1613
- }
1614
- }, {
1615
- key: "_error",
1616
- value: function _error(data) {
1617
- var _iterator3 = _createForOfIteratorHelper(this.observers),
1618
- _step3;
1619
- try {
1620
- for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
1621
- var _observer3$error;
1622
- var _observer3 = _step3.value;
1623
- (_observer3$error = _observer3.error) === null || _observer3$error === void 0 ? void 0 : _observer3$error.call(_observer3, data);
1624
- }
1625
- } catch (err) {
1626
- _iterator3.e(err);
1627
- } finally {
1628
- _iterator3.f();
1629
- }
1630
- this.observers.clear();
1631
- }
1632
- }, {
1633
- key: "_stopProcedure",
1634
- value: function _stopProcedure() {
1635
- if (this.status !== ActorStatus.Running) {
1636
- // Interpreter already stopped; do nothing
1637
- return this;
1638
- }
1639
-
1640
- // Cancel all delayed events
1641
- for (var _i = 0, _Object$keys = Object.keys(this.delayedEventsMap); _i < _Object$keys.length; _i++) {
1642
- var key = _Object$keys[_i];
1643
- this.clock.clearTimeout(this.delayedEventsMap[key]);
1644
- }
1645
-
1646
- // TODO: mailbox.reset
1647
- this.mailbox.clear();
1648
- // TODO: after `stop` we must prepare ourselves for receiving events again
1649
- // events sent *after* stop signal must be queued
1650
- // it seems like this should be the common behavior for all of our consumers
1651
- // so perhaps this should be unified somehow for all of them
1652
- this.mailbox = new Mailbox(this._process.bind(this));
1653
- this.status = ActorStatus.Stopped;
1654
- this.system._unregister(this);
1655
- return this;
1656
- }
1657
-
1658
- /**
1659
- * Sends an event to the running interpreter to trigger a transition.
1660
- *
1661
- * @param event The event to send
1662
- */
1663
- }, {
1664
- key: "send",
1665
- value: function send(event) {
1666
- if (typeof event === 'string') {
1667
- throw new Error("Only event objects may be sent to actors; use .send({ type: \"".concat(event, "\" }) instead"));
1668
- }
1669
- if (this.status === ActorStatus.Stopped) {
1670
- // do nothing
1671
- if (!IS_PRODUCTION) {
1672
- var eventString = JSON.stringify(event);
1673
- warn(false, "Event \"".concat(event.type.toString(), "\" was sent to stopped actor \"").concat(this.id, " (").concat(this.sessionId, ")\". This actor has already reached its final state, and will not transition.\nEvent: ").concat(eventString));
1674
- }
1675
- return;
1676
- }
1677
- if (this.status !== ActorStatus.Running && !this.options.deferEvents) {
1678
- throw new Error("Event \"".concat(event.type, "\" was sent to uninitialized actor \"").concat(this.id
1679
- // tslint:disable-next-line:max-line-length
1680
- , "\". Make sure .start() is called for this actor, or set { deferEvents: true } in the actor options.\nEvent: ").concat(JSON.stringify(event)));
1681
- }
1682
- this.mailbox.enqueue(event);
1683
- }
1684
-
1685
- // TODO: make private (and figure out a way to do this within the machine)
1686
- }, {
1687
- key: "delaySend",
1688
- value: function delaySend(sendAction) {
1689
- var _this4 = this;
1690
- this.delayedEventsMap[sendAction.params.id] = this.clock.setTimeout(function () {
1691
- if ('to' in sendAction.params && sendAction.params.to) {
1692
- sendAction.params.to.send(sendAction.params.event);
1693
- } else {
1694
- _this4.send(sendAction.params.event);
1695
- }
1696
- }, sendAction.params.delay);
1697
- }
1698
-
1699
- // TODO: make private (and figure out a way to do this within the machine)
1700
- }, {
1701
- key: "cancel",
1702
- value: function cancel(sendId) {
1703
- this.clock.clearTimeout(this.delayedEventsMap[sendId]);
1704
- delete this.delayedEventsMap[sendId];
1705
- }
1706
- }, {
1707
- key: "attachDevTools",
1708
- value: function attachDevTools() {
1709
- var devTools = this.options.devTools;
1710
- if (devTools) {
1711
- var resolvedDevToolsAdapter = typeof devTools === 'function' ? devTools : devToolsAdapter;
1712
- resolvedDevToolsAdapter(this);
1713
- }
1714
- }
1715
- }, {
1716
- key: "toJSON",
1717
- value: function toJSON() {
1718
- return {
1719
- id: this.id
1720
- };
1721
- }
1722
- }, {
1723
- key: "getPersistedState",
1724
- value: function getPersistedState() {
1725
- var _this$behavior$getPer, _this$behavior2;
1726
- return (_this$behavior$getPer = (_this$behavior2 = this.behavior).getPersistedState) === null || _this$behavior$getPer === void 0 ? void 0 : _this$behavior$getPer.call(_this$behavior2, this._state);
1727
- }
1728
- }, {
1729
- key: symbolObservable,
1730
- value: function value() {
1731
- return this;
1732
- }
1733
- }, {
1734
- key: "getSnapshot",
1735
- value: function getSnapshot() {
1736
- return this.behavior.getSnapshot ? this.behavior.getSnapshot(this._state) : this._state;
1737
- }
1738
- }]);
1739
- return Interpreter;
1740
- }();
1741
-
1742
- /**
1743
- * Creates a new Interpreter instance for the given machine with the provided options, if any.
1744
- *
1745
- * @param machine The machine to interpret
1746
- * @param options Interpreter options
1747
- */
1748
-
1749
- function interpret(behavior, options) {
1750
- var interpreter = new Interpreter(behavior, options);
1751
- return interpreter;
1752
- }
1753
-
1754
- /**
1755
- * Stops an actor.
1756
- *
1757
- * @param actorRef The actor to stop.
1758
- */
1759
-
1760
- function stop(actorRef) {
1761
- var actor = actorRef;
1762
- return createDynamicAction({
1763
- type: stop$1,
1764
- params: {
1765
- actor: actor
1766
- }
1767
- }, function (event, _ref) {
1768
- var state = _ref.state;
1769
- var actorRefOrString = isFunction(actor) ? actor({
1770
- context: state.context,
1771
- event: event
1772
- }) : actor;
1773
- var actorRef = typeof actorRefOrString === 'string' ? state.children[actorRefOrString] : actorRefOrString;
1774
- return [state, {
1775
- type: 'xstate.stop',
1776
- params: {
1777
- actor: actorRef
1778
- },
1779
- execute: function execute(actorCtx) {
1780
- if (!actorRef) {
1781
- return;
1782
- }
1783
- if (actorRef.status !== ActorStatus.Running) {
1784
- actorCtx.stopChild(actorRef);
1785
- return;
1786
- }
1787
- actorCtx.defer(function () {
1788
- actorCtx.stopChild(actorRef);
1789
- });
1790
- }
1791
- }];
1792
- });
1793
- }
1794
-
1795
- var defaultLogExpr = function defaultLogExpr(_ref) {
1796
- var context = _ref.context,
1797
- event = _ref.event;
1798
- return {
1799
- context: context,
1800
- event: event
1801
- };
1802
- };
1803
-
1804
- /**
1805
- *
1806
- * @param expr The expression function to evaluate which will be logged.
1807
- * Takes in 2 arguments:
1808
- * - `ctx` - the current state context
1809
- * - `event` - the event that caused this action to be executed.
1810
- * @param label The label to give to the logged expression.
1811
- */
1812
-
1813
- function log() {
1814
- var expr = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : defaultLogExpr;
1815
- var label = arguments.length > 1 ? arguments[1] : undefined;
1816
- return createDynamicAction({
1817
- type: log$1,
1818
- params: {
1819
- label: label,
1820
- expr: expr
1821
- }
1822
- }, function (event, _ref2) {
1823
- var _actorContext$self;
1824
- var state = _ref2.state,
1825
- actorContext = _ref2.actorContext;
1826
- var resolvedValue = typeof expr === 'function' ? expr({
1827
- context: state.context,
1828
- event: event,
1829
- self: (_actorContext$self = actorContext === null || actorContext === void 0 ? void 0 : actorContext.self) !== null && _actorContext$self !== void 0 ? _actorContext$self : {},
1830
- system: actorContext === null || actorContext === void 0 ? void 0 : actorContext.system
1831
- }) : expr;
1832
- return [state, {
1833
- type: 'xstate.log',
1834
- params: {
1835
- label: label,
1836
- value: resolvedValue
1837
- },
1838
- execute: function execute(actorCtx) {
1839
- if (label) {
1840
- var _actorCtx$logger;
1841
- (_actorCtx$logger = actorCtx.logger) === null || _actorCtx$logger === void 0 ? void 0 : _actorCtx$logger.call(actorCtx, label, resolvedValue);
1842
- } else {
1843
- var _actorCtx$logger2;
1844
- (_actorCtx$logger2 = actorCtx.logger) === null || _actorCtx$logger2 === void 0 ? void 0 : _actorCtx$logger2.call(actorCtx, resolvedValue);
1845
- }
1846
- }
1847
- }];
1848
- });
1849
- }
1850
-
1851
- /**
1852
- * Cancels an in-flight `send(...)` action. A canceled sent action will not
1853
- * be executed, nor will its event be sent, unless it has already been sent
1854
- * (e.g., if `cancel(...)` is called after the `send(...)` action's `delay`).
1855
- *
1856
- * @param sendId The `id` of the `send(...)` action to cancel.
1857
- */
1858
-
1859
- function cancel(sendId) {
1860
- return createDynamicAction({
1861
- type: cancel$1,
1862
- params: {
1863
- sendId: sendId
1864
- }
1865
- }, function (event, _ref) {
1866
- var _actorContext$self;
1867
- var state = _ref.state,
1868
- actorContext = _ref.actorContext;
1869
- var resolvedSendId = isFunction(sendId) ? sendId({
1870
- context: state.context,
1871
- event: event,
1872
- self: (_actorContext$self = actorContext === null || actorContext === void 0 ? void 0 : actorContext.self) !== null && _actorContext$self !== void 0 ? _actorContext$self : {},
1873
- system: actorContext === null || actorContext === void 0 ? void 0 : actorContext.system
1874
- }) : sendId;
1875
- return [state, {
1876
- type: 'xstate.cancel',
1877
- params: {
1878
- sendId: resolvedSendId
1879
- },
1880
- execute: function execute(actorCtx) {
1881
- var interpreter = actorCtx.self;
1882
- interpreter.cancel(resolvedSendId);
1883
- }
1884
- }];
1885
- });
1886
- }
1887
-
1888
- function _objectWithoutPropertiesLoose(source, excluded) {
1889
- if (source == null) return {};
1890
- var target = {};
1891
- var sourceKeys = Object.keys(source);
1892
- var key, i;
1893
- for (i = 0; i < sourceKeys.length; i++) {
1894
- key = sourceKeys[i];
1895
- if (excluded.indexOf(key) >= 0) continue;
1896
- target[key] = source[key];
1897
- }
1898
- return target;
1899
- }
1900
-
1901
- function _objectWithoutProperties(source, excluded) {
1902
- if (source == null) return {};
1903
- var target = _objectWithoutPropertiesLoose(source, excluded);
1904
- var key, i;
1905
- if (Object.getOwnPropertySymbols) {
1906
- var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
1907
- for (i = 0; i < sourceSymbolKeys.length; i++) {
1908
- key = sourceSymbolKeys[i];
1909
- if (excluded.indexOf(key) >= 0) continue;
1910
- if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
1911
- target[key] = source[key];
1912
- }
1913
- }
1914
- return target;
1915
- }
1916
-
1917
- var cache = new WeakMap();
1918
- function memo(object, key, fn) {
1919
- var memoizedData = cache.get(object);
1920
- if (!memoizedData) {
1921
- memoizedData = _defineProperty({}, key, fn());
1922
- cache.set(object, memoizedData);
1923
- } else if (!(key in memoizedData)) {
1924
- memoizedData[key] = fn();
1925
- }
1926
- return memoizedData[key];
1927
- }
1928
-
1929
- function stateIn(stateValue) {
1930
- return {
1931
- type: 'xstate.guard:in',
1932
- params: {
1933
- stateValue: stateValue
1934
- },
1935
- predicate: function predicate(_ref) {
1936
- var state = _ref.state;
1937
- if (isString(stateValue) && isStateId(stateValue)) {
1938
- return state.configuration.some(function (sn) {
1939
- return sn.id === stateValue.slice(1);
1940
- });
1941
- }
1942
- return state.matches(stateValue);
1943
- }
1944
- };
1945
- }
1946
- function not(guard) {
1947
- return {
1948
- type: 'xstate.boolean',
1949
- params: {
1950
- op: 'not'
1951
- },
1952
- children: [toGuardDefinition(guard)],
1953
- predicate: function predicate(_ref2) {
1954
- var evaluate = _ref2.evaluate,
1955
- guard = _ref2.guard,
1956
- context = _ref2.context,
1957
- event = _ref2.event,
1958
- state = _ref2.state;
1959
- return !evaluate(guard.children[0], context, event, state);
1960
- }
1961
- };
1962
- }
1963
- function and(guards) {
1964
- return {
1965
- type: 'xstate.boolean',
1966
- params: {
1967
- op: 'and'
1968
- },
1969
- children: guards.map(function (guard) {
1970
- return toGuardDefinition(guard);
1971
- }),
1972
- predicate: function predicate(_ref3) {
1973
- var evaluate = _ref3.evaluate,
1974
- guard = _ref3.guard,
1975
- context = _ref3.context,
1976
- event = _ref3.event,
1977
- state = _ref3.state;
1978
- return guard.children.every(function (childGuard) {
1979
- return evaluate(childGuard, context, event, state);
1980
- });
1981
- }
1982
- };
1983
- }
1984
- function or(guards) {
1985
- return {
1986
- type: 'xstate.boolean',
1987
- params: {
1988
- op: 'or'
1989
- },
1990
- children: guards.map(function (guard) {
1991
- return toGuardDefinition(guard);
1992
- }),
1993
- predicate: function predicate(_ref4) {
1994
- var evaluate = _ref4.evaluate,
1995
- guard = _ref4.guard,
1996
- context = _ref4.context,
1997
- event = _ref4.event,
1998
- state = _ref4.state;
1999
- return guard.children.some(function (childGuard) {
2000
- return evaluate(childGuard, context, event, state);
2001
- });
2002
- }
2003
- };
2004
- }
2005
- function evaluateGuard(guard, context, event, state) {
2006
- var _machine$options$guar, _machine$options, _machine$options$guar2;
2007
- var machine = state.machine;
2008
- var predicate = (_machine$options$guar = machine === null || machine === void 0 ? void 0 : (_machine$options = machine.options) === null || _machine$options === void 0 ? void 0 : (_machine$options$guar2 = _machine$options.guards) === null || _machine$options$guar2 === void 0 ? void 0 : _machine$options$guar2[guard.type]) !== null && _machine$options$guar !== void 0 ? _machine$options$guar : guard.predicate;
2009
- if (!predicate) {
2010
- throw new Error("Guard '".concat(guard.type, "' is not implemented.'."));
2011
- }
2012
- return predicate({
2013
- context: context,
2014
- event: event,
2015
- state: state,
2016
- guard: guard,
2017
- evaluate: evaluateGuard
2018
- });
2019
- }
2020
- function toGuardDefinition(guardConfig, getPredicate) {
2021
- var _guardConfig$children;
2022
- if (isString(guardConfig)) {
2023
- return {
2024
- type: guardConfig,
2025
- predicate: (getPredicate === null || getPredicate === void 0 ? void 0 : getPredicate(guardConfig)) || undefined,
2026
- params: {
2027
- type: guardConfig
2028
- }
2029
- };
2030
- }
2031
- if (isFunction(guardConfig)) {
2032
- return {
2033
- type: guardConfig.name,
2034
- predicate: guardConfig,
2035
- params: {
2036
- type: guardConfig.name,
2037
- name: guardConfig.name
2038
- }
2039
- };
2040
- }
2041
- return {
2042
- type: guardConfig.type,
2043
- params: guardConfig.params || guardConfig,
2044
- children: (_guardConfig$children = guardConfig.children) === null || _guardConfig$children === void 0 ? void 0 : _guardConfig$children.map(function (childGuard) {
2045
- return toGuardDefinition(childGuard, getPredicate);
2046
- }),
2047
- predicate: (getPredicate === null || getPredicate === void 0 ? void 0 : getPredicate(guardConfig.type)) || guardConfig.predicate
2048
- };
2049
- }
2050
-
2051
- function getOutput(configuration, context, event) {
2052
- var machine = configuration[0].machine;
2053
- var finalChildStateNode = configuration.find(function (stateNode) {
2054
- return stateNode.type === 'final' && stateNode.parent === machine.root;
2055
- });
2056
- return finalChildStateNode && finalChildStateNode.output ? mapContext(finalChildStateNode.output, context, event) : undefined;
2057
- }
2058
- var isAtomicStateNode = function isAtomicStateNode(stateNode) {
2059
- return stateNode.type === 'atomic' || stateNode.type === 'final';
2060
- };
2061
- function getChildren(stateNode) {
2062
- return Object.values(stateNode.states).filter(function (sn) {
2063
- return sn.type !== 'history';
2064
- });
2065
- }
2066
- function getProperAncestors(stateNode, toStateNode) {
2067
- var ancestors = [];
2068
-
2069
- // add all ancestors
2070
- var m = stateNode.parent;
2071
- while (m && m !== toStateNode) {
2072
- ancestors.push(m);
2073
- m = m.parent;
2074
- }
2075
- return ancestors;
2076
- }
2077
- function getConfiguration(stateNodes) {
2078
- var configuration = new Set(stateNodes);
2079
- var configurationSet = new Set(stateNodes);
2080
- var adjList = getAdjList(configurationSet);
2081
-
2082
- // add descendants
2083
- var _iterator = _createForOfIteratorHelper(configuration),
2084
- _step;
2085
- try {
2086
- for (_iterator.s(); !(_step = _iterator.n()).done;) {
2087
- var s = _step.value;
2088
- // if previously active, add existing child nodes
2089
- if (s.type === 'compound' && (!adjList.get(s) || !adjList.get(s).length)) {
2090
- getInitialStateNodes(s).forEach(function (sn) {
2091
- return configurationSet.add(sn);
2092
- });
2093
- } else {
2094
- if (s.type === 'parallel') {
2095
- var _iterator3 = _createForOfIteratorHelper(getChildren(s)),
2096
- _step3;
2097
- try {
2098
- for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
2099
- var child = _step3.value;
2100
- if (child.type === 'history') {
2101
- continue;
2102
- }
2103
- if (!configurationSet.has(child)) {
2104
- for (var _i = 0, _getInitialStateNodes = getInitialStateNodes(child); _i < _getInitialStateNodes.length; _i++) {
2105
- var initialStateNode = _getInitialStateNodes[_i];
2106
- configurationSet.add(initialStateNode);
2107
- }
2108
- }
2109
- }
2110
- } catch (err) {
2111
- _iterator3.e(err);
2112
- } finally {
2113
- _iterator3.f();
2114
- }
2115
- }
2116
- }
2117
- }
2118
-
2119
- // add all ancestors
2120
- } catch (err) {
2121
- _iterator.e(err);
2122
- } finally {
2123
- _iterator.f();
2124
- }
2125
- var _iterator2 = _createForOfIteratorHelper(configurationSet),
2126
- _step2;
2127
- try {
2128
- for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
2129
- var _s = _step2.value;
2130
- var m = _s.parent;
2131
- while (m) {
2132
- configurationSet.add(m);
2133
- m = m.parent;
2134
- }
2135
- }
2136
- } catch (err) {
2137
- _iterator2.e(err);
2138
- } finally {
2139
- _iterator2.f();
2140
- }
2141
- return configurationSet;
2142
- }
2143
- function getValueFromAdj(baseNode, adjList) {
2144
- var childStateNodes = adjList.get(baseNode);
2145
- if (!childStateNodes) {
2146
- return {}; // todo: fix?
2147
- }
2148
-
2149
- if (baseNode.type === 'compound') {
2150
- var childStateNode = childStateNodes[0];
2151
- if (childStateNode) {
2152
- if (isAtomicStateNode(childStateNode)) {
2153
- return childStateNode.key;
2154
- }
2155
- } else {
2156
- return {};
2157
- }
2158
- }
2159
- var stateValue = {};
2160
- var _iterator4 = _createForOfIteratorHelper(childStateNodes),
2161
- _step4;
2162
- try {
2163
- for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) {
2164
- var _childStateNode = _step4.value;
2165
- stateValue[_childStateNode.key] = getValueFromAdj(_childStateNode, adjList);
2166
- }
2167
- } catch (err) {
2168
- _iterator4.e(err);
2169
- } finally {
2170
- _iterator4.f();
2171
- }
2172
- return stateValue;
2173
- }
2174
- function getAdjList(configuration) {
2175
- var adjList = new Map();
2176
- var _iterator5 = _createForOfIteratorHelper(configuration),
2177
- _step5;
2178
- try {
2179
- for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) {
2180
- var s = _step5.value;
2181
- if (!adjList.has(s)) {
2182
- adjList.set(s, []);
2183
- }
2184
- if (s.parent) {
2185
- if (!adjList.has(s.parent)) {
2186
- adjList.set(s.parent, []);
2187
- }
2188
- adjList.get(s.parent).push(s);
2189
- }
2190
- }
2191
- } catch (err) {
2192
- _iterator5.e(err);
2193
- } finally {
2194
- _iterator5.f();
2195
- }
2196
- return adjList;
2197
- }
2198
- function getStateValue(rootNode, configuration) {
2199
- var config = getConfiguration(configuration);
2200
- return getValueFromAdj(rootNode, getAdjList(config));
2201
- }
2202
- function isInFinalState(configuration) {
2203
- var stateNode = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : configuration[0].machine.root;
2204
- if (stateNode.type === 'compound') {
2205
- return getChildren(stateNode).some(function (s) {
2206
- return s.type === 'final' && configuration.includes(s);
2207
- });
2208
- }
2209
- if (stateNode.type === 'parallel') {
2210
- return getChildren(stateNode).every(function (sn) {
2211
- return isInFinalState(configuration, sn);
2212
- });
2213
- }
2214
- return false;
2215
- }
2216
- var isStateId = function isStateId(str) {
2217
- return str[0] === STATE_IDENTIFIER;
2218
- };
2219
- function getCandidates(stateNode, receivedEventType) {
2220
- var candidates = stateNode.transitions.filter(function (transition) {
2221
- var eventType = transition.eventType;
2222
- // First, check the trivial case: event names are exactly equal
2223
- if (eventType === receivedEventType) {
2224
- return true;
2225
- }
2226
-
2227
- // Then, check if transition is a wildcard transition,
2228
- // which matches any non-transient events
2229
- if (eventType === WILDCARD) {
2230
- return true;
2231
- }
2232
- if (!eventType.endsWith('.*')) {
2233
- return false;
2234
- }
2235
- if (!IS_PRODUCTION) {
2236
- warn(!/.*\*.+/.test(eventType), "Wildcards can only be the last token of an event descriptor (e.g., \"event.*\") or the entire event descriptor (\"*\"). Check the \"".concat(eventType, "\" event."));
2237
- }
2238
- var partialEventTokens = eventType.split('.');
2239
- var eventTokens = receivedEventType.split('.');
2240
- for (var tokenIndex = 0; tokenIndex < partialEventTokens.length; tokenIndex++) {
2241
- var partialEventToken = partialEventTokens[tokenIndex];
2242
- var eventToken = eventTokens[tokenIndex];
2243
- if (partialEventToken === '*') {
2244
- var isLastToken = tokenIndex === partialEventTokens.length - 1;
2245
- if (!IS_PRODUCTION) {
2246
- warn(isLastToken, "Infix wildcards in transition events are not allowed. Check the \"".concat(eventType, "\" event."));
2247
- }
2248
- return isLastToken;
2249
- }
2250
- if (partialEventToken !== eventToken) {
2251
- return false;
2252
- }
2253
- }
2254
- return true;
2255
- });
2256
- return candidates;
2257
- }
2258
-
2259
- /**
2260
- * All delayed transitions from the config.
2261
- */
2262
- function getDelayedTransitions(stateNode) {
2263
- var afterConfig = stateNode.config.after;
2264
- if (!afterConfig) {
2265
- return [];
2266
- }
2267
- var mutateEntryExit = function mutateEntryExit(delay, i) {
2268
- var delayRef = isFunction(delay) ? "".concat(stateNode.id, ":delay[").concat(i, "]") : delay;
2269
- var eventType = after(delayRef, stateNode.id);
2270
- stateNode.entry.push(raise({
2271
- type: eventType
2272
- }, {
2273
- delay: delay
2274
- }));
2275
- stateNode.exit.push(cancel(eventType));
2276
- return eventType;
2277
- };
2278
- var delayedTransitions = isArray(afterConfig) ? afterConfig.map(function (transition, i) {
2279
- var eventType = mutateEntryExit(transition.delay, i);
2280
- return _objectSpread2(_objectSpread2({}, transition), {}, {
2281
- event: eventType
2282
- });
2283
- }) : Object.keys(afterConfig).flatMap(function (delay, i) {
2284
- var configTransition = afterConfig[delay];
2285
- var resolvedTransition = isString(configTransition) ? {
2286
- target: configTransition
2287
- } : configTransition;
2288
- var resolvedDelay = !isNaN(+delay) ? +delay : delay;
2289
- var eventType = mutateEntryExit(resolvedDelay, i);
2290
- return toArray(resolvedTransition).map(function (transition) {
2291
- return _objectSpread2(_objectSpread2({}, transition), {}, {
2292
- event: eventType,
2293
- delay: resolvedDelay
2294
- });
2295
- });
2296
- });
2297
- return delayedTransitions.map(function (delayedTransition) {
2298
- var delay = delayedTransition.delay;
2299
- return _objectSpread2(_objectSpread2({}, formatTransition(stateNode, delayedTransition)), {}, {
2300
- delay: delay
2301
- });
2302
- });
2303
- }
2304
- function formatTransition(stateNode, transitionConfig) {
2305
- var _transitionConfig$ree;
2306
- var normalizedTarget = normalizeTarget(transitionConfig.target);
2307
- var reenter = (_transitionConfig$ree = transitionConfig.reenter) !== null && _transitionConfig$ree !== void 0 ? _transitionConfig$ree : false;
2308
- var guards = stateNode.machine.options.guards;
2309
- var target = resolveTarget(stateNode, normalizedTarget);
2310
-
2311
- // TODO: should this be part of a lint rule instead?
2312
- if (!IS_PRODUCTION && transitionConfig.cond) {
2313
- throw new Error("State \"".concat(stateNode.id, "\" has declared `cond` for one of its transitions. This property has been renamed to `guard`. Please update your code."));
2314
- }
2315
- var transition = _objectSpread2(_objectSpread2({}, transitionConfig), {}, {
2316
- actions: toActionObjects(toArray(transitionConfig.actions)),
2317
- guard: transitionConfig.guard ? toGuardDefinition(transitionConfig.guard, function (guardType) {
2318
- return guards[guardType];
2319
- }) : undefined,
2320
- target: target,
2321
- source: stateNode,
2322
- reenter: reenter,
2323
- eventType: transitionConfig.event,
2324
- toJSON: function toJSON() {
2325
- return _objectSpread2(_objectSpread2({}, transition), {}, {
2326
- source: "#".concat(stateNode.id),
2327
- target: target ? target.map(function (t) {
2328
- return "#".concat(t.id);
2329
- }) : undefined
2330
- });
2331
- }
2332
- });
2333
- return transition;
2334
- }
2335
- function formatTransitions(stateNode) {
2336
- var transitionConfigs = [];
2337
- if (Array.isArray(stateNode.config.on)) {
2338
- transitionConfigs.push.apply(transitionConfigs, _toConsumableArray(stateNode.config.on));
2339
- } else if (stateNode.config.on) {
2340
- var _stateNode$config$on = stateNode.config.on,
2341
- _stateNode$config$on$ = _stateNode$config$on[WILDCARD],
2342
- wildcardConfigs = _stateNode$config$on$ === void 0 ? [] : _stateNode$config$on$,
2343
- namedTransitionConfigs = _objectWithoutProperties(_stateNode$config$on, [WILDCARD].map(_toPropertyKey));
2344
- for (var _i2 = 0, _Object$keys = Object.keys(namedTransitionConfigs); _i2 < _Object$keys.length; _i2++) {
2345
- var eventType = _Object$keys[_i2];
2346
- if (eventType === NULL_EVENT) {
2347
- throw new Error('Null events ("") cannot be specified as a transition key. Use `always: { ... }` instead.');
2348
- }
2349
- var eventTransitionConfigs = toTransitionConfigArray(eventType, namedTransitionConfigs[eventType]);
2350
- transitionConfigs.push.apply(transitionConfigs, _toConsumableArray(eventTransitionConfigs));
2351
- // TODO: add dev-mode validation for unreachable transitions
2352
- }
2353
-
2354
- transitionConfigs.push.apply(transitionConfigs, _toConsumableArray(toTransitionConfigArray(WILDCARD, wildcardConfigs)));
2355
- }
2356
- var doneConfig = stateNode.config.onDone ? toTransitionConfigArray(String(done(stateNode.id)), stateNode.config.onDone) : [];
2357
- var invokeConfig = stateNode.invoke.flatMap(function (invokeDef) {
2358
- var settleTransitions = [];
2359
- if (invokeDef.onDone) {
2360
- settleTransitions.push.apply(settleTransitions, _toConsumableArray(toTransitionConfigArray("done.invoke.".concat(invokeDef.id), invokeDef.onDone)));
2361
- }
2362
- if (invokeDef.onError) {
2363
- settleTransitions.push.apply(settleTransitions, _toConsumableArray(toTransitionConfigArray("error.platform.".concat(invokeDef.id), invokeDef.onError)));
2364
- }
2365
- if (invokeDef.onSnapshot) {
2366
- settleTransitions.push.apply(settleTransitions, _toConsumableArray(toTransitionConfigArray("xstate.snapshot.".concat(invokeDef.id), invokeDef.onSnapshot)));
2367
- }
2368
- return settleTransitions;
2369
- });
2370
- var delayedTransitions = stateNode.after;
2371
- var formattedTransitions = [].concat(_toConsumableArray(doneConfig), _toConsumableArray(invokeConfig), transitionConfigs).flatMap(function (transitionConfig) {
2372
- return toArray(transitionConfig).map(function (transition) {
2373
- return formatTransition(stateNode, transition);
2374
- });
2375
- });
2376
- var _iterator6 = _createForOfIteratorHelper(delayedTransitions),
2377
- _step6;
2378
- try {
2379
- for (_iterator6.s(); !(_step6 = _iterator6.n()).done;) {
2380
- var delayedTransition = _step6.value;
2381
- formattedTransitions.push(delayedTransition);
2382
- }
2383
- } catch (err) {
2384
- _iterator6.e(err);
2385
- } finally {
2386
- _iterator6.f();
2387
- }
2388
- return formattedTransitions;
2389
- }
2390
- function formatInitialTransition(stateNode, _target) {
2391
- if (isString(_target) || isArray(_target)) {
2392
- var targets = toArray(_target).map(function (t) {
2393
- // Resolve state string keys (which represent children)
2394
- // to their state node
2395
- var descStateNode = isString(t) ? isStateId(t) ? stateNode.machine.getStateNodeById(t) : stateNode.states[t] : t;
2396
- if (!descStateNode) {
2397
- throw new Error("Initial state node \"".concat(t, "\" not found on parent state node #").concat(stateNode.id));
2398
- }
2399
- if (!isDescendant(descStateNode, stateNode)) {
2400
- throw new Error("Invalid initial target: state node #".concat(descStateNode.id, " is not a descendant of #").concat(stateNode.id));
2401
- }
2402
- return descStateNode;
2403
- });
2404
- var resolvedTarget = resolveTarget(stateNode, targets);
2405
- var transition = {
2406
- source: stateNode,
2407
- actions: [],
2408
- eventType: null,
2409
- reenter: false,
2410
- target: resolvedTarget,
2411
- toJSON: function toJSON() {
2412
- return _objectSpread2(_objectSpread2({}, transition), {}, {
2413
- source: "#".concat(stateNode.id),
2414
- target: resolvedTarget ? resolvedTarget.map(function (t) {
2415
- return "#".concat(t.id);
2416
- }) : undefined
2417
- });
2418
- }
2419
- };
2420
- return transition;
2421
- }
2422
- return formatTransition(stateNode, {
2423
- target: toArray(_target.target).map(function (t) {
2424
- if (isString(t)) {
2425
- return isStateId(t) ? t : "".concat(stateNode.machine.delimiter).concat(t);
2426
- }
2427
- return t;
2428
- }),
2429
- actions: _target.actions,
2430
- event: null
2431
- });
2432
- }
2433
- function resolveTarget(stateNode, targets) {
2434
- if (targets === undefined) {
2435
- // an undefined target signals that the state node should not transition from that state when receiving that event
2436
- return undefined;
2437
- }
2438
- return targets.map(function (target) {
2439
- if (!isString(target)) {
2440
- return target;
2441
- }
2442
- if (isStateId(target)) {
2443
- return stateNode.machine.getStateNodeById(target);
2444
- }
2445
- var isInternalTarget = target[0] === stateNode.machine.delimiter;
2446
- // If internal target is defined on machine,
2447
- // do not include machine key on target
2448
- if (isInternalTarget && !stateNode.parent) {
2449
- return getStateNodeByPath(stateNode, target.slice(1));
2450
- }
2451
- var resolvedTarget = isInternalTarget ? stateNode.key + target : target;
2452
- if (stateNode.parent) {
2453
- try {
2454
- var targetStateNode = getStateNodeByPath(stateNode.parent, resolvedTarget);
2455
- return targetStateNode;
2456
- } catch (err) {
2457
- throw new Error("Invalid transition definition for state node '".concat(stateNode.id, "':\n").concat(err.message));
2458
- }
2459
- } else {
2460
- throw new Error("Invalid target: \"".concat(target, "\" is not a valid target from the root node. Did you mean \".").concat(target, "\"?"));
2461
- }
2462
- });
2463
- }
2464
- function resolveHistoryTarget(stateNode) {
2465
- var normalizedTarget = normalizeTarget(stateNode.target);
2466
- if (!normalizedTarget) {
2467
- return stateNode.parent.initial.target;
2468
- }
2469
- return normalizedTarget.map(function (t) {
2470
- return typeof t === 'string' ? getStateNodeByPath(stateNode.parent, t) : t;
2471
- });
2472
- }
2473
- function isHistoryNode(stateNode) {
2474
- return stateNode.type === 'history';
2475
- }
2476
- function getInitialStateNodes(stateNode) {
2477
- var set = new Set();
2478
- function iter(descStateNode) {
2479
- if (set.has(descStateNode)) {
2480
- return;
2481
- }
2482
- set.add(descStateNode);
2483
- if (descStateNode.type === 'compound') {
2484
- var _iterator7 = _createForOfIteratorHelper(descStateNode.initial.target),
2485
- _step7;
2486
- try {
2487
- for (_iterator7.s(); !(_step7 = _iterator7.n()).done;) {
2488
- var targetStateNode = _step7.value;
2489
- var _iterator8 = _createForOfIteratorHelper(getProperAncestors(targetStateNode, stateNode)),
2490
- _step8;
2491
- try {
2492
- for (_iterator8.s(); !(_step8 = _iterator8.n()).done;) {
2493
- var a = _step8.value;
2494
- set.add(a);
2495
- }
2496
- } catch (err) {
2497
- _iterator8.e(err);
2498
- } finally {
2499
- _iterator8.f();
2500
- }
2501
- iter(targetStateNode);
2502
- }
2503
- } catch (err) {
2504
- _iterator7.e(err);
2505
- } finally {
2506
- _iterator7.f();
2507
- }
2508
- } else if (descStateNode.type === 'parallel') {
2509
- var _iterator9 = _createForOfIteratorHelper(getChildren(descStateNode)),
2510
- _step9;
2511
- try {
2512
- for (_iterator9.s(); !(_step9 = _iterator9.n()).done;) {
2513
- var child = _step9.value;
2514
- iter(child);
2515
- }
2516
- } catch (err) {
2517
- _iterator9.e(err);
2518
- } finally {
2519
- _iterator9.f();
2520
- }
2521
- }
2522
- }
2523
- iter(stateNode);
2524
- return _toConsumableArray(set);
2525
- }
2526
- /**
2527
- * Returns the child state node from its relative `stateKey`, or throws.
2528
- */
2529
- function getStateNode(stateNode, stateKey) {
2530
- if (isStateId(stateKey)) {
2531
- return stateNode.machine.getStateNodeById(stateKey);
2532
- }
2533
- if (!stateNode.states) {
2534
- throw new Error("Unable to retrieve child state '".concat(stateKey, "' from '").concat(stateNode.id, "'; no child states exist."));
2535
- }
2536
- var result = stateNode.states[stateKey];
2537
- if (!result) {
2538
- throw new Error("Child state '".concat(stateKey, "' does not exist on '").concat(stateNode.id, "'"));
2539
- }
2540
- return result;
2541
- }
2542
-
2543
- /**
2544
- * Returns the relative state node from the given `statePath`, or throws.
2545
- *
2546
- * @param statePath The string or string array relative path to the state node.
2547
- */
2548
- function getStateNodeByPath(stateNode, statePath) {
2549
- if (typeof statePath === 'string' && isStateId(statePath)) {
2550
- try {
2551
- return stateNode.machine.getStateNodeById(statePath);
2552
- } catch (e) {
2553
- // try individual paths
2554
- // throw e;
2555
- }
2556
- }
2557
- var arrayStatePath = toStatePath(statePath, stateNode.machine.delimiter).slice();
2558
- var currentStateNode = stateNode;
2559
- while (arrayStatePath.length) {
2560
- var key = arrayStatePath.shift();
2561
- if (!key.length) {
2562
- break;
2563
- }
2564
- currentStateNode = getStateNode(currentStateNode, key);
2565
- }
2566
- return currentStateNode;
2567
- }
2568
-
2569
- /**
2570
- * Returns the state nodes represented by the current state value.
2571
- *
2572
- * @param state The state value or State instance
2573
- */
2574
- function getStateNodes(stateNode, state) {
2575
- var stateValue = state instanceof State ? state.value : toStateValue(state, stateNode.machine.delimiter);
2576
- if (isString(stateValue)) {
2577
- return [stateNode, stateNode.states[stateValue]];
2578
- }
2579
- var childStateKeys = Object.keys(stateValue);
2580
- var childStateNodes = childStateKeys.map(function (subStateKey) {
2581
- return getStateNode(stateNode, subStateKey);
2582
- }).filter(Boolean);
2583
- return [stateNode.machine.root, stateNode].concat(childStateNodes, childStateKeys.reduce(function (allSubStateNodes, subStateKey) {
2584
- var subStateNode = getStateNode(stateNode, subStateKey);
2585
- if (!subStateNode) {
2586
- return allSubStateNodes;
2587
- }
2588
- var subStateNodes = getStateNodes(subStateNode, stateValue[subStateKey]);
2589
- return allSubStateNodes.concat(subStateNodes);
2590
- }, []));
2591
- }
2592
- function transitionAtomicNode(stateNode, stateValue, state, event) {
2593
- var childStateNode = getStateNode(stateNode, stateValue);
2594
- var next = childStateNode.next(state, event);
2595
- if (!next || !next.length) {
2596
- return stateNode.next(state, event);
2597
- }
2598
- return next;
2599
- }
2600
- function transitionCompoundNode(stateNode, stateValue, state, event) {
2601
- var subStateKeys = Object.keys(stateValue);
2602
- var childStateNode = getStateNode(stateNode, subStateKeys[0]);
2603
- var next = transitionNode(childStateNode, stateValue[subStateKeys[0]], state, event);
2604
- if (!next || !next.length) {
2605
- return stateNode.next(state, event);
2606
- }
2607
- return next;
2608
- }
2609
- function transitionParallelNode(stateNode, stateValue, state, event) {
2610
- var allInnerTransitions = [];
2611
- for (var _i3 = 0, _Object$keys2 = Object.keys(stateValue); _i3 < _Object$keys2.length; _i3++) {
2612
- var subStateKey = _Object$keys2[_i3];
2613
- var subStateValue = stateValue[subStateKey];
2614
- if (!subStateValue) {
2615
- continue;
2616
- }
2617
- var subStateNode = getStateNode(stateNode, subStateKey);
2618
- var innerTransitions = transitionNode(subStateNode, subStateValue, state, event);
2619
- if (innerTransitions) {
2620
- allInnerTransitions.push.apply(allInnerTransitions, _toConsumableArray(innerTransitions));
2621
- }
2622
- }
2623
- if (!allInnerTransitions.length) {
2624
- return stateNode.next(state, event);
2625
- }
2626
- return allInnerTransitions;
2627
- }
2628
- function transitionNode(stateNode, stateValue, state, event) {
2629
- // leaf node
2630
- if (isString(stateValue)) {
2631
- return transitionAtomicNode(stateNode, stateValue, state, event);
2632
- }
2633
-
2634
- // compound node
2635
- if (Object.keys(stateValue).length === 1) {
2636
- return transitionCompoundNode(stateNode, stateValue, state, event);
2637
- }
2638
-
2639
- // parallel node
2640
- return transitionParallelNode(stateNode, stateValue, state, event);
2641
- }
2642
- function getHistoryNodes(stateNode) {
2643
- return Object.keys(stateNode.states).map(function (key) {
2644
- return stateNode.states[key];
2645
- }).filter(function (sn) {
2646
- return sn.type === 'history';
2647
- });
2648
- }
2649
- function isDescendant(childStateNode, parentStateNode) {
2650
- var marker = childStateNode;
2651
- while (marker.parent && marker.parent !== parentStateNode) {
2652
- marker = marker.parent;
2653
- }
2654
- return marker.parent === parentStateNode;
2655
- }
2656
- function getPathFromRootToNode(stateNode) {
2657
- var path = [];
2658
- var marker = stateNode.parent;
2659
- while (marker) {
2660
- path.unshift(marker);
2661
- marker = marker.parent;
2662
- }
2663
- return path;
2664
- }
2665
- function hasIntersection(s1, s2) {
2666
- var set1 = new Set(s1);
2667
- var set2 = new Set(s2);
2668
- var _iterator10 = _createForOfIteratorHelper(set1),
2669
- _step10;
2670
- try {
2671
- for (_iterator10.s(); !(_step10 = _iterator10.n()).done;) {
2672
- var item = _step10.value;
2673
- if (set2.has(item)) {
2674
- return true;
2675
- }
2676
- }
2677
- } catch (err) {
2678
- _iterator10.e(err);
2679
- } finally {
2680
- _iterator10.f();
2681
- }
2682
- var _iterator11 = _createForOfIteratorHelper(set2),
2683
- _step11;
2684
- try {
2685
- for (_iterator11.s(); !(_step11 = _iterator11.n()).done;) {
2686
- var _item = _step11.value;
2687
- if (set1.has(_item)) {
2688
- return true;
2689
- }
2690
- }
2691
- } catch (err) {
2692
- _iterator11.e(err);
2693
- } finally {
2694
- _iterator11.f();
2695
- }
2696
- return false;
2697
- }
2698
- function removeConflictingTransitions(enabledTransitions, configuration, historyValue) {
2699
- var filteredTransitions = new Set();
2700
- var _iterator12 = _createForOfIteratorHelper(enabledTransitions),
2701
- _step12;
2702
- try {
2703
- for (_iterator12.s(); !(_step12 = _iterator12.n()).done;) {
2704
- var t1 = _step12.value;
2705
- var t1Preempted = false;
2706
- var transitionsToRemove = new Set();
2707
- var _iterator13 = _createForOfIteratorHelper(filteredTransitions),
2708
- _step13;
2709
- try {
2710
- for (_iterator13.s(); !(_step13 = _iterator13.n()).done;) {
2711
- var t2 = _step13.value;
2712
- if (hasIntersection(computeExitSet([t1], configuration, historyValue), computeExitSet([t2], configuration, historyValue))) {
2713
- if (isDescendant(t1.source, t2.source)) {
2714
- transitionsToRemove.add(t2);
2715
- } else {
2716
- t1Preempted = true;
2717
- break;
2718
- }
2719
- }
2720
- }
2721
- } catch (err) {
2722
- _iterator13.e(err);
2723
- } finally {
2724
- _iterator13.f();
2725
- }
2726
- if (!t1Preempted) {
2727
- var _iterator14 = _createForOfIteratorHelper(transitionsToRemove),
2728
- _step14;
2729
- try {
2730
- for (_iterator14.s(); !(_step14 = _iterator14.n()).done;) {
2731
- var t3 = _step14.value;
2732
- filteredTransitions["delete"](t3);
2733
- }
2734
- } catch (err) {
2735
- _iterator14.e(err);
2736
- } finally {
2737
- _iterator14.f();
2738
- }
2739
- filteredTransitions.add(t1);
2740
- }
2741
- }
2742
- } catch (err) {
2743
- _iterator12.e(err);
2744
- } finally {
2745
- _iterator12.f();
2746
- }
2747
- return Array.from(filteredTransitions);
2748
- }
2749
- function findLCCA(stateNodes) {
2750
- var _stateNodes = _slicedToArray(stateNodes, 1),
2751
- head = _stateNodes[0];
2752
- var current = getPathFromRootToNode(head);
2753
- var candidates = [];
2754
- var _iterator15 = _createForOfIteratorHelper(stateNodes),
2755
- _step15;
2756
- try {
2757
- var _loop = function _loop() {
2758
- var stateNode = _step15.value;
2759
- var path = getPathFromRootToNode(stateNode);
2760
- candidates = current.filter(function (sn) {
2761
- return path.includes(sn);
2762
- });
2763
- current = candidates;
2764
- candidates = [];
2765
- };
2766
- for (_iterator15.s(); !(_step15 = _iterator15.n()).done;) {
2767
- _loop();
2768
- }
2769
- } catch (err) {
2770
- _iterator15.e(err);
2771
- } finally {
2772
- _iterator15.f();
2773
- }
2774
- return current[current.length - 1];
2775
- }
2776
- function getEffectiveTargetStates(transition, historyValue) {
2777
- if (!transition.target) {
2778
- return [];
2779
- }
2780
- var targets = new Set();
2781
- var _iterator16 = _createForOfIteratorHelper(transition.target),
2782
- _step16;
2783
- try {
2784
- for (_iterator16.s(); !(_step16 = _iterator16.n()).done;) {
2785
- var targetNode = _step16.value;
2786
- if (isHistoryNode(targetNode)) {
2787
- if (historyValue[targetNode.id]) {
2788
- var _iterator17 = _createForOfIteratorHelper(historyValue[targetNode.id]),
2789
- _step17;
2790
- try {
2791
- for (_iterator17.s(); !(_step17 = _iterator17.n()).done;) {
2792
- var node = _step17.value;
2793
- targets.add(node);
2794
- }
2795
- } catch (err) {
2796
- _iterator17.e(err);
2797
- } finally {
2798
- _iterator17.f();
2799
- }
2800
- } else {
2801
- var _iterator18 = _createForOfIteratorHelper(getEffectiveTargetStates({
2802
- target: resolveHistoryTarget(targetNode)
2803
- }, historyValue)),
2804
- _step18;
2805
- try {
2806
- for (_iterator18.s(); !(_step18 = _iterator18.n()).done;) {
2807
- var _node = _step18.value;
2808
- targets.add(_node);
2809
- }
2810
- } catch (err) {
2811
- _iterator18.e(err);
2812
- } finally {
2813
- _iterator18.f();
2814
- }
2815
- }
2816
- } else {
2817
- targets.add(targetNode);
2818
- }
2819
- }
2820
- } catch (err) {
2821
- _iterator16.e(err);
2822
- } finally {
2823
- _iterator16.f();
2824
- }
2825
- return _toConsumableArray(targets);
2826
- }
2827
- function getTransitionDomain(transition, historyValue) {
2828
- var targetStates = getEffectiveTargetStates(transition, historyValue);
2829
- if (!targetStates) {
2830
- return null;
2831
- }
2832
- if (!transition.reenter && transition.source.type !== 'parallel' && targetStates.every(function (targetStateNode) {
2833
- return isDescendant(targetStateNode, transition.source);
2834
- })) {
2835
- return transition.source;
2836
- }
2837
- var lcca = findLCCA(targetStates.concat(transition.source));
2838
- return lcca;
2839
- }
2840
- function computeExitSet(transitions, configuration, historyValue) {
2841
- var statesToExit = new Set();
2842
- var _iterator19 = _createForOfIteratorHelper(transitions),
2843
- _step19;
2844
- try {
2845
- for (_iterator19.s(); !(_step19 = _iterator19.n()).done;) {
2846
- var _t$target;
2847
- var t = _step19.value;
2848
- if ((_t$target = t.target) !== null && _t$target !== void 0 && _t$target.length) {
2849
- var domain = getTransitionDomain(t, historyValue);
2850
- var _iterator20 = _createForOfIteratorHelper(configuration),
2851
- _step20;
2852
- try {
2853
- for (_iterator20.s(); !(_step20 = _iterator20.n()).done;) {
2854
- var stateNode = _step20.value;
2855
- if (isDescendant(stateNode, domain)) {
2856
- statesToExit.add(stateNode);
2857
- }
2858
- }
2859
- } catch (err) {
2860
- _iterator20.e(err);
2861
- } finally {
2862
- _iterator20.f();
2863
- }
2864
- }
2865
- }
2866
- } catch (err) {
2867
- _iterator19.e(err);
2868
- } finally {
2869
- _iterator19.f();
2870
- }
2871
- return _toConsumableArray(statesToExit);
2872
- }
2873
-
2874
- /**
2875
- * https://www.w3.org/TR/scxml/#microstepProcedure
2876
- *
2877
- * @private
2878
- * @param transitions
2879
- * @param currentState
2880
- * @param mutConfiguration
2881
- */
2882
-
2883
- function microstep(transitions, currentState, actorCtx, event) {
2884
- var machine = currentState.machine;
2885
- // Transition will "apply" if:
2886
- // - the state node is the initial state (there is no current state)
2887
- // - OR there are transitions
2888
- var willTransition = currentState._initial || transitions.length > 0;
2889
- var mutConfiguration = new Set(currentState.configuration);
2890
- if (!currentState._initial && !willTransition) {
2891
- var inertState = cloneState(currentState, {
2892
- event: event,
2893
- actions: [],
2894
- transitions: []
2895
- });
2896
- inertState.changed = false;
2897
- return inertState;
2898
- }
2899
- var microstate = microstepProcedure(currentState._initial ? [{
2900
- target: _toConsumableArray(currentState.configuration).filter(isAtomicStateNode),
2901
- source: machine.root,
2902
- reenter: true,
2903
- actions: [],
2904
- eventType: null,
2905
- toJSON: null // TODO: fix
2906
- }] : transitions, currentState, mutConfiguration, event, actorCtx);
2907
- var context = microstate.context,
2908
- nonRaisedActions = microstate.actions;
2909
- var children = setChildren(currentState, nonRaisedActions);
2910
- var nextState = cloneState(microstate, {
2911
- value: {},
2912
- // TODO: make optional
2913
- transitions: transitions,
2914
- children: children
2915
- });
2916
- nextState.changed = currentState._initial ? undefined : !stateValuesEqual(nextState.value, currentState.value) || nextState.actions.length > 0 || context !== currentState.context;
2917
- return nextState;
2918
- }
2919
- function setChildren(currentState, nonRaisedActions) {
2920
- var children = _objectSpread2({}, currentState.children);
2921
- var _iterator21 = _createForOfIteratorHelper(nonRaisedActions),
2922
- _step21;
2923
- try {
2924
- for (_iterator21.s(); !(_step21 = _iterator21.n()).done;) {
2925
- var action = _step21.value;
2926
- if (action.type === invoke$1 && action.params.ref) {
2927
- var ref = action.params.ref;
2928
- if (ref) {
2929
- children[ref.id] = ref;
2930
- }
2931
- } else if (action.type === stop$1) {
2932
- var _ref = action.params.actor;
2933
- if (_ref) {
2934
- delete children[_ref.id];
2935
- }
2936
- }
2937
- }
2938
- } catch (err) {
2939
- _iterator21.e(err);
2940
- } finally {
2941
- _iterator21.f();
2942
- }
2943
- return children;
2944
- }
2945
- function microstepProcedure(transitions, currentState, mutConfiguration, event, actorCtx) {
2946
- var actions = [];
2947
- var historyValue = _objectSpread2({}, currentState.historyValue);
2948
- var filteredTransitions = removeConflictingTransitions(transitions, mutConfiguration, historyValue);
2949
- var internalQueue = _toConsumableArray(currentState._internalQueue);
2950
-
2951
- // Exit states
2952
- if (!currentState._initial) {
2953
- exitStates(filteredTransitions, mutConfiguration, historyValue, actions);
2954
- }
2955
-
2956
- // Execute transition content
2957
- actions.push.apply(actions, _toConsumableArray(filteredTransitions.flatMap(function (t) {
2958
- return t.actions;
2959
- })));
2960
-
2961
- // Enter states
2962
- enterStates(filteredTransitions, mutConfiguration, actions, internalQueue, currentState, historyValue);
2963
- var nextConfiguration = _toConsumableArray(mutConfiguration);
2964
- var done = isInFinalState(nextConfiguration);
2965
- if (done) {
2966
- var finalActions = nextConfiguration.sort(function (a, b) {
2967
- return b.order - a.order;
2968
- }).flatMap(function (state) {
2969
- return state.exit;
2970
- });
2971
- actions.push.apply(actions, _toConsumableArray(finalActions));
2972
- }
2973
- try {
2974
- var _resolveActionsAndCon = resolveActionsAndContext(actions, event, currentState, actorCtx),
2975
- nextState = _resolveActionsAndCon.nextState;
2976
- var output = done ? getOutput(nextConfiguration, nextState.context, event) : undefined;
2977
- internalQueue.push.apply(internalQueue, _toConsumableArray(nextState._internalQueue));
2978
- return cloneState(currentState, {
2979
- actions: nextState.actions,
2980
- configuration: nextConfiguration,
2981
- historyValue: historyValue,
2982
- _internalQueue: internalQueue,
2983
- context: nextState.context,
2984
- event: event,
2985
- done: done,
2986
- output: output,
2987
- children: nextState.children
2988
- });
2989
- } catch (e) {
2990
- // TODO: Refactor this once proper error handling is implemented.
2991
- // See https://github.com/statelyai/rfcs/pull/4
2992
- throw e;
2993
- }
2994
- }
2995
- function enterStates(filteredTransitions, mutConfiguration, actions, internalQueue, currentState, historyValue) {
2996
- var statesToEnter = new Set();
2997
- var statesForDefaultEntry = new Set();
2998
- computeEntrySet(filteredTransitions, historyValue, statesForDefaultEntry, statesToEnter);
2999
-
3000
- // In the initial state, the root state node is "entered".
3001
- if (currentState._initial) {
3002
- statesForDefaultEntry.add(currentState.machine.root);
3003
- }
3004
- var _iterator22 = _createForOfIteratorHelper(_toConsumableArray(statesToEnter).sort(function (a, b) {
3005
- return a.order - b.order;
3006
- })),
3007
- _step22;
3008
- try {
3009
- for (_iterator22.s(); !(_step22 = _iterator22.n()).done;) {
3010
- var stateNodeToEnter = _step22.value;
3011
- mutConfiguration.add(stateNodeToEnter);
3012
- var _iterator23 = _createForOfIteratorHelper(stateNodeToEnter.invoke),
3013
- _step23;
3014
- try {
3015
- for (_iterator23.s(); !(_step23 = _iterator23.n()).done;) {
3016
- var invokeDef = _step23.value;
3017
- actions.push(invoke(invokeDef));
3018
- }
3019
-
3020
- // Add entry actions
3021
- } catch (err) {
3022
- _iterator23.e(err);
3023
- } finally {
3024
- _iterator23.f();
3025
- }
3026
- actions.push.apply(actions, _toConsumableArray(stateNodeToEnter.entry));
3027
- if (statesForDefaultEntry.has(stateNodeToEnter)) {
3028
- var _iterator24 = _createForOfIteratorHelper(statesForDefaultEntry),
3029
- _step24;
3030
- try {
3031
- for (_iterator24.s(); !(_step24 = _iterator24.n()).done;) {
3032
- var stateNode = _step24.value;
3033
- var initialActions = stateNode.initial.actions;
3034
- actions.push.apply(actions, _toConsumableArray(initialActions));
3035
- }
3036
- } catch (err) {
3037
- _iterator24.e(err);
3038
- } finally {
3039
- _iterator24.f();
3040
- }
3041
- }
3042
- if (stateNodeToEnter.type === 'final') {
3043
- var parent = stateNodeToEnter.parent;
3044
- if (!parent.parent) {
3045
- continue;
3046
- }
3047
- internalQueue.push(done(parent.id, stateNodeToEnter.output ? mapContext(stateNodeToEnter.output, currentState.context, currentState.event) : undefined));
3048
- if (parent.parent) {
3049
- var grandparent = parent.parent;
3050
- if (grandparent.type === 'parallel') {
3051
- if (getChildren(grandparent).every(function (parentNode) {
3052
- return isInFinalState(_toConsumableArray(mutConfiguration), parentNode);
3053
- })) {
3054
- internalQueue.push(done(grandparent.id));
3055
- }
3056
- }
3057
- }
3058
- }
3059
- }
3060
- } catch (err) {
3061
- _iterator22.e(err);
3062
- } finally {
3063
- _iterator22.f();
3064
- }
3065
- }
3066
- function computeEntrySet(transitions, historyValue, statesForDefaultEntry, statesToEnter) {
3067
- var _iterator25 = _createForOfIteratorHelper(transitions),
3068
- _step25;
3069
- try {
3070
- for (_iterator25.s(); !(_step25 = _iterator25.n()).done;) {
3071
- var t = _step25.value;
3072
- var _iterator26 = _createForOfIteratorHelper(t.target || []),
3073
- _step26;
3074
- try {
3075
- for (_iterator26.s(); !(_step26 = _iterator26.n()).done;) {
3076
- var s = _step26.value;
3077
- addDescendantStatesToEnter(s, historyValue, statesForDefaultEntry, statesToEnter);
3078
- }
3079
- } catch (err) {
3080
- _iterator26.e(err);
3081
- } finally {
3082
- _iterator26.f();
3083
- }
3084
- var ancestor = getTransitionDomain(t, historyValue);
3085
- var targetStates = getEffectiveTargetStates(t, historyValue);
3086
- var _iterator27 = _createForOfIteratorHelper(targetStates),
3087
- _step27;
3088
- try {
3089
- for (_iterator27.s(); !(_step27 = _iterator27.n()).done;) {
3090
- var _s2 = _step27.value;
3091
- addAncestorStatesToEnter(_s2, ancestor, statesToEnter, historyValue, statesForDefaultEntry);
3092
- }
3093
- } catch (err) {
3094
- _iterator27.e(err);
3095
- } finally {
3096
- _iterator27.f();
3097
- }
3098
- }
3099
- } catch (err) {
3100
- _iterator25.e(err);
3101
- } finally {
3102
- _iterator25.f();
3103
- }
3104
- }
3105
- function addDescendantStatesToEnter(stateNode, historyValue, statesForDefaultEntry, statesToEnter) {
3106
- if (isHistoryNode(stateNode)) {
3107
- if (historyValue[stateNode.id]) {
3108
- var historyStateNodes = historyValue[stateNode.id];
3109
- var _iterator28 = _createForOfIteratorHelper(historyStateNodes),
3110
- _step28;
3111
- try {
3112
- for (_iterator28.s(); !(_step28 = _iterator28.n()).done;) {
3113
- var s = _step28.value;
3114
- addDescendantStatesToEnter(s, historyValue, statesForDefaultEntry, statesToEnter);
3115
- }
3116
- } catch (err) {
3117
- _iterator28.e(err);
3118
- } finally {
3119
- _iterator28.f();
3120
- }
3121
- var _iterator29 = _createForOfIteratorHelper(historyStateNodes),
3122
- _step29;
3123
- try {
3124
- for (_iterator29.s(); !(_step29 = _iterator29.n()).done;) {
3125
- var _s3 = _step29.value;
3126
- addAncestorStatesToEnter(_s3, stateNode.parent, statesToEnter, historyValue, statesForDefaultEntry);
3127
- var _iterator30 = _createForOfIteratorHelper(statesForDefaultEntry),
3128
- _step30;
3129
- try {
3130
- for (_iterator30.s(); !(_step30 = _iterator30.n()).done;) {
3131
- var stateForDefaultEntry = _step30.value;
3132
- statesForDefaultEntry.add(stateForDefaultEntry);
3133
- }
3134
- } catch (err) {
3135
- _iterator30.e(err);
3136
- } finally {
3137
- _iterator30.f();
3138
- }
3139
- }
3140
- } catch (err) {
3141
- _iterator29.e(err);
3142
- } finally {
3143
- _iterator29.f();
3144
- }
3145
- } else {
3146
- var targets = resolveHistoryTarget(stateNode);
3147
- var _iterator31 = _createForOfIteratorHelper(targets),
3148
- _step31;
3149
- try {
3150
- for (_iterator31.s(); !(_step31 = _iterator31.n()).done;) {
3151
- var _s4 = _step31.value;
3152
- addDescendantStatesToEnter(_s4, historyValue, statesForDefaultEntry, statesToEnter);
3153
- }
3154
- } catch (err) {
3155
- _iterator31.e(err);
3156
- } finally {
3157
- _iterator31.f();
3158
- }
3159
- var _iterator32 = _createForOfIteratorHelper(targets),
3160
- _step32;
3161
- try {
3162
- for (_iterator32.s(); !(_step32 = _iterator32.n()).done;) {
3163
- var _s5 = _step32.value;
3164
- addAncestorStatesToEnter(_s5, stateNode, statesToEnter, historyValue, statesForDefaultEntry);
3165
- var _iterator33 = _createForOfIteratorHelper(statesForDefaultEntry),
3166
- _step33;
3167
- try {
3168
- for (_iterator33.s(); !(_step33 = _iterator33.n()).done;) {
3169
- var _stateForDefaultEntry = _step33.value;
3170
- statesForDefaultEntry.add(_stateForDefaultEntry);
3171
- }
3172
- } catch (err) {
3173
- _iterator33.e(err);
3174
- } finally {
3175
- _iterator33.f();
3176
- }
3177
- }
3178
- } catch (err) {
3179
- _iterator32.e(err);
3180
- } finally {
3181
- _iterator32.f();
3182
- }
3183
- }
3184
- } else {
3185
- statesToEnter.add(stateNode);
3186
- if (stateNode.type === 'compound') {
3187
- statesForDefaultEntry.add(stateNode);
3188
- var initialStates = stateNode.initial.target;
3189
- var _iterator34 = _createForOfIteratorHelper(initialStates),
3190
- _step34;
3191
- try {
3192
- for (_iterator34.s(); !(_step34 = _iterator34.n()).done;) {
3193
- var initialState = _step34.value;
3194
- addDescendantStatesToEnter(initialState, historyValue, statesForDefaultEntry, statesToEnter);
3195
- }
3196
- } catch (err) {
3197
- _iterator34.e(err);
3198
- } finally {
3199
- _iterator34.f();
3200
- }
3201
- var _iterator35 = _createForOfIteratorHelper(initialStates),
3202
- _step35;
3203
- try {
3204
- for (_iterator35.s(); !(_step35 = _iterator35.n()).done;) {
3205
- var _initialState = _step35.value;
3206
- addAncestorStatesToEnter(_initialState, stateNode, statesToEnter, historyValue, statesForDefaultEntry);
3207
- }
3208
- } catch (err) {
3209
- _iterator35.e(err);
3210
- } finally {
3211
- _iterator35.f();
3212
- }
3213
- } else {
3214
- if (stateNode.type === 'parallel') {
3215
- var _iterator36 = _createForOfIteratorHelper(getChildren(stateNode).filter(function (sn) {
3216
- return !isHistoryNode(sn);
3217
- })),
3218
- _step36;
3219
- try {
3220
- var _loop2 = function _loop2() {
3221
- var child = _step36.value;
3222
- if (!_toConsumableArray(statesToEnter).some(function (s) {
3223
- return isDescendant(s, child);
3224
- })) {
3225
- addDescendantStatesToEnter(child, historyValue, statesForDefaultEntry, statesToEnter);
3226
- }
3227
- };
3228
- for (_iterator36.s(); !(_step36 = _iterator36.n()).done;) {
3229
- _loop2();
3230
- }
3231
- } catch (err) {
3232
- _iterator36.e(err);
3233
- } finally {
3234
- _iterator36.f();
3235
- }
3236
- }
3237
- }
3238
- }
3239
- }
3240
- function addAncestorStatesToEnter(stateNode, toStateNode, statesToEnter, historyValue, statesForDefaultEntry) {
3241
- var properAncestors = getProperAncestors(stateNode, toStateNode);
3242
- var _iterator37 = _createForOfIteratorHelper(properAncestors),
3243
- _step37;
3244
- try {
3245
- for (_iterator37.s(); !(_step37 = _iterator37.n()).done;) {
3246
- var anc = _step37.value;
3247
- statesToEnter.add(anc);
3248
- if (anc.type === 'parallel') {
3249
- var _iterator38 = _createForOfIteratorHelper(getChildren(anc).filter(function (sn) {
3250
- return !isHistoryNode(sn);
3251
- })),
3252
- _step38;
3253
- try {
3254
- var _loop3 = function _loop3() {
3255
- var child = _step38.value;
3256
- if (!_toConsumableArray(statesToEnter).some(function (s) {
3257
- return isDescendant(s, child);
3258
- })) {
3259
- addDescendantStatesToEnter(child, historyValue, statesForDefaultEntry, statesToEnter);
3260
- }
3261
- };
3262
- for (_iterator38.s(); !(_step38 = _iterator38.n()).done;) {
3263
- _loop3();
3264
- }
3265
- } catch (err) {
3266
- _iterator38.e(err);
3267
- } finally {
3268
- _iterator38.f();
3269
- }
3270
- }
3271
- }
3272
- } catch (err) {
3273
- _iterator37.e(err);
3274
- } finally {
3275
- _iterator37.f();
3276
- }
3277
- }
3278
- function exitStates(transitions, mutConfiguration, historyValue, actions) {
3279
- var statesToExit = computeExitSet(transitions, mutConfiguration, historyValue);
3280
- statesToExit.sort(function (a, b) {
3281
- return b.order - a.order;
3282
- });
3283
-
3284
- // From SCXML algorithm: https://www.w3.org/TR/scxml/#exitStates
3285
- var _iterator39 = _createForOfIteratorHelper(statesToExit),
3286
- _step39;
3287
- try {
3288
- var _loop4 = function _loop4() {
3289
- var exitStateNode = _step39.value;
3290
- var _iterator41 = _createForOfIteratorHelper(getHistoryNodes(exitStateNode)),
3291
- _step41;
3292
- try {
3293
- for (_iterator41.s(); !(_step41 = _iterator41.n()).done;) {
3294
- var historyNode = _step41.value;
3295
- var predicate = void 0;
3296
- if (historyNode.history === 'deep') {
3297
- predicate = function predicate(sn) {
3298
- return isAtomicStateNode(sn) && isDescendant(sn, exitStateNode);
3299
- };
3300
- } else {
3301
- predicate = function predicate(sn) {
3302
- return sn.parent === exitStateNode;
3303
- };
3304
- }
3305
- historyValue[historyNode.id] = Array.from(mutConfiguration).filter(predicate);
3306
- }
3307
- } catch (err) {
3308
- _iterator41.e(err);
3309
- } finally {
3310
- _iterator41.f();
3311
- }
3312
- };
3313
- for (_iterator39.s(); !(_step39 = _iterator39.n()).done;) {
3314
- _loop4();
3315
- }
3316
- } catch (err) {
3317
- _iterator39.e(err);
3318
- } finally {
3319
- _iterator39.f();
3320
- }
3321
- var _iterator40 = _createForOfIteratorHelper(statesToExit),
3322
- _step40;
3323
- try {
3324
- for (_iterator40.s(); !(_step40 = _iterator40.n()).done;) {
3325
- var s = _step40.value;
3326
- actions.push.apply(actions, _toConsumableArray(s.exit.flat()).concat(_toConsumableArray(s.invoke.map(function (def) {
3327
- return stop(def.id);
3328
- }))));
3329
- mutConfiguration["delete"](s);
3330
- }
3331
- } catch (err) {
3332
- _iterator40.e(err);
3333
- } finally {
3334
- _iterator40.f();
3335
- }
3336
- }
3337
- function resolveActionsAndContext(actions, event, currentState, actorCtx) {
3338
- var machine = currentState.machine;
3339
- var resolvedActions = [];
3340
- var raiseActions = [];
3341
- var intermediateState = currentState;
3342
- function handleAction(action) {
3343
- resolvedActions.push(action);
3344
- if ((actorCtx === null || actorCtx === void 0 ? void 0 : actorCtx.self.status) === ActorStatus.Running) {
3345
- var _action$execute;
3346
- (_action$execute = action.execute) === null || _action$execute === void 0 ? void 0 : _action$execute.call(action, actorCtx);
3347
- // TODO: this is hacky; re-evaluate
3348
- delete action.execute;
3349
- }
3350
- }
3351
- function resolveAction(actionObject) {
3352
- var executableActionObject = resolveActionObject(actionObject, machine.options.actions);
3353
- if (isDynamicAction(executableActionObject)) {
3354
- var _resolvedAction$param;
3355
- var _executableActionObje = executableActionObject.resolve(event, {
3356
- state: intermediateState,
3357
- action: actionObject,
3358
- actorContext: actorCtx
3359
- }),
3360
- _executableActionObje2 = _slicedToArray(_executableActionObje, 2),
3361
- nextState = _executableActionObje2[0],
3362
- resolvedAction = _executableActionObje2[1];
3363
- var matchedActions = (_resolvedAction$param = resolvedAction.params) === null || _resolvedAction$param === void 0 ? void 0 : _resolvedAction$param.actions;
3364
- intermediateState = nextState;
3365
- if ((resolvedAction.type === raise$1 || resolvedAction.type === send$1 && resolvedAction.params.internal) && typeof resolvedAction.params.delay !== 'number') {
3366
- raiseActions.push(resolvedAction);
3367
- }
3368
-
3369
- // TODO: remove the check; just handleAction
3370
- if (resolvedAction.type !== pure$1) {
3371
- handleAction(resolvedAction);
3372
- }
3373
- toActionObjects(matchedActions).forEach(resolveAction);
3374
- return;
3375
- }
3376
- handleAction(executableActionObject);
3377
- }
3378
- var _iterator42 = _createForOfIteratorHelper(actions),
3379
- _step42;
3380
- try {
3381
- for (_iterator42.s(); !(_step42 = _iterator42.n()).done;) {
3382
- var actionObject = _step42.value;
3383
- resolveAction(actionObject);
3384
- }
3385
- } catch (err) {
3386
- _iterator42.e(err);
3387
- } finally {
3388
- _iterator42.f();
3389
- }
3390
- return {
3391
- nextState: cloneState(intermediateState, {
3392
- actions: resolvedActions,
3393
- _internalQueue: raiseActions.map(function (a) {
3394
- return a.params.event;
3395
- })
3396
- })
3397
- };
3398
- }
3399
- function macrostep(state, event, actorCtx) {
3400
- if (!IS_PRODUCTION && event.type === WILDCARD) {
3401
- throw new Error("An event cannot have the wildcard type ('".concat(WILDCARD, "')"));
3402
- }
3403
- var nextState = state;
3404
- var states = [];
3405
-
3406
- // Handle stop event
3407
- if (event.type === stopSignalType) {
3408
- nextState = stopStep(event, nextState, actorCtx);
3409
- states.push(nextState);
3410
- return {
3411
- state: nextState,
3412
- microstates: states
3413
- };
3414
- }
3415
-
3416
- // Assume the state is at rest (no raised events)
3417
- // Determine the next state based on the next microstep
3418
- if (event.type !== init) {
3419
- var transitions = selectTransitions(event, nextState);
3420
- nextState = microstep(transitions, state, actorCtx, event);
3421
- states.push(nextState);
3422
- }
3423
- while (!nextState.done) {
3424
- var enabledTransitions = selectEventlessTransitions(nextState);
3425
- if (enabledTransitions.length === 0) {
3426
- // TODO: this is a bit of a hack, we need to review this
3427
- // this matches the behavior from v4 for eventless transitions
3428
- // where for `hasAlwaysTransitions` we were always trying to resolve with a NULL event
3429
- // and if a transition was not selected the `state.transitions` stayed empty
3430
- // without this we get into an infinite loop in the dieHard test in `@xstate/test` for the `simplePathsTo`
3431
- if (nextState.configuration.some(function (state) {
3432
- return state.always;
3433
- })) {
3434
- nextState.transitions = [];
3435
- }
3436
- if (!nextState._internalQueue.length) {
3437
- break;
3438
- } else {
3439
- var _nextState$actions;
3440
- var currentActions = nextState.actions;
3441
- var nextEvent = nextState._internalQueue[0];
3442
- var _transitions = selectTransitions(nextEvent, nextState);
3443
- nextState = microstep(_transitions, nextState, actorCtx, nextEvent);
3444
- nextState._internalQueue.shift();
3445
- (_nextState$actions = nextState.actions).unshift.apply(_nextState$actions, _toConsumableArray(currentActions));
3446
- states.push(nextState);
3447
- }
3448
- }
3449
- if (enabledTransitions.length) {
3450
- var _nextState$actions2;
3451
- var _currentActions = nextState.actions;
3452
- nextState = microstep(enabledTransitions, nextState, actorCtx, nextState.event);
3453
- (_nextState$actions2 = nextState.actions).unshift.apply(_nextState$actions2, _toConsumableArray(_currentActions));
3454
- states.push(nextState);
3455
- }
3456
- }
3457
- if (nextState.done) {
3458
- // Perform the stop step to ensure that child actors are stopped
3459
- stopStep(nextState.event, nextState, actorCtx);
3460
- }
3461
- return {
3462
- state: nextState,
3463
- microstates: states
3464
- };
3465
- }
3466
- function stopStep(event, nextState, actorCtx) {
3467
- var actions = [];
3468
- var _iterator43 = _createForOfIteratorHelper(nextState.configuration.sort(function (a, b) {
3469
- return b.order - a.order;
3470
- })),
3471
- _step43;
3472
- try {
3473
- for (_iterator43.s(); !(_step43 = _iterator43.n()).done;) {
3474
- var stateNode = _step43.value;
3475
- actions.push.apply(actions, _toConsumableArray(stateNode.exit));
3476
- }
3477
- } catch (err) {
3478
- _iterator43.e(err);
3479
- } finally {
3480
- _iterator43.f();
3481
- }
3482
- for (var _i4 = 0, _Object$values = Object.values(nextState.children); _i4 < _Object$values.length; _i4++) {
3483
- var child = _Object$values[_i4];
3484
- actions.push(stop(child));
3485
- }
3486
- var _resolveActionsAndCon2 = resolveActionsAndContext(actions, event, nextState, actorCtx),
3487
- stoppedState = _resolveActionsAndCon2.nextState;
3488
- return stoppedState;
3489
- }
3490
- function selectTransitions(event, nextState) {
3491
- return nextState.machine.getTransitionData(nextState, event);
3492
- }
3493
- function selectEventlessTransitions(nextState) {
3494
- var enabledTransitionSet = new Set();
3495
- var atomicStates = nextState.configuration.filter(isAtomicStateNode);
3496
- var _iterator44 = _createForOfIteratorHelper(atomicStates),
3497
- _step44;
3498
- try {
3499
- for (_iterator44.s(); !(_step44 = _iterator44.n()).done;) {
3500
- var stateNode = _step44.value;
3501
- var _iterator45 = _createForOfIteratorHelper([stateNode].concat(getProperAncestors(stateNode, null))),
3502
- _step45;
3503
- try {
3504
- loop: for (_iterator45.s(); !(_step45 = _iterator45.n()).done;) {
3505
- var s = _step45.value;
3506
- if (!s.always) {
3507
- continue;
3508
- }
3509
- var _iterator46 = _createForOfIteratorHelper(s.always),
3510
- _step46;
3511
- try {
3512
- for (_iterator46.s(); !(_step46 = _iterator46.n()).done;) {
3513
- var transition = _step46.value;
3514
- if (transition.guard === undefined || evaluateGuard(transition.guard, nextState.context, nextState.event, nextState)) {
3515
- enabledTransitionSet.add(transition);
3516
- break loop;
3517
- }
3518
- }
3519
- } catch (err) {
3520
- _iterator46.e(err);
3521
- } finally {
3522
- _iterator46.f();
3523
- }
3524
- }
3525
- } catch (err) {
3526
- _iterator45.e(err);
3527
- } finally {
3528
- _iterator45.f();
3529
- }
3530
- }
3531
- } catch (err) {
3532
- _iterator44.e(err);
3533
- } finally {
3534
- _iterator44.f();
3535
- }
3536
- return removeConflictingTransitions(Array.from(enabledTransitionSet), new Set(nextState.configuration), nextState.historyValue);
3537
- }
3538
-
3539
- /**
3540
- * Resolves a partial state value with its full representation in the state node's machine.
3541
- *
3542
- * @param stateValue The partial state value to resolve.
3543
- */
3544
- function resolveStateValue(rootNode, stateValue) {
3545
- var configuration = getConfiguration(getStateNodes(rootNode, stateValue));
3546
- return getStateValue(rootNode, _toConsumableArray(configuration));
3547
- }
3548
- function stateValuesEqual(a, b) {
3549
- if (a === b) {
3550
- return true;
3551
- }
3552
- if (a === undefined || b === undefined) {
3553
- return false;
3554
- }
3555
- if (isString(a) || isString(b)) {
3556
- return a === b;
3557
- }
3558
- var aKeys = Object.keys(a);
3559
- var bKeys = Object.keys(b);
3560
- return aKeys.length === bKeys.length && aKeys.every(function (key) {
3561
- return stateValuesEqual(a[key], b[key]);
3562
- });
3563
- }
3564
- function getInitialConfiguration(rootNode) {
3565
- var configuration = [];
3566
- var initialTransition = rootNode.initial;
3567
- var statesToEnter = new Set();
3568
- var statesForDefaultEntry = new Set([rootNode]);
3569
- computeEntrySet([initialTransition], {}, statesForDefaultEntry, statesToEnter);
3570
- var _iterator47 = _createForOfIteratorHelper(_toConsumableArray(statesToEnter).sort(function (a, b) {
3571
- return a.order - b.order;
3572
- })),
3573
- _step47;
3574
- try {
3575
- for (_iterator47.s(); !(_step47 = _iterator47.n()).done;) {
3576
- var stateNodeToEnter = _step47.value;
3577
- configuration.push(stateNodeToEnter);
3578
- }
3579
- } catch (err) {
3580
- _iterator47.e(err);
3581
- } finally {
3582
- _iterator47.f();
3583
- }
3584
- return configuration;
3585
- }
3586
-
3587
- var _excluded = ["configuration", "transitions", "tags", "machine"],
3588
- _excluded2 = ["configuration", "transitions", "tags", "machine", "children"];
3589
- var State = /*#__PURE__*/function () {
3590
- /**
3591
- * Creates a new `State` instance that represents the current state of a running machine.
3592
- *
3593
- * @param config
3594
- */
3595
- function State(config, machine) {
3596
- var _config$_internalQueu, _config$actions, _config$configuration, _config$done;
3597
- _classCallCheck(this, State);
3598
- this.machine = machine;
3599
- _defineProperty(this, "tags", void 0);
3600
- _defineProperty(this, "value", void 0);
3601
- _defineProperty(this, "done", void 0);
3602
- _defineProperty(this, "output", void 0);
3603
- _defineProperty(this, "context", void 0);
3604
- _defineProperty(this, "historyValue", {});
3605
- _defineProperty(this, "actions", []);
3606
- _defineProperty(this, "event", void 0);
3607
- _defineProperty(this, "_internalQueue", void 0);
3608
- _defineProperty(this, "_initial", false);
3609
- _defineProperty(this, "changed", void 0);
3610
- _defineProperty(this, "configuration", void 0);
3611
- _defineProperty(this, "transitions", void 0);
3612
- _defineProperty(this, "children", void 0);
3613
- this.context = config.context;
3614
- this._internalQueue = (_config$_internalQueu = config._internalQueue) !== null && _config$_internalQueu !== void 0 ? _config$_internalQueu : [];
3615
- this.event = config.event;
3616
- this.historyValue = config.historyValue || {};
3617
- this.actions = (_config$actions = config.actions) !== null && _config$actions !== void 0 ? _config$actions : [];
3618
- this.matches = this.matches.bind(this);
3619
- this.toStrings = this.toStrings.bind(this);
3620
- this.configuration = (_config$configuration = config.configuration) !== null && _config$configuration !== void 0 ? _config$configuration : Array.from(getConfiguration(getStateNodes(machine.root, config.value)));
3621
- this.transitions = config.transitions;
3622
- this.children = config.children;
3623
- this.value = getStateValue(machine.root, this.configuration);
3624
- this.tags = new Set(flatten(this.configuration.map(function (sn) {
3625
- return sn.tags;
3626
- })));
3627
- this.done = (_config$done = config.done) !== null && _config$done !== void 0 ? _config$done : false;
3628
- this.output = config.output;
3629
- }
3630
-
3631
- /**
3632
- * Returns an array of all the string leaf state node paths.
3633
- * @param stateValue
3634
- * @param delimiter The character(s) that separate each subpath in the string state node path.
3635
- */
3636
- _createClass(State, [{
3637
- key: "toStrings",
3638
- value: function toStrings() {
3639
- var _this = this;
3640
- var stateValue = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.value;
3641
- var delimiter = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '.';
3642
- if (isString(stateValue)) {
3643
- return [stateValue];
3644
- }
3645
- var valueKeys = Object.keys(stateValue);
3646
- return valueKeys.concat.apply(valueKeys, _toConsumableArray(valueKeys.map(function (key) {
3647
- return _this.toStrings(stateValue[key], delimiter).map(function (s) {
3648
- return key + delimiter + s;
3649
- });
3650
- })));
3651
- }
3652
- }, {
3653
- key: "toJSON",
3654
- value: function toJSON() {
3655
- this.configuration;
3656
- this.transitions;
3657
- var tags = this.tags;
3658
- this.machine;
3659
- var jsonValues = _objectWithoutProperties(this, _excluded);
3660
- return _objectSpread2(_objectSpread2({}, jsonValues), {}, {
3661
- tags: Array.from(tags),
3662
- meta: this.meta
3663
- });
3664
- }
3665
-
3666
- /**
3667
- * Whether the current state value is a subset of the given parent state value.
3668
- * @param parentStateValue
3669
- */
3670
- }, {
3671
- key: "matches",
3672
- value: function matches(parentStateValue) {
3673
- return matchesState(parentStateValue, this.value);
3674
- }
3675
-
3676
- /**
3677
- * Whether the current state configuration has a state node with the specified `tag`.
3678
- * @param tag
3679
- */
3680
- }, {
3681
- key: "hasTag",
3682
- value: function hasTag(tag) {
3683
- return this.tags.has(tag);
3684
- }
3685
-
3686
- /**
3687
- * Determines whether sending the `event` will cause a non-forbidden transition
3688
- * to be selected, even if the transitions have no actions nor
3689
- * change the state value.
3690
- *
3691
- * @param event The event to test
3692
- * @returns Whether the event will cause a transition
3693
- */
3694
- }, {
3695
- key: "can",
3696
- value: function can(event) {
3697
- if (IS_PRODUCTION) {
3698
- warn(!!this.machine, "state.can(...) used outside of a machine-created State object; this will always return false.");
3699
- }
3700
- var transitionData = this.machine.getTransitionData(this, event);
3701
- return !!(transitionData !== null && transitionData !== void 0 && transitionData.length) &&
3702
- // Check that at least one transition is not forbidden
3703
- transitionData.some(function (t) {
3704
- return t.target !== undefined || t.actions.length;
3705
- });
3706
- }
3707
-
3708
- /**
3709
- * The next events that will cause a transition from the current state.
3710
- */
3711
- }, {
3712
- key: "nextEvents",
3713
- get: function get() {
3714
- var _this2 = this;
3715
- return memo(this, 'nextEvents', function () {
3716
- return _toConsumableArray(new Set(flatten(_toConsumableArray(_this2.configuration.map(function (sn) {
3717
- return sn.ownEvents;
3718
- })))));
3719
- });
3720
- }
3721
- }, {
3722
- key: "meta",
3723
- get: function get() {
3724
- return this.configuration.reduce(function (acc, stateNode) {
3725
- if (stateNode.meta !== undefined) {
3726
- acc[stateNode.id] = stateNode.meta;
3727
- }
3728
- return acc;
3729
- }, {});
3730
- }
3731
- }], [{
3732
- key: "from",
3733
- value:
3734
- /**
3735
- * Indicates whether the state is a final state.
3736
- */
3737
-
3738
- /**
3739
- * The done data of the top-level finite state.
3740
- */
3741
- // TODO: add an explicit type for `output`
3742
-
3743
- /**
3744
- * Indicates whether the state has changed from the previous state. A state is considered "changed" if:
3745
- *
3746
- * - Its value is not equal to its previous value, or:
3747
- * - It has any new actions (side-effects) to execute.
3748
- *
3749
- * An initial state (with no history) will return `undefined`.
3750
- */
3751
-
3752
- /**
3753
- * The enabled state nodes representative of the state value.
3754
- */
3755
-
3756
- /**
3757
- * The transition definitions that resulted in this state.
3758
- */
3759
-
3760
- /**
3761
- * An object mapping actor names to spawned/invoked actors.
3762
- */
3763
-
3764
- /**
3765
- * Creates a new State instance for the given `stateValue` and `context`.
3766
- * @param stateValue
3767
- * @param context
3768
- */
3769
- function from(stateValue) {
3770
- var context = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
3771
- var machine = arguments.length > 2 ? arguments[2] : undefined;
3772
- if (stateValue instanceof State) {
3773
- if (stateValue.context !== context) {
3774
- return new State({
3775
- value: stateValue.value,
3776
- context: context,
3777
- event: stateValue.event,
3778
- actions: [],
3779
- meta: {},
3780
- configuration: [],
3781
- // TODO: fix,
3782
- transitions: [],
3783
- children: {}
3784
- }, machine);
3785
- }
3786
- return stateValue;
3787
- }
3788
- var event = createInitEvent({}); // TODO: fix
3789
-
3790
- var configuration = getConfiguration(getStateNodes(machine.root, stateValue));
3791
- return new State({
3792
- value: stateValue,
3793
- context: context,
3794
- event: event,
3795
- actions: [],
3796
- meta: undefined,
3797
- configuration: Array.from(configuration),
3798
- transitions: [],
3799
- children: {}
3800
- }, machine);
3801
- }
3802
- }]);
3803
- return State;
3804
- }();
3805
- function cloneState(state) {
3806
- var config = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
3807
- return new State(_objectSpread2(_objectSpread2({}, state), config), state.machine);
3808
- }
3809
- function getPersistedState(state) {
3810
- state.configuration;
3811
- state.transitions;
3812
- state.tags;
3813
- state.machine;
3814
- var children = state.children,
3815
- jsonValues = _objectWithoutProperties(state, _excluded2);
3816
- var childrenJson = {};
3817
- for (var id in children) {
3818
- var _children$id$getPersi, _children$id;
3819
- childrenJson[id] = {
3820
- state: (_children$id$getPersi = (_children$id = children[id]).getPersistedState) === null || _children$id$getPersi === void 0 ? void 0 : _children$id$getPersi.call(_children$id),
3821
- src: children[id].src
3822
- };
3823
- }
3824
- return _objectSpread2(_objectSpread2({}, jsonValues), {}, {
3825
- children: childrenJson
3826
- });
3827
- }
3828
-
3829
- function invoke(invokeDef) {
3830
- return createDynamicAction({
3831
- type: invoke$1,
3832
- params: invokeDef
3833
- }, function (event, _ref) {
3834
- var state = _ref.state,
3835
- actorContext = _ref.actorContext;
3836
- var type = invoke$1;
3837
- var id = invokeDef.id,
3838
- src = invokeDef.src;
3839
- var resolvedInvokeAction;
3840
- if (isActorRef(src)) {
3841
- resolvedInvokeAction = {
3842
- type: type,
3843
- params: _objectSpread2(_objectSpread2({}, invokeDef), {}, {
3844
- ref: src
3845
- })
3846
- };
3847
- } else {
3848
- var referenced = resolveReferencedActor(state.machine.options.actors[src]);
3849
- if (!referenced) {
3850
- resolvedInvokeAction = {
3851
- type: type,
3852
- params: invokeDef
3853
- };
3854
- } else {
3855
- var input = 'input' in invokeDef ? invokeDef.input : referenced.input;
3856
- var ref = interpret(referenced.src, {
3857
- id: id,
3858
- src: src,
3859
- parent: actorContext === null || actorContext === void 0 ? void 0 : actorContext.self,
3860
- systemId: invokeDef.systemId,
3861
- input: typeof input === 'function' ? input({
3862
- context: state.context,
3863
- event: event,
3864
- self: actorContext === null || actorContext === void 0 ? void 0 : actorContext.self
3865
- }) : input
3866
- });
3867
- resolvedInvokeAction = {
3868
- type: type,
3869
- params: _objectSpread2(_objectSpread2({}, invokeDef), {}, {
3870
- ref: ref
3871
- })
3872
- };
3873
- }
3874
- }
3875
- var actorRef = resolvedInvokeAction.params.ref;
3876
- var invokedState = cloneState(state, {
3877
- children: _objectSpread2(_objectSpread2({}, state.children), {}, _defineProperty({}, id, actorRef))
3878
- });
3879
- resolvedInvokeAction.execute = function (actorCtx) {
3880
- var parent = actorCtx.self;
3881
- var _resolvedInvokeAction = resolvedInvokeAction.params,
3882
- id = _resolvedInvokeAction.id,
3883
- ref = _resolvedInvokeAction.ref;
3884
- if (!ref) {
3885
- if (!IS_PRODUCTION) {
3886
- warn(false, "Actor type '".concat(resolvedInvokeAction.params.src, "' not found in machine '").concat(actorCtx.id, "'."));
3887
- }
3888
- return;
3889
- }
3890
- actorCtx.defer(function () {
3891
- if (actorRef.status === ActorStatus.Stopped) {
3892
- return;
3893
- }
3894
- try {
3895
- var _actorRef$start;
3896
- (_actorRef$start = actorRef.start) === null || _actorRef$start === void 0 ? void 0 : _actorRef$start.call(actorRef);
3897
- } catch (err) {
3898
- parent.send(error(id, err));
3899
- return;
3900
- }
3901
- });
3902
- };
3903
- return [invokedState, resolvedInvokeAction];
3904
- });
3905
- }
3906
-
3907
- function createSpawner(self, machine, context, event, mutCapturedActions) {
3908
- return function (src) {
3909
- var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
3910
- if (isString(src)) {
3911
- var referenced = resolveReferencedActor(machine.options.actors[src]);
3912
- if (referenced) {
3913
- var _options$id;
3914
- var resolvedName = (_options$id = options.id) !== null && _options$id !== void 0 ? _options$id : 'anon'; // TODO: better name
3915
- var input = 'input' in options ? options.input : referenced.input;
3916
-
3917
- // TODO: this should also receive `src`
3918
- var actorRef = interpret(referenced.src, {
3919
- id: resolvedName,
3920
- parent: self,
3921
- input: typeof input === 'function' ? input({
3922
- context: context,
3923
- event: event,
3924
- self: self
3925
- }) : input
3926
- });
3927
- mutCapturedActions.push(invoke({
3928
- id: actorRef.id,
3929
- // @ts-ignore TODO: fix types
3930
- src: actorRef,
3931
- // TODO
3932
- ref: actorRef,
3933
- meta: undefined,
3934
- input: input
3935
- }));
3936
- return actorRef; // TODO: fix types
3937
- }
3938
-
3939
- throw new Error("Behavior '".concat(src, "' not implemented in machine '").concat(machine.id, "'"));
3940
- } else {
3941
- // TODO: this should also receive `src`
3942
- // TODO: instead of anonymous, it should be a unique stable ID
3943
- var _actorRef = interpret(src, {
3944
- id: options.id || 'anonymous',
3945
- parent: self,
3946
- input: options.input
3947
- });
3948
- mutCapturedActions.push(invoke({
3949
- // @ts-ignore TODO: fix types
3950
- src: _actorRef,
3951
- ref: _actorRef,
3952
- id: _actorRef.id,
3953
- meta: undefined,
3954
- input: options.input
3955
- }));
3956
- return _actorRef; // TODO: fix types
3957
- }
3958
- };
3959
- }
3960
-
3961
- /**
3962
- * Updates the current context of the machine.
3963
- *
3964
- * @param assignment An object that represents the partial context to update.
3965
- */
3966
- function assign(assignment) {
3967
- return createDynamicAction({
3968
- type: assign$1,
3969
- params: {
3970
- assignment: assignment
3971
- }
3972
- }, function (event, _ref) {
3973
- var _actorContext$self;
3974
- var state = _ref.state,
3975
- action = _ref.action,
3976
- actorContext = _ref.actorContext;
3977
- var capturedActions = [];
3978
- if (!state.context) {
3979
- throw new Error('Cannot assign to undefined `context`. Ensure that `context` is defined in the machine config.');
3980
- }
3981
- var args = {
3982
- context: state.context,
3983
- event: event,
3984
- action: action,
3985
- spawn: createSpawner(actorContext === null || actorContext === void 0 ? void 0 : actorContext.self, state.machine, state.context, event, capturedActions),
3986
- self: (_actorContext$self = actorContext === null || actorContext === void 0 ? void 0 : actorContext.self) !== null && _actorContext$self !== void 0 ? _actorContext$self : {},
3987
- system: actorContext === null || actorContext === void 0 ? void 0 : actorContext.system
3988
- };
3989
- var partialUpdate = {};
3990
- if (isFunction(assignment)) {
3991
- partialUpdate = assignment(args);
3992
- } else {
3993
- for (var _i = 0, _Object$keys = Object.keys(assignment); _i < _Object$keys.length; _i++) {
3994
- var key = _Object$keys[_i];
3995
- var propAssignment = assignment[key];
3996
- partialUpdate[key] = isFunction(propAssignment) ? propAssignment(args) : propAssignment;
3997
- }
3998
- }
3999
- var updatedContext = Object.assign({}, state.context, partialUpdate);
4000
- return [cloneState(state, {
4001
- context: updatedContext
4002
- }), {
4003
- type: assign$1,
4004
- params: {
4005
- context: updatedContext,
4006
- actions: capturedActions
4007
- }
4008
- }];
4009
- });
4010
- }
4011
-
4012
- /**
4013
- * Raises an event. This places the event in the internal event queue, so that
4014
- * the event is immediately consumed by the machine in the current step.
4015
- *
4016
- * @param eventType The event to raise.
4017
- */
4018
-
4019
- function raise(eventOrExpr, options) {
4020
- return createDynamicAction({
4021
- type: raise$1,
4022
- params: {
4023
- delay: options ? options.delay : undefined,
4024
- event: eventOrExpr,
4025
- id: options && options.id !== undefined ? options.id : typeof eventOrExpr === 'function' ? eventOrExpr.name : eventOrExpr.type
4026
- }
4027
- }, function (event, _ref) {
4028
- var _actorContext$self;
4029
- var state = _ref.state,
4030
- actorContext = _ref.actorContext;
4031
- var params = {
4032
- delay: options ? options.delay : undefined,
4033
- event: eventOrExpr,
4034
- id: options && options.id !== undefined ? options.id : typeof eventOrExpr === 'function' ? eventOrExpr.name : eventOrExpr.type
4035
- };
4036
- var args = {
4037
- context: state.context,
4038
- event: event,
4039
- self: (_actorContext$self = actorContext === null || actorContext === void 0 ? void 0 : actorContext.self) !== null && _actorContext$self !== void 0 ? _actorContext$self : {},
4040
- system: actorContext === null || actorContext === void 0 ? void 0 : actorContext.system
4041
- };
4042
- var delaysMap = state.machine.options.delays;
4043
-
4044
- // TODO: helper function for resolving Expr
4045
- if (typeof eventOrExpr === 'string') {
4046
- throw new Error("Only event objects may be used with raise; use raise({ type: \"".concat(eventOrExpr, "\" }) instead"));
4047
- }
4048
- var resolvedEvent = typeof eventOrExpr === 'function' ? eventOrExpr(args) : eventOrExpr;
4049
- var resolvedDelay;
4050
- if (typeof params.delay === 'string') {
4051
- var configDelay = delaysMap && delaysMap[params.delay];
4052
- resolvedDelay = typeof configDelay === 'function' ? configDelay(args) : configDelay;
4053
- } else {
4054
- resolvedDelay = typeof params.delay === 'function' ? params.delay(args) : params.delay;
4055
- }
4056
- var resolvedAction = {
4057
- type: raise$1,
4058
- params: _objectSpread2(_objectSpread2({}, params), {}, {
4059
- event: resolvedEvent,
4060
- delay: resolvedDelay
4061
- }),
4062
- execute: function execute(actorCtx) {
4063
- if (typeof resolvedAction.params.delay === 'number') {
4064
- actorCtx.self.delaySend(resolvedAction);
4065
- return;
4066
- }
4067
- }
4068
- };
4069
- return [state, resolvedAction];
4070
- });
4071
- }
4072
-
4073
- function choose(guards) {
4074
- return createDynamicAction({
4075
- type: choose$1,
4076
- params: {
4077
- guards: guards
4078
- }
4079
- }, function (event, _ref) {
4080
- var _guards$find;
4081
- var state = _ref.state;
4082
- var matchedActions = (_guards$find = guards.find(function (condition) {
4083
- var guard = condition.guard && toGuardDefinition(condition.guard, function (guardType) {
4084
- return state.machine.options.guards[guardType];
4085
- });
4086
- return !guard || evaluateGuard(guard, state.context, event, state);
4087
- })) === null || _guards$find === void 0 ? void 0 : _guards$find.actions;
4088
- return [state, {
4089
- type: choose$1,
4090
- params: {
4091
- actions: toActionObjects(matchedActions)
4092
- }
4093
- }];
4094
- });
4095
- }
4096
-
4097
- function pure(getActions) {
4098
- return createDynamicAction({
4099
- type: pure$1,
4100
- params: {
4101
- get: getActions
4102
- }
4103
- }, function (event, _ref) {
4104
- var _toArray;
4105
- var state = _ref.state;
4106
- return [state, {
4107
- type: pure$1,
4108
- params: {
4109
- actions: (_toArray = toArray(toActionObjects(getActions({
4110
- context: state.context,
4111
- event: event
4112
- })))) !== null && _toArray !== void 0 ? _toArray : []
4113
- }
4114
- }];
4115
- });
4116
- }
4117
-
4118
- var initEvent = {
4119
- type: init
4120
- };
4121
- function resolveActionObject(actionObject, actionFunctionMap) {
4122
- if (isDynamicAction(actionObject)) {
4123
- return actionObject;
4124
- }
4125
- var dereferencedAction = actionFunctionMap[actionObject.type];
4126
- if (typeof dereferencedAction === 'function') {
4127
- var _actionObject$params;
4128
- return createDynamicAction({
4129
- type: 'xstate.function',
4130
- params: (_actionObject$params = actionObject.params) !== null && _actionObject$params !== void 0 ? _actionObject$params : {}
4131
- }, function (event, _ref) {
4132
- var state = _ref.state;
4133
- var a = {
4134
- type: actionObject.type,
4135
- params: actionObject.params,
4136
- execute: function execute(actorCtx) {
4137
- return dereferencedAction({
4138
- context: state.context,
4139
- event: event,
4140
- action: a,
4141
- system: actorCtx.system,
4142
- self: actorCtx.self
4143
- });
4144
- }
4145
- };
4146
- return [state, a];
4147
- });
4148
- } else if (dereferencedAction) {
4149
- return dereferencedAction;
4150
- } else {
4151
- return actionObject;
4152
- }
4153
- }
4154
- function toActionObject(action) {
4155
- if (isDynamicAction(action)) {
4156
- return action;
4157
- }
4158
- if (typeof action === 'string') {
4159
- return {
4160
- type: action,
4161
- params: {}
4162
- };
4163
- }
4164
- if (typeof action === 'function') {
4165
- var type = 'xstate.function';
4166
- return createDynamicAction({
4167
- type: type,
4168
- params: {}
4169
- }, function (event, _ref2) {
4170
- var state = _ref2.state;
4171
- var actionObject = {
4172
- type: type,
4173
- params: {
4174
- "function": action
4175
- },
4176
- execute: function execute(actorCtx) {
4177
- return action({
4178
- context: state.context,
4179
- event: event,
4180
- action: actionObject,
4181
- self: actorCtx.self,
4182
- system: actorCtx.system
4183
- });
4184
- }
4185
- };
4186
- return [state, actionObject];
4187
- });
4188
- }
4189
-
4190
- // action is already a BaseActionObject
4191
- return action;
4192
- }
4193
- var toActionObjects = function toActionObjects(action) {
4194
- if (!action) {
4195
- return [];
4196
- }
4197
- var actions = isArray(action) ? action : [action];
4198
- return actions.map(toActionObject);
4199
- };
4200
-
4201
- /**
4202
- * Returns an event type that represents an implicit event that
4203
- * is sent after the specified `delay`.
4204
- *
4205
- * @param delayRef The delay in milliseconds
4206
- * @param id The state node ID where this event is handled
4207
- */
4208
- function after(delayRef, id) {
4209
- var idSuffix = id ? "#".concat(id) : '';
4210
- return "".concat(ActionTypes.After, "(").concat(delayRef, ")").concat(idSuffix);
4211
- }
4212
-
4213
- /**
4214
- * Returns an event that represents that a final state node
4215
- * has been reached in the parent state node.
4216
- *
4217
- * @param id The final state node's parent state node `id`
4218
- * @param output The data to pass into the event
4219
- */
4220
- function done(id, output) {
4221
- var type = "".concat(ActionTypes.DoneState, ".").concat(id);
4222
- var eventObject = {
4223
- type: type,
4224
- output: output
4225
- };
4226
- eventObject.toString = function () {
4227
- return type;
4228
- };
4229
- return eventObject;
4230
- }
4231
-
4232
- /**
4233
- * Returns an event that represents that an invoked service has terminated.
4234
- *
4235
- * An invoked service is terminated when it has reached a top-level final state node,
4236
- * but not when it is canceled.
4237
- *
4238
- * @param invokeId The invoked service ID
4239
- * @param output The data to pass into the event
4240
- */
4241
- function doneInvoke(invokeId, output) {
4242
- var type = "".concat(ActionTypes.DoneInvoke, ".").concat(invokeId);
4243
- var eventObject = {
4244
- type: type,
4245
- output: output
4246
- };
4247
- eventObject.toString = function () {
4248
- return type;
4249
- };
4250
- return eventObject;
4251
- }
4252
- function error(id, data) {
4253
- var type = "".concat(ActionTypes.ErrorPlatform, ".").concat(id);
4254
- var eventObject = {
4255
- type: type,
4256
- data: data
4257
- };
4258
- eventObject.toString = function () {
4259
- return type;
4260
- };
4261
- return eventObject;
4262
- }
4263
- function createInitEvent(input) {
4264
- return {
4265
- type: init,
4266
- input: input
4267
- };
4268
- }
4269
-
4270
- export { assign as $, isInFinalState as A, isErrorEvent as B, macrostep as C, transitionNode as D, _slicedToArray as E, getInitialConfiguration as F, createInitEvent as G, resolveActionsAndContext as H, microstep as I, error as J, isStateId as K, getStateNodeByPath as L, getPersistedState as M, NULL_EVENT as N, resolveReferencedActor as O, interpret as P, STATE_DELIMITER as Q, initEvent as R, State as S, matchesState as T, sendTo as U, sendParent as V, forwardTo as W, Interpreter as X, ActorStatus as Y, doneInvoke as Z, _createClass as _, formatTransition as a, cancel as a0, choose as a1, log as a2, pure as a3, raise as a4, stop as a5, pathToStateValue as a6, toObserver as a7, fromPromise as a8, fromObservable as a9, fromCallback as aa, fromEventObservable as ab, fromTransition as ac, stateIn as ad, not as ae, and as af, or as ag, ActionTypes as ah, SpecialTargets as ai, startSignalType as aj, stopSignalType as ak, startSignal as al, stopSignal as am, isSignal as an, isActorRef as ao, toActorRef as ap, createEmptyActor as aq, toGuardDefinition as ar, actionTypes as as, resolveActionObject as at, toActionObject as au, after as av, done as aw, send as ax, escalate as ay, memo as b, _createForOfIteratorHelper as c, _toConsumableArray as d, evaluateGuard as e, formatTransitions as f, flatten as g, _classCallCheck as h, _defineProperty as i, toActionObjects as j, toArray as k, createInvokeId as l, mapValues as m, toInvokeConfig as n, _objectSpread2 as o, invoke$1 as p, _objectWithoutProperties as q, getDelayedTransitions as r, formatInitialTransition as s, toTransitionConfigArray as t, getCandidates as u, isString as v, createSpawner as w, getConfiguration as x, getStateNodes as y, resolveStateValue as z };