xstate 4.30.4 → 4.31.0

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.
package/es/waitFor.js ADDED
@@ -0,0 +1,66 @@
1
+ import { __assign } from './_virtual/_tslib.js';
2
+
3
+ var defaultWaitForOptions = {
4
+ timeout: 10000 // 10 seconds
5
+
6
+ };
7
+ /**
8
+ * Subscribes to an actor ref and waits for its emitted value to satisfy
9
+ * a predicate, and then resolves with that value.
10
+ *
11
+ * @example
12
+ * ```js
13
+ * const state = await waitFor(someService, state => {
14
+ * return state.hasTag('loaded');
15
+ * });
16
+ *
17
+ * state.hasTag('loaded'); // true
18
+ * ```
19
+ *
20
+ * @param actorRef The actor ref to subscribe to
21
+ * @param predicate Determines if a value matches the condition to wait for
22
+ * @param options
23
+ * @returns A promise that eventually resolves to the emitted value
24
+ * that matches the condition
25
+ */
26
+
27
+ function waitFor(actorRef, predicate, options) {
28
+ var resolvedOptions = __assign(__assign({}, defaultWaitForOptions), options);
29
+
30
+ return new Promise(function (res, rej) {
31
+ var done = false;
32
+ var handle = setTimeout(function () {
33
+ sub.unsubscribe();
34
+ rej(new Error("Timeout of ".concat(resolvedOptions.timeout, " ms exceeded")));
35
+ }, resolvedOptions.timeout);
36
+
37
+ var dispose = function () {
38
+ clearTimeout(handle);
39
+ done = true;
40
+ sub === null || sub === void 0 ? void 0 : sub.unsubscribe();
41
+ };
42
+
43
+ var sub = actorRef.subscribe({
44
+ next: function (emitted) {
45
+ if (predicate(emitted)) {
46
+ dispose();
47
+ res(emitted);
48
+ }
49
+ },
50
+ error: function (err) {
51
+ dispose();
52
+ rej(err);
53
+ },
54
+ complete: function () {
55
+ dispose();
56
+ rej(new Error("Actor terminated without satisfying predicate"));
57
+ }
58
+ });
59
+
60
+ if (done) {
61
+ sub.unsubscribe();
62
+ }
63
+ });
64
+ }
65
+
66
+ export { waitFor };
@@ -1,83 +1,85 @@
1
- "use strict";
2
- var __read = (this && this.__read) || function (o, n) {
3
- var m = typeof Symbol === "function" && o[Symbol.iterator];
4
- if (!m) return o;
5
- var i = m.call(o), r, ar = [], e;
6
- try {
7
- while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var _tslib = require('./_virtual/_tslib.js');
6
+
7
+ var SimulatedClock =
8
+ /*#__PURE__*/
9
+
10
+ /** @class */
11
+ function () {
12
+ function SimulatedClock() {
13
+ this.timeouts = new Map();
14
+ this._now = 0;
15
+ this._id = 0;
16
+ }
17
+
18
+ SimulatedClock.prototype.now = function () {
19
+ return this._now;
20
+ };
21
+
22
+ SimulatedClock.prototype.getId = function () {
23
+ return this._id++;
24
+ };
25
+
26
+ SimulatedClock.prototype.setTimeout = function (fn, timeout) {
27
+ var id = this.getId();
28
+ this.timeouts.set(id, {
29
+ start: this.now(),
30
+ timeout: timeout,
31
+ fn: fn
32
+ });
33
+ return id;
34
+ };
35
+
36
+ SimulatedClock.prototype.clearTimeout = function (id) {
37
+ this.timeouts.delete(id);
38
+ };
39
+
40
+ SimulatedClock.prototype.set = function (time) {
41
+ if (this._now > time) {
42
+ throw new Error('Unable to travel back in time');
8
43
  }
9
- catch (error) { e = { error: error }; }
10
- finally {
11
- try {
12
- if (r && !r.done && (m = i["return"])) m.call(i);
13
- }
14
- finally { if (e) throw e.error; }
15
- }
16
- return ar;
17
- };
18
- var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
19
- if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
20
- if (ar || !(i in from)) {
21
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
22
- ar[i] = from[i];
23
- }
24
- }
25
- return to.concat(ar || Array.prototype.slice.call(from));
26
- };
27
- Object.defineProperty(exports, "__esModule", { value: true });
28
- exports.SimulatedClock = void 0;
29
- var SimulatedClock = /** @class */ (function () {
30
- function SimulatedClock() {
31
- this.timeouts = new Map();
32
- this._now = 0;
33
- this._id = 0;
34
- }
35
- SimulatedClock.prototype.now = function () {
36
- return this._now;
37
- };
38
- SimulatedClock.prototype.getId = function () {
39
- return this._id++;
40
- };
41
- SimulatedClock.prototype.setTimeout = function (fn, timeout) {
42
- var id = this.getId();
43
- this.timeouts.set(id, {
44
- start: this.now(),
45
- timeout: timeout,
46
- fn: fn
47
- });
48
- return id;
49
- };
50
- SimulatedClock.prototype.clearTimeout = function (id) {
51
- this.timeouts.delete(id);
52
- };
53
- SimulatedClock.prototype.set = function (time) {
54
- if (this._now > time) {
55
- throw new Error('Unable to travel back in time');
56
- }
57
- this._now = time;
58
- this.flushTimeouts();
59
- };
60
- SimulatedClock.prototype.flushTimeouts = function () {
61
- var _this = this;
62
- __spreadArray([], __read(this.timeouts), false).sort(function (_a, _b) {
63
- var _c = __read(_a, 2), _idA = _c[0], timeoutA = _c[1];
64
- var _d = __read(_b, 2), _idB = _d[0], timeoutB = _d[1];
65
- var endA = timeoutA.start + timeoutA.timeout;
66
- var endB = timeoutB.start + timeoutB.timeout;
67
- return endB > endA ? -1 : 1;
68
- })
69
- .forEach(function (_a) {
70
- var _b = __read(_a, 2), id = _b[0], timeout = _b[1];
71
- if (_this.now() - timeout.start >= timeout.timeout) {
72
- _this.timeouts.delete(id);
73
- timeout.fn.call(null);
74
- }
75
- });
76
- };
77
- SimulatedClock.prototype.increment = function (ms) {
78
- this._now += ms;
79
- this.flushTimeouts();
80
- };
81
- return SimulatedClock;
82
- }());
44
+
45
+ this._now = time;
46
+ this.flushTimeouts();
47
+ };
48
+
49
+ SimulatedClock.prototype.flushTimeouts = function () {
50
+ var _this = this;
51
+
52
+ _tslib.__spreadArray([], _tslib.__read(this.timeouts), false).sort(function (_a, _b) {
53
+ var _c = _tslib.__read(_a, 2);
54
+ _c[0];
55
+ var timeoutA = _c[1];
56
+
57
+ var _d = _tslib.__read(_b, 2);
58
+ _d[0];
59
+ var timeoutB = _d[1];
60
+
61
+ var endA = timeoutA.start + timeoutA.timeout;
62
+ var endB = timeoutB.start + timeoutB.timeout;
63
+ return endB > endA ? -1 : 1;
64
+ }).forEach(function (_a) {
65
+ var _b = _tslib.__read(_a, 2),
66
+ id = _b[0],
67
+ timeout = _b[1];
68
+
69
+ if (_this.now() - timeout.start >= timeout.timeout) {
70
+ _this.timeouts.delete(id);
71
+
72
+ timeout.fn.call(null);
73
+ }
74
+ });
75
+ };
76
+
77
+ SimulatedClock.prototype.increment = function (ms) {
78
+ this._now += ms;
79
+ this.flushTimeouts();
80
+ };
81
+
82
+ return SimulatedClock;
83
+ }();
84
+
83
85
  exports.SimulatedClock = SimulatedClock;
