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/interpreter.js CHANGED
@@ -1,16 +1,16 @@
1
1
  import { __values, __spreadArray, __read, __assign } from './_virtual/_tslib.js';
2
2
  import { ActionTypes, SpecialTargets } from './types.js';
3
+ import { isStateConfig, State, bindActionToState } from './State.js';
3
4
  import { errorPlatform, log, stop, start, cancel, send, update, error as error$1 } from './actionTypes.js';
5
+ import { doneInvoke, initEvent, getActionFunction, error } from './actions.js';
4
6
  import { IS_PRODUCTION } from './environment.js';
5
7
  import { warn, mapContext, isFunction, toSCXMLEvent, toInvokeSource, isMachine, isPromiseLike, isObservable, isBehavior, reportUnhandledExceptionOnInvocation, symbolObservable, isArray, toEventObject, isString, isActor, uniqueId, toObserver } from './utils.js';
6
- import { doneInvoke, initEvent, getActionFunction, error } from './actions.js';
7
- import { provide, consume } from './serviceScope.js';
8
+ import { Scheduler } from './scheduler.js';
8
9
  import { isSpawnedActor, createDeferredActor } from './Actor.js';
9
10
  import { isInFinalState } from './stateUtils.js';
10
- import { isStateConfig, State, bindActionToState } from './State.js';
11
- import { Scheduler } from './scheduler.js';
12
11
  import { registry } from './registry.js';
13
- import { registerService, getGlobal } from './devTools.js';
12
+ import { getGlobal, registerService } from './devTools.js';
13
+ import { provide, consume } from './serviceScope.js';
14
14
  import { spawnBehavior } from './behaviors.js';
15
15
 
16
16
  var DEFAULT_SPAWN_OPTIONS = {
@@ -24,8 +24,6 @@ var InterpreterStatus;
24
24
  InterpreterStatus[InterpreterStatus["Running"] = 1] = "Running";
25
25
  InterpreterStatus[InterpreterStatus["Stopped"] = 2] = "Stopped";
26
26
  })(InterpreterStatus || (InterpreterStatus = {}));
27
- /** @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 */
28
-
29
27
 
30
28
  var Interpreter =
31
29
  /*#__PURE__*/
@@ -46,7 +44,6 @@ function () {
46
44
  }
47
45
 
48
46
  this.machine = machine;
49
- this.scheduler = new Scheduler();
50
47
  this.delayedEventsMap = {};
51
48
  this.listeners = new Set();
52
49
  this.contextListeners = new Set();
@@ -363,12 +360,16 @@ function () {
363
360
 
364
361
  this.listeners.add(listener); // Send current state to listener
365
362
 
366
- if (this.status === InterpreterStatus.Running) {
363
+ if (this.status !== InterpreterStatus.NotStarted) {
367
364
  listener(this.state);
368
365
  }
369
366
 
370
367
  if (resolvedCompleteListener) {
371
- this.onDone(resolvedCompleteListener);
368
+ if (this.status === InterpreterStatus.Stopped) {
369
+ resolvedCompleteListener();
370
+ } else {
371
+ this.onDone(resolvedCompleteListener);
372
+ }
372
373
  }
373
374
 
374
375
  return {
@@ -455,7 +456,13 @@ function () {
455
456
  if (this.status === InterpreterStatus.Running) {
456
457
  // Do not restart the service if it is already started
457
458
  return this;
458
- }
459
+ } // yes, it's a hack but we need the related cache to be populated for some things to work (like delayed transitions)
460
+ // this is usually called by `machine.getInitialState` but if we rehydrate from a state we might bypass this call
461
+ // we also don't want to call this method here as it resolves the full initial state which might involve calling assign actions
462
+ // and that could potentially lead to some unwanted side-effects (even such as creating some rogue actors)
463
+
464
+
465
+ this.machine._init();
459
466
 
460
467
  registry.register(this.sessionId, this);
461
468
  this.initialized = true;
@@ -590,6 +597,7 @@ function () {
590
597
  child.stop();
591
598
  }
592
599
  });
600
+ this.children.clear();
593
601
 
594
602
  try {
595
603
  // Cancel all delayed events
@@ -610,8 +618,12 @@ function () {
610
618
  }
611
619
 
612
620
  this.scheduler.clear();
621
+ this.scheduler = new Scheduler({
622
+ deferEvents: this.options.deferEvents
623
+ });
613
624
  this.initialized = false;
614
625
  this.status = InterpreterStatus.Stopped;
626
+ this._initialState = undefined;
615
627
  registry.free(this.sessionId);
616
628
  return this;
617
629
  };
@@ -1310,8 +1322,6 @@ function () {
1310
1322
  id: this.id
1311
1323
  };
1312
1324
  };
1313
- /** @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 */
1314
-
1315
1325
 