package/lib/State.d.ts CHANGED
@@ -98,7 +98,7 @@ export declare class State<TContext, TEvent extends EventObject = EventObject, T
98
98
  * Whether the current state value is a subset of the given parent state value.
99
99
  * @param parentStateValue
100
100
  */
101
- matches<TSV extends TResolvedTypesMeta extends TypegenEnabled ? Prop<TResolvedTypesMeta, 'matchesStates'> : never>(parentStateValue: TSV): boolean;
101
+ matches<TSV extends TResolvedTypesMeta extends TypegenEnabled ? Prop<Prop<TResolvedTypesMeta, 'resolved'>, 'matchesStates'> : never>(parentStateValue: TSV): boolean;
102
102
  matches<TSV extends TResolvedTypesMeta extends TypegenDisabled ? TTypestate['value'] : never>(parentStateValue: TSV): this is State<(TTypestate extends any ? {
103
103
  value: TSV;
104
104
  context: any;
@@ -109,7 +109,7 @@ export declare class State<TContext, TEvent extends EventObject = EventObject, T
109
109
  * Whether the current state configuration has a state node with the specified `tag`.
110
110
  * @param tag
111
111
  */
112
- hasTag(tag: TResolvedTypesMeta extends TypegenEnabled ? Prop<TResolvedTypesMeta, 'tags'> : string): boolean;
112
+ hasTag(tag: TResolvedTypesMeta extends TypegenEnabled ? Prop<Prop<TResolvedTypesMeta, 'resolved'>, 'tags'> : string): boolean;
113
113
  /**
114
114
  * Determines whether sending the `event` will cause a non-forbidden transition
115
115
  * to be selected, even if the transitions have no actions nor
package/lib/State.js CHANGED
@@ -4,10 +4,10 @@ Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
5
  var _tslib = require('./_virtual/_tslib.js');
6
6
  var constants = require('./constants.js');
7
- var environment = require('./environment.js');
8
7
  var utils = require('./utils.js');
9
- var actions = require('./actions.js');
10
8
  var stateUtils = require('./stateUtils.js');
9
+ var actions = require('./actions.js');
10
+ var environment = require('./environment.js');
11
11
 
12
12
  function stateValuesEqual(a, b) {
13
13
  if (a === b) {
@@ -35,6 +35,11 @@ function isStateConfig(state) {
35
35
 
36
36
  return 'value' in state && '_event' in state;
37
37
  }
38
+ /**
39
+ * @deprecated Use `isStateConfig(object)` or `state instanceof State` instead.
40
+ */
41
+
42
+ var isState = isStateConfig;
38
43
  function bindActionToState(action, state) {
39
44
  var exec = action.exec;
40
45
 
@@ -219,12 +224,12 @@ function () {
219
224
  };
220
225
 
221
226
  State.prototype.toJSON = function () {
222
- var _a = this,
223
- configuration = _a.configuration,
224
- transitions = _a.transitions,
225
- tags = _a.tags,
226
- machine = _a.machine,
227
- jsonValues = _tslib.__rest(_a, ["configuration", "transitions", "tags", "machine"]);
227
+ var _a = this;
228
+ _a.configuration;
229
+ _a.transitions;
230
+ var tags = _a.tags;
231
+ _a.machine;
232
+ var jsonValues = _tslib.__rest(_a, ["configuration", "transitions", "tags", "machine"]);
228
233
 
229
234
  return _tslib.__assign(_tslib.__assign({}, jsonValues), {
230
235
  tags: Array.from(tags)
@@ -272,5 +277,6 @@ function () {
272
277
 
273
278
  exports.State = State;
274
279
  exports.bindActionToState = bindActionToState;
280
+ exports.isState = isState;
275
281
  exports.isStateConfig = isStateConfig;
276
282
  exports.stateValuesEqual = stateValuesEqual;
package/lib/StateNode.js CHANGED
@@ -3,15 +3,15 @@
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
5
  var _tslib = require('./_virtual/_tslib.js');
6
+ var utils = require('./utils.js');
6
7
  var types = require('./types.js');
8
+ var State = require('./State.js');
7
9
  var actionTypes = require('./actionTypes.js');
8
- var constants = require('./constants.js');
9
- var environment = require('./environment.js');
10
- var utils = require('./utils.js');
11
10
  var actions = require('./actions.js');
12
- var Actor = require('./Actor.js');
11
+ var environment = require('./environment.js');
12
+ var constants = require('./constants.js');
13
13
  var stateUtils = require('./stateUtils.js');
14
- var State = require('./State.js');
14
+ var Actor = require('./Actor.js');
15
15
  var invokeUtils = require('./invokeUtils.js');
16
16
 
17
17
  var NULL_EVENT = '';
@@ -447,7 +447,8 @@ function () {
447
447
  value: this.resolve(stateFromConfig.value),
448
448
  configuration: configuration,
449
449
  done: stateUtils.isInFinalState(configuration, this),
450
- tags: stateUtils.getTagsFromConfiguration(configuration)
450
+ tags: stateUtils.getTagsFromConfiguration(configuration),
451
+ machine: this.machine
451
452
  }));
452
453
  };
453
454
 
@@ -923,7 +924,7 @@ function () {
923
924
  transitions: stateTransition.transitions,
924
925
  children: children,
925
926
  done: isDone,
926
- tags: currentState === null || currentState === void 0 ? void 0 : currentState.tags,
927
+ tags: stateUtils.getTagsFromConfiguration(resolvedConfiguration),
927
928
  machine: this
928
929
  });
929
930
  var didUpdateContext = context !== updatedContext;
@@ -973,7 +974,6 @@ function () {
973
974
  maybeNextState.changed = changed; // Preserve original history after raised events
974
975
 
975
976
  maybeNextState.history = history;
976
- maybeNextState.tags = stateUtils.getTagsFromConfiguration(maybeNextState.configuration);
977
977
  return maybeNextState;
978
978
  };
979
979
  /**
package/lib/actions.js CHANGED
@@ -5,8 +5,8 @@ Object.defineProperty(exports, '__esModule', { value: true });
5
5
  var _tslib = require('./_virtual/_tslib.js');
6
6
  var types = require('./types.js');
7
7
  var actionTypes = require('./actionTypes.js');
8
- var environment = require('./environment.js');
9
8
  var utils = require('./utils.js');
9
+ var environment = require('./environment.js');
10
10
 
11
11
  var initEvent = /*#__PURE__*/utils.toSCXMLEvent({
12
12
  type: actionTypes.init
package/lib/behaviors.js CHANGED
@@ -2,12 +2,78 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
- require('./types.js');
6
- require('./actionTypes.js');
7
- require('./environment.js');
8
- var utils = require('./utils.js');
5
+ var actions = require('./actions.js');
9
6
  var Actor = require('./Actor.js');
7
+ var utils = require('./utils.js');
8
+
9
+ /**
10
+ * Returns an actor behavior from a reducer and its initial state.
11
+ *
12
+ * @param transition The pure reducer that returns the next state given the current state and event.
13
+ * @param initialState The initial state of the reducer.
14
+ * @returns An actor behavior
15
+ */
16
+
17
+ function fromReducer(transition, initialState) {
18
+ return {
19
+ transition: transition,
20
+ initialState: initialState
21
+ };
22
+ }
23
+ function fromPromise(promiseFn) {
24
+ var initialState = {
25
+ error: undefined,
26
+ data: undefined,
27
+ status: 'pending'
28
+ };
29
+ return {
30
+ transition: function (state, event, _a) {
31
+ var parent = _a.parent,
32
+ id = _a.id,
33
+ observers = _a.observers;
10
34
 
35
+ switch (event.type) {
36
+ case 'fulfill':
37
+ parent === null || parent === void 0 ? void 0 : parent.send(actions.doneInvoke(id, event.data));
38
+ return {
39
+ error: undefined,
40
+ data: event.data,
41
+ status: 'fulfilled'
42
+ };
43
+
44
+ case 'reject':
45
+ parent === null || parent === void 0 ? void 0 : parent.send(actions.error(id, event.error));
46
+ observers.forEach(function (observer) {
47
+ observer.error(event.error);
48
+ });
49
+ return {
50
+ error: event.error,
51
+ data: undefined,
52
+ status: 'rejected'
53
+ };
54
+
55
+ default:
56
+ return state;
57
+ }
58
+ },
59
+ initialState: initialState,
60
+ start: function (_a) {
61
+ var self = _a.self;
62
+ promiseFn().then(function (data) {
63
+ self.send({
64
+ type: 'fulfill',
65
+ data: data
66
+ });
67
+ }, function (reason) {
68
+ self.send({
69
+ type: 'reject',
70
+ error: reason
71
+ });
72
+ });
73
+ return initialState;
74
+ }
75
+ };
76
+ }
11
77
  function spawnBehavior(behavior, options) {
12
78
  if (options === void 0) {
13
79
  options = {};
@@ -66,4 +132,6 @@ function spawnBehavior(behavior, options) {
66
132
  return actor;
67
133
  }
68
134
 
135
+ exports.fromPromise = fromPromise;
136
+ exports.fromReducer = fromReducer;
69
137
  exports.spawnBehavior = spawnBehavior;
package/lib/devTools.js CHANGED
@@ -2,7 +2,8 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
- // From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis
5
+ var environment = require('./environment.js');
6
+
6
7
  function getGlobal() {
7
8
  if (typeof globalThis !== 'undefined') {
8
9
  return globalThis;
@@ -20,7 +21,9 @@ function getGlobal() {
20
21
  return global;
21
22
  }
22
23
 
23
- return undefined;
24
+ if (!environment.IS_PRODUCTION) {
25
+ console.warn('XState could not find a global object in this environment. Please let the maintainers know and raise an issue here: https://github.com/statelyai/xstate/issues');
26
+ }
24
27
  }
25
28
 
26
29
  function getDevTools() {
package/lib/each.js CHANGED
@@ -1,15 +1,17 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.each = void 0;
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
4
5
  function each(collection, item, indexOrActions, maybeActions) {
5
- var actions = maybeActions || indexOrActions;
6
- var index = maybeActions ? indexOrActions : undefined;
7
- return {
8
- type: 'xstate.foreach',
9
- collection: collection,
10
- item: item,
11
- index: index,
12
- actions: actions
13
- };
6
+ var actions = maybeActions || indexOrActions;
7
+ var index = maybeActions ? indexOrActions : undefined;
8
+ return {
9
+ type: 'xstate.foreach',
10
+ collection: collection,
11
+ item: item,
12
+ index: index,
13
+ actions: actions
14
+ };
14
15
  }
16
+
15
17
  exports.each = each;
package/lib/index.js CHANGED
@@ -2,18 +2,18 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
- var types = require('./types.js');
6
- var utils = require('./utils.js');
7
5
  var actions = require('./actions.js');
8
6
  var Actor = require('./Actor.js');
9
- var State = require('./State.js');
10
- var behaviors = require('./behaviors.js');
11
7
  var interpreter = require('./interpreter.js');
12
- var StateNode = require('./StateNode.js');
13
8
  var Machine = require('./Machine.js');
14
9
  var mapState = require('./mapState.js');
15
10
  var match = require('./match.js');
16
11
  var schema = require('./schema.js');
12
+ var State = require('./State.js');
13
+ var StateNode = require('./StateNode.js');
14
+ var behaviors = require('./behaviors.js');
15
+ var types = require('./types.js');
16
+ var utils = require('./utils.js');
17
17
 
18
18
  var assign = actions.assign,
19
19
  send = actions.send,
@@ -22,42 +22,36 @@ var assign = actions.assign,
22
22
  forwardTo = actions.forwardTo,
23
23
  doneInvoke = actions.doneInvoke;
24
24
 
25
- Object.defineProperty(exports, 'ActionTypes', {
26
- enumerable: true,
27
- get: function () {
28
- return types.ActionTypes;
29
- }
30
- });
31
- Object.defineProperty(exports, 'SpecialTargets', {
32
- enumerable: true,
33
- get: function () {
34
- return types.SpecialTargets;
35
- }
36
- });
37
- exports.matchesState = utils.matchesState;
38
- exports.toEventObject = utils.toEventObject;
39
- exports.toObserver = utils.toObserver;
40
- exports.toSCXMLEvent = utils.toSCXMLEvent;
41
25
  exports.actions = actions;
42
26
  exports.toActorRef = Actor.toActorRef;
43
- exports.State = State.State;
44
- exports.spawnBehavior = behaviors.spawnBehavior;
45
27
  exports.Interpreter = interpreter.Interpreter;
46
28
  Object.defineProperty(exports, 'InterpreterStatus', {
47
29
  enumerable: true,
48
- get: function () {
49
- return interpreter.InterpreterStatus;
50
- }
30
+ get: function () { return interpreter.InterpreterStatus; }
51
31
  });
52
32
  exports.interpret = interpreter.interpret;
53
33
  exports.spawn = interpreter.spawn;
54
- exports.StateNode = StateNode.StateNode;
55
34
  exports.Machine = Machine.Machine;
56
35
  exports.createMachine = Machine.createMachine;
57
36
  exports.mapState = mapState.mapState;
58
37
  exports.matchState = match.matchState;
59
38
  exports.createSchema = schema.createSchema;
60
39
  exports.t = schema.t;
40
+ exports.State = State.State;
41
+ exports.StateNode = StateNode.StateNode;
42
+ exports.spawnBehavior = behaviors.spawnBehavior;
43
+ Object.defineProperty(exports, 'ActionTypes', {
44
+ enumerable: true,
45
+ get: function () { return types.ActionTypes; }
46
+ });
47
+ Object.defineProperty(exports, 'SpecialTargets', {
48
+ enumerable: true,
49
+ get: function () { return types.SpecialTargets; }
50
+ });
51
+ exports.matchesState = utils.matchesState;
52
+ exports.toEventObject = utils.toEventObject;
53
+ exports.toObserver = utils.toObserver;
54
+ exports.toSCXMLEvent = utils.toSCXMLEvent;
61
55
  exports.assign = assign;
62
56
  exports.doneInvoke = doneInvoke;
63
57
  exports.forwardTo = forwardTo;
@@ -23,7 +23,6 @@ export declare enum InterpreterStatus {
23
23
  Running = 1,
24
24
  Stopped = 2
25
25
  }
26
- /** @ts-ignore [symbolObservable] creates problems for people without `skipLibCheck` who are on older versions of TS, remove this comment when we drop support for TS@<4.3 */
27
26
  export declare class Interpreter<TContext, TStateSchema extends StateSchema = any, TEvent extends EventObject = EventObject, TTypestate extends Typestate<TContext> = {
28
27
  value: any;
29
28
  context: TContext;
@@ -190,8 +189,7 @@ export declare class Interpreter<TContext, TStateSchema extends StateSchema = an
190
189
  toJSON(): {
191
190
  id: string;
192
191
  };
193
- /** @ts-ignore this creates problems for people without `skipLibCheck` who are on older versions of TS, remove this comment when we drop support for TS@<4.3 */
194
- [symbolObservable](): InteropSubscribable<State<TContext, TEvent, TStateSchema, TTypestate, TResolvedTypesMeta>>;
192
+ [Symbol.observable](): InteropSubscribable<State<TContext, TEvent, TStateSchema, TTypestate, TResolvedTypesMeta>>;
195
193
  getSnapshot(): State<TContext, TEvent, TStateSchema, TTypestate, TResolvedTypesMeta>;
196
194
  }
197
195
  export declare function spawn<T extends Behavior<any, any>>(entity: T, nameOrOptions?: string | SpawnOptions): ActorRefFrom<T>;