1316
1326
  Interpreter.prototype[symbolObservable] = function () {
1317
1327
  return this;
@@ -1332,23 +1342,20 @@ function () {
1332
1342
  */
1333
1343
 
1334
1344
 
1335
- Interpreter.defaultOptions = /*#__PURE__*/function (global) {
1336
- return {
1337
- execute: true,
1338
- deferEvents: true,
1339
- clock: {
1340
- setTimeout: function (fn, ms) {
1341
- return setTimeout(fn, ms);
1342
- },
1343
- clearTimeout: function (id) {
1344
- return clearTimeout(id);
1345
- }
1345
+ Interpreter.defaultOptions = {
1346
+ execute: true,
1347
+ deferEvents: true,
1348
+ clock: {
1349
+ setTimeout: function (fn, ms) {
1350
+ return setTimeout(fn, ms);
1346
1351
  },
1347
- logger: global.console.log.bind(console),
1348
- devTools: false
1349
- };
1350
- }(typeof self !== 'undefined' ? self : global);
1351
-
1352
+ clearTimeout: function (id) {
1353
+ return clearTimeout(id);
1354
+ }
1355
+ },
1356
+ logger: /*#__PURE__*/console.log.bind(console),
1357
+ devTools: false
1358
+ };
1352
1359
  Interpreter.interpret = interpret;
1353
1360
  return Interpreter;
1354
1361
  }();
package/es/invokeUtils.js CHANGED
@@ -1,8 +1,8 @@
1
1
  import { __assign, __rest } from './_virtual/_tslib.js';
2
2
  import './types.js';
3
3
  import { invoke } from './actionTypes.js';
4
- import './environment.js';
5
4
  import './utils.js';
5
+ import './environment.js';
6
6
 
7
7
  function toInvokeSource(src) {
8
8
  if (typeof src === 'string') {
@@ -25,9 +25,9 @@ function toInvokeDefinition(invokeConfig) {
25
25
  type: invoke
26
26
  }, invokeConfig), {
27
27
  toJSON: function () {
28
- var onDone = invokeConfig.onDone,
29
- onError = invokeConfig.onError,
30
- invokeDef = __rest(invokeConfig, ["onDone", "onError"]);
28
+ invokeConfig.onDone;
29
+ invokeConfig.onError;
30
+ var invokeDef = __rest(invokeConfig, ["onDone", "onError"]);
31
31
 
32
32
  return __assign(__assign({}, invokeDef), {
33
33
  type: invoke,
package/es/json.js ADDED
@@ -0,0 +1,86 @@
1
+ import { mapValues, isFunction } from './utils.js';
2
+
3
+ function stringifyFunction(fn) {
4
+ return {
5
+ $function: fn.toString()
6
+ };
7
+ }
8
+
9
+ function getStateNodeId(stateNode) {
10
+ return "#".concat(stateNode.id);
11
+ } // derive config from machine
12
+
13
+
14
+ function machineToJSON(stateNode) {
15
+ var config = {
16
+ type: stateNode.type,
17
+ initial: stateNode.initial === undefined ? undefined : String(stateNode.initial),
18
+ id: stateNode.id,
19
+ key: stateNode.key,
20
+ entry: stateNode.onEntry,
21
+ exit: stateNode.onExit,
22
+ on: mapValues(stateNode.on, function (transition) {
23
+ return transition.map(function (t) {
24
+ return {
25
+ target: t.target ? t.target.map(getStateNodeId) : [],
26
+ source: getStateNodeId(t.source),
27
+ actions: t.actions,
28
+ cond: t.cond,
29
+ eventType: t.eventType
30
+ };
31
+ });
32
+ }),
33
+ invoke: stateNode.invoke,
34
+ states: {}
35
+ };
36
+ Object.values(stateNode.states).forEach(function (sn) {
37
+ config.states[sn.key] = machineToJSON(sn);
38
+ });
39
+ return config;
40
+ }
41
+ function stringify(machine) {
42
+ return JSON.stringify(machineToJSON(machine), function (_, value) {
43
+ if (isFunction(value)) {
44
+ return {
45
+ $function: value.toString()
46
+ };
47
+ }
48
+
49
+ return value;
50
+ });
51
+ }
52
+ function parse(machineString) {
53
+ var config = JSON.parse(machineString, function (_, value) {
54
+ if (typeof value === 'object' && '$function' in value) {
55
+ return new Function(value.value);
56
+ }
57
+
58
+ return value;
59
+ });
60
+ return config;
61
+ }
62
+ function jsonify(value) {
63
+ Object.defineProperty(value, 'toJSON', {
64
+ value: function () {
65
+ return mapValues(value, function (subValue) {
66
+ if (isFunction(subValue)) {
67
+ return stringifyFunction(subValue);
68
+ } else if (typeof subValue === 'object' && !Array.isArray(subValue)) {
69
+ // mostly for assignments
70
+ return mapValues(subValue, function (subSubValue) {
71
+ if (isFunction(subSubValue)) {
72
+ return stringifyFunction(subSubValue);
73
+ }
74
+
75
+ return subSubValue;
76
+ });
77
+ }
78
+
79
+ return subValue;
80
+ });
81
+ }
82
+ });
83
+ return value;
84
+ }
85
+
86
+ export { jsonify, machineToJSON, parse, stringify, stringifyFunction };
package/es/model.js ADDED
@@ -0,0 +1,50 @@
1
+ import { __assign, __spreadArray, __read } from './_virtual/_tslib.js';
2
+ import { assign } from './actions.js';
3
+ import { createMachine } from './Machine.js';
4
+ import { mapValues } from './utils.js';
5
+
6
+ function createModel(initialContext, creators) {
7
+ var eventCreators = creators === null || creators === void 0 ? void 0 : creators.events;
8
+ var actionCreators = creators === null || creators === void 0 ? void 0 : creators.actions;
9
+ var model = {
10
+ initialContext: initialContext,
11
+ assign: assign,
12
+ events: eventCreators ? mapValues(eventCreators, function (fn, eventType) {
13
+ return function () {
14
+ var args = [];
15
+
16
+ for (var _i = 0; _i < arguments.length; _i++) {
17
+ args[_i] = arguments[_i];
18
+ }
19
+
20
+ return __assign(__assign({}, fn.apply(void 0, __spreadArray([], __read(args), false))), {
21
+ type: eventType
22
+ });
23
+ };
24
+ }) : undefined,
25
+ actions: actionCreators ? mapValues(actionCreators, function (fn, actionType) {
26
+ return function () {
27
+ var args = [];
28
+
29
+ for (var _i = 0; _i < arguments.length; _i++) {
30
+ args[_i] = arguments[_i];
31
+ }
32
+
33
+ return __assign(__assign({}, fn.apply(void 0, __spreadArray([], __read(args), false))), {
34
+ type: actionType
35
+ });
36
+ };
37
+ }) : undefined,
38
+ reset: function () {
39
+ return assign(initialContext);
40
+ },
41
+ createMachine: function (config, implementations) {
42
+ return createMachine('context' in config ? config : __assign(__assign({}, config), {
43
+ context: initialContext
44
+ }), implementations);
45
+ }
46
+ };
47
+ return model;
48
+ }
49
+
50
+ export { createModel };
package/es/patterns.js ADDED
@@ -0,0 +1,48 @@
1
+ import { __assign } from './_virtual/_tslib.js';
2
+ import { toEventObject } from './utils.js';
3
+
4
+ function toggle(onState, offState, eventType) {
5
+ var _a, _b, _c;
6
+
7
+ return _a = {}, _a[onState] = {
8
+ on: (_b = {}, _b[eventType] = offState, _b)
9
+ }, _a[offState] = {
10
+ on: (_c = {}, _c[eventType] = onState, _c)
11
+ }, _a;
12
+ }
13
+ var defaultSequencePatternOptions = {
14
+ nextEvent: 'NEXT',
15
+ prevEvent: 'PREV'
16
+ };
17
+ function sequence(items, options) {
18
+ var resolvedOptions = __assign(__assign({}, defaultSequencePatternOptions), options);
19
+
20
+ var states = {};
21
+ var nextEventObject = resolvedOptions.nextEvent === undefined ? undefined : toEventObject(resolvedOptions.nextEvent);
22
+ var prevEventObject = resolvedOptions.prevEvent === undefined ? undefined : toEventObject(resolvedOptions.prevEvent);
23
+ items.forEach(function (item, i) {
24
+ var state = {
25
+ on: {}
26
+ };
27
+
28
+ if (i + 1 === items.length) {
29
+ state.type = 'final';
30
+ }
31
+
32
+ if (nextEventObject && i + 1 < items.length) {
33
+ state.on[nextEventObject.type] = items[i + 1];
34
+ }
35
+
36
+ if (prevEventObject && i > 0) {
37
+ state.on[prevEventObject.type] = items[i - 1];
38
+ }
39
+
40
+ states[item] = state;
41
+ });
42
+ return {
43
+ initial: items[0],
44
+ states: states
45
+ };
46
+ }
47
+
48
+ export { sequence, toggle };
package/es/stateUtils.js CHANGED
@@ -7,6 +7,8 @@ var isLeafNode = function (stateNode) {
7
7
  function getChildren(stateNode) {
8
8
  return Object.keys(stateNode.states).map(function (key) {
9
9
  return stateNode.states[key];
10
+ }).filter(function (sn) {
11
+ return sn.type !== 'history';
10
12
  });
11
13
  }
12
14
  function getAllStateNodes(stateNode) {
@@ -71,10 +73,6 @@ function getConfiguration(prevStateNodes, stateNodes) {
71
73
  for (var _e = (e_3 = void 0, __values(getChildren(s))), _f = _e.next(); !_f.done; _f = _e.next()) {
72
74
  var child = _f.value;
73
75
 
74
- if (child.type === 'history') {
75
- continue;
76
- }
77
-
78
76
  if (!configuration.has(child)) {
79
77
  configuration.add(child);
80
78
 
@@ -77,21 +77,27 @@ export interface TypegenMeta extends TypegenEnabled {
77
77
  eventsCausingServices: Record<string, string>;
78
78
  }
79
79
  export interface ResolvedTypegenMeta extends TypegenMeta {
80
- indexedActions: Record<string, BaseActionObject>;
81
- indexedEvents: Record<string, EventObject>;
80
+ resolved: TypegenMeta & {
81
+ indexedActions: Record<string, BaseActionObject>;
82
+ indexedEvents: Record<string, EventObject>;
83
+ };
82
84
  }
83
85
  export declare type TypegenConstraint = TypegenEnabled | TypegenDisabled;
84
- export declare type AreAllImplementationsAssumedToBeProvided<TResolvedTypesMeta, TMissingImplementations = Prop<TResolvedTypesMeta, 'missingImplementations'>> = IsAny<TResolvedTypesMeta> extends true ? true : TResolvedTypesMeta extends TypegenEnabled ? IsNever<Values<{
86
+ export declare type AreAllImplementationsAssumedToBeProvided<TResolvedTypesMeta, TMissingImplementations = Prop<Prop<TResolvedTypesMeta, 'resolved'>, 'missingImplementations'>> = IsAny<TResolvedTypesMeta> extends true ? true : TResolvedTypesMeta extends TypegenEnabled ? IsNever<Values<{
85
87
  [K in keyof TMissingImplementations]: TMissingImplementations[K];
86
88
  }>> extends true ? true : false : true;
87
- export declare type MarkAllImplementationsAsProvided<TResolvedTypesMeta> = TResolvedTypesMeta & {
89
+ interface AllImplementationsProvided {
88
90
  missingImplementations: {
89
91
  actions: never;
90
92
  delays: never;
91
93
  guards: never;
92
94
  services: never;
93
95
  };
94
- };
96
+ }
97
+ export interface MarkAllImplementationsAsProvided<TResolvedTypesMeta> {
98
+ '@@xstate/typegen': Prop<TResolvedTypesMeta, '@@xstate/typegen'>;
99
+ resolved: Prop<TResolvedTypesMeta, 'resolved'> & AllImplementationsProvided;
100
+ }
95
101
  declare type GenerateServiceEvent<TServiceName, TEventType, TServiceMap extends ServiceMap> = TEventType extends any ? {
96
102
  type: TEventType;
97
103
  } & Prop<TServiceMap, TServiceName> : never;
@@ -105,17 +111,20 @@ declare type AllowAllEvents = {
105
111
  eventsCausingGuards: Record<string, string>;
106
112
  eventsCausingServices: Record<string, string>;
107
113
  };
108
- export declare type ResolveTypegenMeta<TTypesMeta extends TypegenConstraint, TEvent extends EventObject, TAction extends BaseActionObject, TServiceMap extends ServiceMap> = TTypesMeta extends TypegenEnabled ? TTypesMeta & {
109
- indexedActions: IndexByType<TAction>;
110
- indexedEvents: MergeWithInternalEvents<IndexByType<(string extends TEvent['type'] ? never : TEvent) | GenerateServiceEvents<TServiceMap, Prop<TTypesMeta, 'invokeSrcNameMap'>>>, Prop<TTypesMeta, 'internalEvents'>>;
111
- } : MarkAllImplementationsAsProvided<TypegenDisabled> & AllowAllEvents & {
112
- indexedActions: IndexByType<TAction>;
113
- indexedEvents: Record<string, TEvent> & {
114
- __XSTATE_ALLOW_ANY_INVOKE_DATA_HACK__: {
115
- data: any;
114
+ export interface ResolveTypegenMeta<TTypesMeta extends TypegenConstraint, TEvent extends EventObject, TAction extends BaseActionObject, TServiceMap extends ServiceMap> {
115
+ '@@xstate/typegen': TTypesMeta['@@xstate/typegen'];
116
+ resolved: TTypesMeta extends TypegenEnabled ? TTypesMeta & {
117
+ indexedActions: IndexByType<TAction>;
118
+ indexedEvents: MergeWithInternalEvents<IndexByType<(string extends TEvent['type'] ? never : TEvent) | GenerateServiceEvents<TServiceMap, Prop<TTypesMeta, 'invokeSrcNameMap'>>>, Prop<TTypesMeta, 'internalEvents'>>;
119
+ } : TypegenDisabled & AllImplementationsProvided & AllowAllEvents & {
120
+ indexedActions: IndexByType<TAction>;
121
+ indexedEvents: Record<string, TEvent> & {
122
+ __XSTATE_ALLOW_ANY_INVOKE_DATA_HACK__: {
123
+ data: any;
124
+ };
116
125
  };
126
+ invokeSrcNameMap: Record<string, '__XSTATE_ALLOW_ANY_INVOKE_DATA_HACK__'>;
117
127
  };
118
- invokeSrcNameMap: Record<string, '__XSTATE_ALLOW_ANY_INVOKE_DATA_HACK__'>;
119
- };
128
+ }
120
129
  export {};
121
130
  //# sourceMappingURL=typegenTypes.d.ts.map
package/es/types.d.ts CHANGED
@@ -489,16 +489,16 @@ export declare type ActionFunctionMap<TContext, TEvent extends EventObject, TAct
489
489
  export declare type DelayFunctionMap<TContext, TEvent extends EventObject> = Record<string, DelayConfig<TContext, TEvent>>;
490
490
  export declare type ServiceConfig<TContext, TEvent extends EventObject = AnyEventObject> = string | AnyStateMachine | InvokeCreator<TContext, TEvent>;
491
491
  export declare type DelayConfig<TContext, TEvent extends EventObject> = number | DelayExpr<TContext, TEvent>;
492
- declare type MachineOptionsActions<TContext, TResolvedTypesMeta, TEventsCausingActions = Prop<TResolvedTypesMeta, 'eventsCausingActions'>, TIndexedEvents = Prop<TResolvedTypesMeta, 'indexedEvents'>, TIndexedActions = Prop<TResolvedTypesMeta, 'indexedActions'>> = {
492
+ declare type MachineOptionsActions<TContext, TResolvedTypesMeta, TEventsCausingActions = Prop<Prop<TResolvedTypesMeta, 'resolved'>, 'eventsCausingActions'>, TIndexedEvents = Prop<Prop<TResolvedTypesMeta, 'resolved'>, 'indexedEvents'>, TIndexedActions = Prop<Prop<TResolvedTypesMeta, 'resolved'>, 'indexedActions'>> = {
493
493
  [K in keyof TEventsCausingActions]?: ActionObject<TContext, Cast<Prop<TIndexedEvents, TEventsCausingActions[K]>, EventObject>> | ActionFunction<TContext, Cast<Prop<TIndexedEvents, TEventsCausingActions[K]>, EventObject>, Cast<Prop<TIndexedActions, K>, BaseActionObject>>;
494
494
  };
495
- declare type MachineOptionsDelays<TContext, TResolvedTypesMeta, TEventsCausingDelays = Prop<TResolvedTypesMeta, 'eventsCausingDelays'>, TIndexedEvents = Prop<TResolvedTypesMeta, 'indexedEvents'>> = {
495
+ declare type MachineOptionsDelays<TContext, TResolvedTypesMeta, TEventsCausingDelays = Prop<Prop<TResolvedTypesMeta, 'resolved'>, 'eventsCausingDelays'>, TIndexedEvents = Prop<Prop<TResolvedTypesMeta, 'resolved'>, 'indexedEvents'>> = {
496
496
  [K in keyof TEventsCausingDelays]?: DelayConfig<TContext, Cast<Prop<TIndexedEvents, TEventsCausingDelays[K]>, EventObject>>;
497
497
  };
498
- declare type MachineOptionsGuards<TContext, TResolvedTypesMeta, TEventsCausingGuards = Prop<TResolvedTypesMeta, 'eventsCausingGuards'>, TIndexedEvents = Prop<TResolvedTypesMeta, 'indexedEvents'>> = {
498
+ declare type MachineOptionsGuards<TContext, TResolvedTypesMeta, TEventsCausingGuards = Prop<Prop<TResolvedTypesMeta, 'resolved'>, 'eventsCausingGuards'>, TIndexedEvents = Prop<Prop<TResolvedTypesMeta, 'resolved'>, 'indexedEvents'>> = {
499
499
  [K in keyof TEventsCausingGuards]?: ConditionPredicate<TContext, Cast<Prop<TIndexedEvents, TEventsCausingGuards[K]>, EventObject>>;
500
500
  };
501
- declare type MachineOptionsServices<TContext, TResolvedTypesMeta, TEventsCausingServices = Prop<TResolvedTypesMeta, 'eventsCausingServices'>, TIndexedEvents = Prop<TResolvedTypesMeta, 'indexedEvents'>, TInvokeSrcNameMap = Prop<TResolvedTypesMeta, 'invokeSrcNameMap'>> = {
501
+ declare type MachineOptionsServices<TContext, TResolvedTypesMeta, TEventsCausingServices = Prop<Prop<TResolvedTypesMeta, 'resolved'>, 'eventsCausingServices'>, TIndexedEvents = Prop<Prop<TResolvedTypesMeta, 'resolved'>, 'indexedEvents'>, TInvokeSrcNameMap = Prop<Prop<TResolvedTypesMeta, 'resolved'>, 'invokeSrcNameMap'>> = {
502
502
  [K in keyof TEventsCausingServices]?: AnyStateMachine | InvokeCreator<TContext, Cast<Prop<TIndexedEvents, TEventsCausingServices[K]>, EventObject>, Prop<Prop<TIndexedEvents, Prop<TInvokeSrcNameMap, K>>, 'data'>, EventObject, Cast<TIndexedEvents[keyof TIndexedEvents], EventObject>>;
503
503
  };
504
504
  declare type MakeKeysRequired<T extends string> = {
@@ -519,14 +519,14 @@ declare type GenerateGuardsConfigPart<TContext, TResolvedTypesMeta, TRequireMiss
519
519
  declare type GenerateServicesConfigPart<TContext, TResolvedTypesMeta, TRequireMissingImplementations, TMissingImplementations> = MaybeMakeMissingImplementationsRequired<'services', Prop<TMissingImplementations, 'services'>, TRequireMissingImplementations> & {
520
520
  services?: MachineOptionsServices<TContext, TResolvedTypesMeta>;
521
521
  };
522
- export declare type InternalMachineOptions<TContext, TEvent extends EventObject, TResolvedTypesMeta, TRequireMissingImplementations extends boolean = false, TMissingImplementations = Prop<TResolvedTypesMeta, 'missingImplementations'>> = GenerateActionsConfigPart<TContext, TResolvedTypesMeta, TRequireMissingImplementations, TMissingImplementations> & GenerateDelaysConfigPart<TContext, TResolvedTypesMeta, TRequireMissingImplementations, TMissingImplementations> & GenerateGuardsConfigPart<TContext, TResolvedTypesMeta, TRequireMissingImplementations, TMissingImplementations> & GenerateServicesConfigPart<TContext, TResolvedTypesMeta, TRequireMissingImplementations, TMissingImplementations> & {
522
+ export declare type InternalMachineOptions<TContext, TEvent extends EventObject, TResolvedTypesMeta, TRequireMissingImplementations extends boolean = false, TMissingImplementations = Prop<Prop<TResolvedTypesMeta, 'resolved'>, 'missingImplementations'>> = GenerateActionsConfigPart<TContext, TResolvedTypesMeta, TRequireMissingImplementations, TMissingImplementations> & GenerateDelaysConfigPart<TContext, TResolvedTypesMeta, TRequireMissingImplementations, TMissingImplementations> & GenerateGuardsConfigPart<TContext, TResolvedTypesMeta, TRequireMissingImplementations, TMissingImplementations> & GenerateServicesConfigPart<TContext, TResolvedTypesMeta, TRequireMissingImplementations, TMissingImplementations> & {
523
523
  /**
524
524
  * @deprecated Use `services` instead.
525
525
  */
526
526
  activities?: Record<string, ActivityConfig<TContext, TEvent>>;
527
527
  };
528
528
  export declare type MachineOptions<TContext, TEvent extends EventObject, TAction extends BaseActionObject = BaseActionObject, TServiceMap extends ServiceMap = ServiceMap, TTypesMeta extends TypegenConstraint = TypegenDisabled> = InternalMachineOptions<TContext, TEvent, ResolveTypegenMeta<TTypesMeta, TEvent, TAction, TServiceMap>>;
529
- export interface MachineConfig<TContext, TStateSchema extends StateSchema, TEvent extends EventObject, TAction extends BaseActionObject = BaseActionObject, TServiceMap extends ServiceMap = ServiceMap, TTypesMeta = TypegenDisabled> extends StateNodeConfig<NoInfer<TContext>, TStateSchema, TEvent, TAction> {
529
+ export interface MachineConfig<TContext, TStateSchema extends StateSchema, TEvent extends EventObject, TAction extends BaseActionObject = BaseActionObject, TServiceMap extends ServiceMap = ServiceMap, TTypesMeta = TypegenDisabled> extends StateNodeConfig<NoInfer<TContext>, TStateSchema, NoInfer<TEvent>, TAction> {
530
530
  /**
531
531
  * The initial context (extended state)
532
532
  */
@@ -572,7 +572,7 @@ export interface HistoryStateNode<TContext> extends StateNode<TContext> {
572
572
  export interface StateMachine<TContext, TStateSchema extends StateSchema, TEvent extends EventObject, TTypestate extends Typestate<TContext> = {
573
573
  value: any;
574
574
  context: TContext;
575
- }, TAction extends BaseActionObject = BaseActionObject, TServiceMap extends ServiceMap = ServiceMap, TResolvedTypesMeta = ResolveTypegenMeta<TypegenDisabled, TEvent, TAction, TServiceMap>> extends StateNode<TContext, TStateSchema, TEvent, TTypestate, TServiceMap, TResolvedTypesMeta> {
575
+ }, TAction extends BaseActionObject = BaseActionObject, TServiceMap extends ServiceMap = ServiceMap, TResolvedTypesMeta = ResolveTypegenMeta<TypegenDisabled, NoInfer<TEvent>, TAction, TServiceMap>> extends StateNode<TContext, TStateSchema, TEvent, TTypestate, TServiceMap, TResolvedTypesMeta> {
576
576
  id: string;
577
577
  states: StateNode<TContext, TStateSchema, TEvent, TTypestate, TServiceMap, TResolvedTypesMeta>['states'];
578
578
  withConfig(options: InternalMachineOptions<TContext, TEvent, TResolvedTypesMeta, true>, context?: TContext | (() => TContext)): StateMachine<TContext, TStateSchema, TEvent, TTypestate, TAction, TServiceMap, AreAllImplementationsAssumedToBeProvided<TResolvedTypesMeta> extends false ? MarkAllImplementationsAsProvided<TResolvedTypesMeta> : TResolvedTypesMeta>;
@@ -1011,9 +1011,9 @@ export declare type ActorRefWithDeprecatedState<TContext, TEvent extends EventOb
1011
1011
  */
1012
1012
  state: State<TContext, TEvent, any, TTypestate, TResolvedTypesMeta>;
1013
1013
  };
1014
- export declare type ActorRefFrom<T> = ReturnTypeOrValue<T> extends infer R ? R extends StateMachine<infer TContext, any, infer TEvent, infer TTypestate, any, any, infer TResolvedTypesMeta> ? ActorRefWithDeprecatedState<TContext, TEvent, TTypestate, TResolvedTypesMeta> : R extends Promise<infer U> ? ActorRef<never, U> : R extends Behavior<infer TEvent, infer TEmitted> ? ActorRef<TEvent, TEmitted> : never : never;
1014
+ export declare type ActorRefFrom<T> = ReturnTypeOrValue<T> extends infer R ? R extends StateMachine<infer TContext, any, infer TEvent, infer TTypestate, any, any, infer TResolvedTypesMeta> ? ActorRefWithDeprecatedState<TContext, TEvent, TTypestate, AreAllImplementationsAssumedToBeProvided<TResolvedTypesMeta> extends false ? MarkAllImplementationsAsProvided<TResolvedTypesMeta> : TResolvedTypesMeta> : R extends Promise<infer U> ? ActorRef<never, U> : R extends Behavior<infer TEvent, infer TEmitted> ? ActorRef<TEvent, TEmitted> : never : never;
1015
1015
  export declare type AnyInterpreter = Interpreter<any, any, any, any, any>;
1016
- export declare type InterpreterFrom<T extends AnyStateMachine | ((...args: any[]) => AnyStateMachine)> = T extends StateMachine<infer TContext, infer TStateSchema, infer TEvent, infer TTypestate, any, any, infer TResolvedTypesMeta> ? Interpreter<TContext, TStateSchema, TEvent, TTypestate, TResolvedTypesMeta> : T extends (...args: any[]) => StateMachine<infer TContext, infer TStateSchema, infer TEvent, infer TTypestate, any, any, infer TResolvedTypesMeta> ? Interpreter<TContext, TStateSchema, TEvent, TTypestate, TResolvedTypesMeta> : never;
1016
+ export declare type InterpreterFrom<T extends AnyStateMachine | ((...args: any[]) => AnyStateMachine)> = ReturnTypeOrValue<T> extends StateMachine<infer TContext, infer TStateSchema, infer TEvent, infer TTypestate, any, any, infer TResolvedTypesMeta> ? Interpreter<TContext, TStateSchema, TEvent, TTypestate, AreAllImplementationsAssumedToBeProvided<TResolvedTypesMeta> extends false ? MarkAllImplementationsAsProvided<TResolvedTypesMeta> : TResolvedTypesMeta> : never;
1017
1017
  export declare type MachineOptionsFrom<T extends AnyStateMachine | ((...args: any[]) => AnyStateMachine), TRequireMissingImplementations extends boolean = false> = ReturnTypeOrValue<T> extends StateMachine<infer TContext, any, infer TEvent, any, any, any, infer TResolvedTypesMeta> ? InternalMachineOptions<TContext, TEvent, TResolvedTypesMeta, TRequireMissingImplementations> : never;
1018
1018
  export declare type __ResolvedTypesMetaFrom<T> = T extends StateMachine<any, any, any, any, any, any, infer TResolvedTypesMeta> ? TResolvedTypesMeta : never;
1019
1019
  export interface ActorContext<TEvent extends EventObject, TEmitted> {
package/es/utils.js CHANGED
@@ -1,8 +1,11 @@
1
- import { __assign, __spreadArray, __read, __values } from './_virtual/_tslib.js';
1
+ import { __values, __spreadArray, __read, __assign } from './_virtual/_tslib.js';
2
2
  import { DEFAULT_GUARD_TYPE, TARGETLESS_KEY, STATE_DELIMITER } from './constants.js';
3
3
  import { IS_PRODUCTION } from './environment.js';
4
4
 
5
5
  var _a;
6
+ function keys(value) {
7
+ return Object.keys(value);
8
+ }
6
9
  function matchesState(parentStateId, childStateId, delimiter) {
7
10
  if (delimiter === void 0) {
8
11
  delimiter = STATE_DELIMITER;
@@ -39,6 +42,13 @@ function getEventType(event) {
39
42
  throw new Error('Events must be strings or objects with a string event.type property.');
40
43
  }
41
44
  }
45
+ function getActionType(action) {
46
+ try {
47
+ return isString(action) || typeof action === 'number' ? "".concat(action) : isFunction(action) ? action.name : action.type;
48
+ } catch (e) {
49
+ throw new Error('Actions must be strings or objects with a string action.type property.');
50
+ }
51
+ }
42
52
  function toStatePath(stateId, delimiter) {
43
53
  try {
44
54
  if (isArray(stateId)) {
@@ -213,6 +223,46 @@ function toStatePaths(stateValue) {
213
223
  }));
214
224
  return result;
215
225
  }
226
+ function pathsToStateValue(paths) {
227
+ var e_4, _a;
228
+
229
+ var result = {};
230
+
231
+ if (paths && paths.length === 1 && paths[0].length === 1) {
232
+ return paths[0][0];
233
+ }
234
+
235
+ try {
236
+ for (var paths_1 = __values(paths), paths_1_1 = paths_1.next(); !paths_1_1.done; paths_1_1 = paths_1.next()) {
237
+ var currentPath = paths_1_1.value;
238
+ var marker = result; // tslint:disable-next-line:prefer-for-of
239
+
240
+ for (var i = 0; i < currentPath.length; i++) {
241
+ var subPath = currentPath[i];
242
+
243
+ if (i === currentPath.length - 2) {
244
+ marker[subPath] = currentPath[i + 1];
245
+ break;
246
+ }
247
+
248
+ marker[subPath] = marker[subPath] || {};
249
+ marker = marker[subPath];
250
+ }
251
+ }
252
+ } catch (e_4_1) {
253
+ e_4 = {
254
+ error: e_4_1
255
+ };
256
+ } finally {
257
+ try {
258
+ if (paths_1_1 && !paths_1_1.done && (_a = paths_1.return)) _a.call(paths_1);
259
+ } finally {
260
+ if (e_4) throw e_4.error;
261
+ }
262
+ }
263
+
264
+ return result;
265
+ }
216
266
  function flatten(array) {
217
267
  var _a;
218
268
 
@@ -573,4 +623,4 @@ function createInvokeId(stateNodeId, index) {
573
623
  return "".concat(stateNodeId, ":invocation[").concat(index, "]");
574
624
  }
575
625
 
576
- export { createInvokeId, evaluateGuard, flatten, getEventType, interopSymbols, isActor, isArray, isBehavior, isBuiltInEvent, isFunction, isMachine, isObservable, isPromiseLike, isStateLike, isString, mapContext, mapFilterValues, mapValues, matchesState, nestedPath, normalizeTarget, partition, path, pathToStateValue, reportUnhandledExceptionOnInvocation, symbolObservable, toArray, toArrayStrict, toEventObject, toGuard, toInvokeSource, toObserver, toSCXMLEvent, toStatePath, toStatePaths, toStateValue, toTransitionConfigArray, uniqueId, updateContext, updateHistoryStates, updateHistoryValue, warn };
626
+ export { createInvokeId, evaluateGuard, flatten, getActionType, getEventType, interopSymbols, isActor, isArray, isBehavior, isBuiltInEvent, isFunction, isMachine, isObservable, isPromiseLike, isStateLike, isString, keys, mapContext, mapFilterValues, mapValues, matchesState, nestedPath, normalizeTarget, partition, path, pathToStateValue, pathsToStateValue, reportUnhandledExceptionOnInvocation, symbolObservable, toArray, toArrayStrict, toEventObject, toGuard, toInvokeSource, toObserver, toSCXMLEvent, toStatePath, toStatePaths, toStateValue, toTransitionConfigArray, uniqueId, updateContext, updateHistoryStates, updateHistoryValue, warn };
@@ -0,0 +1,32 @@
1
+ import { ActorRef, EmittedFrom } from '.';
2
+ interface WaitForOptions {
3
+ /**
4
+ * How long to wait before rejecting, if no emitted
5
+ * state satisfies the predicate.
6
+ *
7
+ * @default 10_000 (10 seconds)
8
+ */
9
+ timeout: number;
10
+ }
11
+ /**
12
+ * Subscribes to an actor ref and waits for its emitted value to satisfy
13
+ * a predicate, and then resolves with that value.
14
+ *
15
+ * @example
16
+ * ```js
17
+ * const state = await waitFor(someService, state => {
18
+ * return state.hasTag('loaded');
19
+ * });
20
+ *
21
+ * state.hasTag('loaded'); // true
22
+ * ```
23
+ *
24
+ * @param actorRef The actor ref to subscribe to
25
+ * @param predicate Determines if a value matches the condition to wait for
26
+ * @param options
27
+ * @returns A promise that eventually resolves to the emitted value
28
+ * that matches the condition
29
+ */
30
+ export declare function waitFor<TActorRef extends ActorRef<any, any>>(actorRef: TActorRef, predicate: (emitted: EmittedFrom<TActorRef>) => boolean, options?: Partial<WaitForOptions>): Promise<EmittedFrom<TActorRef>>;
31
+ export {};
32
+ //# sourceMappingURL=waitFor.d.ts.map