xstate 6.0.0-alpha.21 → 6.0.0-alpha.23

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 (41) hide show
  1. package/dist/{StateMachine-3c17fe3e.esm.js → StateMachine-022864fd.esm.js} +183 -64
  2. package/dist/{StateMachine-550ff7f2.development.cjs.js → StateMachine-53114dce.development.cjs.js} +187 -63
  3. package/dist/{StateMachine-1b155670.cjs.js → StateMachine-aad57180.cjs.js} +187 -63
  4. package/dist/{StateMachine-e25dd61f.development.esm.js → StateMachine-d2247245.development.esm.js} +183 -64
  5. package/dist/declarations/src/State.d.ts +4 -2
  6. package/dist/declarations/src/StateMachine.d.ts +5 -4
  7. package/dist/declarations/src/actions.d.ts +10 -8
  8. package/dist/declarations/src/actors/logic.d.ts +5 -21
  9. package/dist/declarations/src/createActor.d.ts +3 -1
  10. package/dist/declarations/src/fsm.d.ts +3 -1
  11. package/dist/declarations/src/index.d.ts +2 -2
  12. package/dist/declarations/src/spawn.d.ts +3 -3
  13. package/dist/declarations/src/stateUtils.d.ts +1 -1
  14. package/dist/declarations/src/system.d.ts +34 -9
  15. package/dist/declarations/src/transitionActions.d.ts +5 -1
  16. package/dist/declarations/src/types.d.ts +70 -51
  17. package/dist/{index-3f87408c.esm.js → index-3609e096.esm.js} +782 -389
  18. package/dist/{index-ec7c7a2d.development.cjs.js → index-41c0375c.development.cjs.js} +790 -390
  19. package/dist/{index-e694228c.cjs.js → index-434fac23.cjs.js} +789 -389
  20. package/dist/{index-d39fb138.development.esm.js → index-f5407323.development.esm.js} +783 -390
  21. package/dist/xstate-actors.cjs.js +1 -1
  22. package/dist/xstate-actors.development.cjs.js +1 -1
  23. package/dist/xstate-actors.development.esm.js +1 -1
  24. package/dist/xstate-actors.esm.js +1 -1
  25. package/dist/xstate-actors.umd.min.js +1 -1
  26. package/dist/xstate-actors.umd.min.js.map +1 -1
  27. package/dist/xstate-graph.cjs.js +2 -2
  28. package/dist/xstate-graph.development.cjs.js +2 -2
  29. package/dist/xstate-graph.development.esm.js +2 -2
  30. package/dist/xstate-graph.esm.js +2 -2
  31. package/dist/xstate-graph.umd.min.js +1 -1
  32. package/dist/xstate-graph.umd.min.js.map +1 -1
  33. package/dist/xstate.cjs.js +82 -103
  34. package/dist/xstate.cjs.mjs +1 -0
  35. package/dist/xstate.development.cjs.js +82 -103
  36. package/dist/xstate.development.cjs.mjs +1 -0
  37. package/dist/xstate.development.esm.js +80 -102
  38. package/dist/xstate.esm.js +80 -102
  39. package/dist/xstate.umd.min.js +1 -1
  40. package/dist/xstate.umd.min.js.map +1 -1
  41. package/package.json +1 -1
@@ -1,54 +1,125 @@
1
- import { P as ProcessingStatus, H as resolveReferencedActor, e as createActor, S as STATE_DELIMITER, I as mapValues, t as toArray, J as createInvokeId, K as getDelayedTransitions, L as evaluateCandidate, M as formatTransition, N as NULL_EVENT, O as toTransitionConfigArray, Q as createInvokeTimeoutEvent, R as getCandidates, U as formatRouteTransitions, V as resolveStateValue, W as getAllStateNodes, l as getStateNodes, Y as createMachineSnapshot, Z as isInFinalState, f as macrostep, d as deriveDeferredStarts, _ as cloneMachineSnapshot, $ as transitionNode, m as matchesEventDescriptor, a0 as getTransitionResult, a1 as hasEffect, a2 as createErrorPlatformEvent, r as resolveActionsWithContext, g as createInitEvent, h as initialMicrostep, a3 as toStatePath, a4 as isStateId, a5 as getStateNodeByPath, a6 as getPersistedSnapshot, a7 as $$ACTOR_TYPE } from './index-3f87408c.esm.js';
1
+ import { M as setSnapshotActorRef, N as getSnapshotActorRef, O as createSnapshotSystem, q as isMachineSnapshot, h as createActor, S as STATE_DELIMITER, P as mapValues, t as toArray, Q as createInvokeId, R as getDelayedTransitions, U as evaluateCandidate, V as formatTransition, W as NULL_EVENT, Y as toTransitionConfigArray, Z as createInvokeTimeoutEvent, _ as getCandidates, $ as formatRouteTransitions, a0 as resolveStateValue, a1 as getAllStateNodes, s as getStateNodes, a2 as createMachineSnapshot, a3 as isInFinalState, j as macrostep, a4 as cloneMachineSnapshot, a5 as transitionNode, e as XSTATE_TIMER, m as matchesEventDescriptor, a6 as getTransitionResult, a7 as hasEffect, a8 as createErrorPlatformEvent, r as resolveActionsWithContext, k as createInitEvent, l as createSpawnEffect, n as initialMicrostep, a9 as toStatePath, aa as isStateId, ab as getStateNodeByPath, ac as getPersistedSnapshot, ad as resolveReferencedActor, ae as $$ACTOR_TYPE } from './index-3609e096.esm.js';
2
2
 
3
- function createSpawner(actorScope, {
4
- machine,
5
- context
6
- }, event, spawnedChildren) {
7
- const spawn = (src, options) => {
8
- if (typeof src === 'string') {
9
- const logic = resolveReferencedActor(machine, src);
10
- if (!logic) {
11
- throw new Error(`Actor logic '${src}' not implemented in machine '${machine.id}'`);
12
- }
13
- const actor = createActor(logic, {
14
- id: options?.id,
15
- parent: actorScope.self,
16
- syncSnapshot: options?.syncSnapshot,
17
- input: typeof options?.input === 'function' ? options.input({
18
- context,
19
- event,
20
- self: actorScope.self
21
- }) : options?.input,
22
- src,
23
- registryKey: options?.registryKey
24
- });
25
- spawnedChildren[actor.id] = actor;
26
- return actor;
27
- } else {
28
- const actor = createActor(src, {
29
- id: options?.id,
30
- parent: actorScope.self,
31
- syncSnapshot: options?.syncSnapshot,
32
- input: options?.input,
33
- src,
34
- registryKey: options?.registryKey
35
- });
36
- return actor;
37
- }
38
- };
3
+ function createSpawner(actorScope, actorSources, spawnedChildren) {
39
4
  return (src, options) => {
40
- const actor = spawn(src, options); // TODO: fix types
41
- spawnedChildren[actor.id] = actor;
42
- actorScope.defer(() => {
43
- if (actor._processingStatus === ProcessingStatus.Stopped) {
44
- return;
45
- }
46
- actor.start();
5
+ const referencedSrc = Object.entries(actorSources).find(([, logic]) => logic === src)?.[0];
6
+ const actor = actorScope.system.createActorRef(src, {
7
+ id: options?.id,
8
+ parent: actorScope.self,
9
+ syncSnapshot: options?.syncSnapshot,
10
+ input: options?.input,
11
+ src: referencedSrc ?? src,
12
+ registryKey: options?.registryKey
47
13
  });
14
+ spawnedChildren[actor.id] = actor;
48
15
  return actor;
49
16
  };
50
17
  }
51
18
 
19
+ /** @internal */
20
+ function setInertActorScopeSnapshot(actorScope, snapshot, attachActorRef = true) {
21
+ actorScope.self._snapshot = snapshot;
22
+ if (attachActorRef && snapshot && typeof snapshot === 'object') {
23
+ setSnapshotActorRef(snapshot, actorScope.self);
24
+ }
25
+ return snapshot;
26
+ }
27
+
28
+ /** @internal */
29
+ function isInertActorScope(actorScope) {
30
+ return !!actorScope.self.options?._inert;
31
+ }
32
+
33
+ /** @internal */
34
+ function attachSnapshotActorRef(actorLogic, actorScope, snapshot) {
35
+ const snapshotScope = createInertActorScope(actorLogic, snapshot, actorScope.self);
36
+ return setInertActorScopeSnapshot(snapshotScope, snapshot);
37
+ }
38
+
39
+ /** @internal */
40
+ function createInertActorScope(actorLogic, snapshot, sourceSelf) {
41
+ const snapshotRef = snapshot ? getSnapshotActorRef(snapshot) : undefined;
42
+ const previousSelf = sourceSelf ?? snapshotRef?.actor;
43
+ const baseSystem = previousSelf?.system;
44
+ const system = previousSelf && baseSystem ? createSnapshotSystem(baseSystem, previousSelf, isMachineSnapshot(snapshot) ? snapshot.children : {}, sourceSelf ? undefined : snapshotRef?.systemState) : undefined;
45
+ const self = createActor(actorLogic, {
46
+ _inert: true,
47
+ ...(previousSelf ? {
48
+ id: previousSelf.id
49
+ } : {}),
50
+ ...(system ? {
51
+ _systemRef: {
52
+ current: system
53
+ }
54
+ } : {})
55
+ });
56
+ if (previousSelf?._parent) {
57
+ self._parent = previousSelf._parent;
58
+ }
59
+ if (snapshot) {
60
+ self._snapshot = snapshot;
61
+ }
62
+ const actorScope = {
63
+ self: self,
64
+ defer: () => {},
65
+ id: self.id,
66
+ logger: self.system._logger,
67
+ sessionId: self.sessionId,
68
+ stopChild: child => child._stop(),
69
+ system: self.system,
70
+ emit: event => self.system.emitEvent(self, event),
71
+ actionExecutor: () => {}
72
+ };
73
+ return actorScope;
74
+ }
75
+
76
+ /** @deprecated Use `initialTransition(…)` instead. */
77
+ function getInitialSnapshot(actorLogic, ...[input]) {
78
+ const actorScope = createInertActorScope(actorLogic);
79
+ return actorLogic.initialTransition(input, actorScope)[0];
80
+ }
81
+
82
+ /**
83
+ * Determines the next snapshot for the given `actorLogic` based on the given
84
+ * `snapshot` and `event`.
85
+ *
86
+ * If the `snapshot` is `undefined`, the initial snapshot of the `actorLogic` is
87
+ * used.
88
+ *
89
+ * @deprecated Use `transition(…)` instead.
90
+ * @example
91
+ *
92
+ * ```ts
93
+ * import { getNextSnapshot } from 'xstate';
94
+ * import { trafficLightMachine } from './trafficLightMachine.ts';
95
+ *
96
+ * const nextSnapshot = getNextSnapshot(
97
+ * trafficLightMachine, // actor logic
98
+ * undefined, // snapshot (or initial state if undefined)
99
+ * { type: 'TIMER' }
100
+ * ); // event object
101
+ *
102
+ * console.log(nextSnapshot.value);
103
+ * // => 'yellow'
104
+ *
105
+ * const nextSnapshot2 = getNextSnapshot(
106
+ * trafficLightMachine, // actor logic
107
+ * nextSnapshot, // snapshot
108
+ * { type: 'TIMER' }
109
+ * ); // event object
110
+ *
111
+ * console.log(nextSnapshot2.value);
112
+ * // =>'red'
113
+ * ```
114
+ */
115
+ function getNextSnapshot(actorLogic, snapshot, event) {
116
+ const actorScope = createInertActorScope(actorLogic, snapshot);
117
+ const transitionResult = actorLogic.transition(snapshot, event, actorScope);
118
+ const nextSnapshot = Array.isArray(transitionResult) ? transitionResult[0] : transitionResult;
119
+ setInertActorScopeSnapshot(actorScope, nextSnapshot, false);
120
+ return nextSnapshot === snapshot ? nextSnapshot : attachSnapshotActorRef(actorLogic, actorScope, nextSnapshot);
121
+ }
122
+
52
123
  const cache = new WeakMap();
53
124
  function memo(object, key, fn) {
54
125
  let memoizedData = cache.get(object);
@@ -541,19 +612,37 @@ class StateMachine {
541
612
  * @param event The received event
542
613
  */
543
614
  transition(snapshot, event, actorScope) {
544
- const fastSnapshot = this._transitionFast(snapshot, event, actorScope);
615
+ const usesInertScope = !actorScope;
616
+ const resolvedActorScope = actorScope ?? createInertActorScope(this, snapshot);
617
+ if (usesInertScope) {
618
+ setInertActorScopeSnapshot(resolvedActorScope, snapshot, false);
619
+ }
620
+ const fastSnapshot = this._transitionFast(snapshot, event, resolvedActorScope);
545
621
  if (fastSnapshot) {
546
- return [fastSnapshot, []];
622
+ if (usesInertScope) {
623
+ setInertActorScopeSnapshot(resolvedActorScope, fastSnapshot, false);
624
+ }
625
+ const returnedSnapshot = usesInertScope && fastSnapshot !== snapshot ? attachSnapshotActorRef(this, resolvedActorScope, fastSnapshot) : this._attachPureActorRef(fastSnapshot, resolvedActorScope);
626
+ return [returnedSnapshot, []];
547
627
  }
548
628
  const {
549
629
  snapshot: nextSnapshot,
550
630
  microsteps
551
- } = macrostep(snapshot, event, actorScope, []);
552
- return [nextSnapshot, this._collectEffects(microsteps)];
631
+ } = macrostep(snapshot, event, resolvedActorScope, []);
632
+ if (usesInertScope) {
633
+ setInertActorScopeSnapshot(resolvedActorScope, nextSnapshot, false);
634
+ }
635
+ const returnedSnapshot = usesInertScope ? nextSnapshot === snapshot ? nextSnapshot : attachSnapshotActorRef(this, resolvedActorScope, nextSnapshot) : this._attachPureActorRef(nextSnapshot, resolvedActorScope);
636
+ return [returnedSnapshot, this._collectEffects(microsteps)];
637
+ }
638
+ _collectEffects(microsteps) {
639
+ return microsteps.flatMap(([, actions]) => actions);
553
640
  }
554
- _collectEffects(microsteps, initialActions = []) {
555
- const effects = [...initialActions, ...microsteps.flatMap(([, actions]) => actions)];
556
- return [...effects, ...deriveDeferredStarts(effects)];
641
+ _attachPureActorRef(snapshot, actorScope) {
642
+ if (isInertActorScope(actorScope)) {
643
+ return snapshot;
644
+ }
645
+ return attachSnapshotActorRef(this, actorScope, snapshot);
557
646
  }
558
647
  _transitionFast(snapshot, event, actorScope) {
559
648
  if (snapshot.status !== 'active' || typeof snapshot.value !== 'string' || this.root.always?.length) {
@@ -614,6 +703,9 @@ class StateMachine {
614
703
  return transitionNode(this.root, snapshot.value, snapshot, event, self) || [];
615
704
  }
616
705
  isInternalEventType(eventType) {
706
+ if (eventType === XSTATE_TIMER) {
707
+ return true;
708
+ }
617
709
  for (const descriptor of this.internalEventDescriptors) {
618
710
  if (matchesEventDescriptor(eventType, descriptor)) {
619
711
  return true;
@@ -680,10 +772,10 @@ class StateMachine {
680
772
  _nodes: [this.root],
681
773
  children: {},
682
774
  status: 'active'
683
- }, this);
775
+ }, this, actorScope.self);
684
776
  if (typeof context === 'function') {
685
777
  const children = {};
686
- const spawn = createSpawner(actorScope, preInitial, initEvent, children);
778
+ const spawn = createSpawner(actorScope, this.implementations.actorSources, children);
687
779
  const resolvedContext = context({
688
780
  spawn,
689
781
  input: initEvent.input,
@@ -713,30 +805,37 @@ class StateMachine {
713
805
  return this.initialTransition(input, actorScope)[0];
714
806
  }
715
807
  initialTransition(input, actorScope) {
808
+ const usesInertScope = !actorScope;
809
+ const resolvedActorScope = actorScope ?? createInertActorScope(this);
716
810
  const initEvent = createInitEvent(input); // TODO: fix;
717
811
  const internalQueue = [];
718
- const preInitialState = this._getPreInitialState(actorScope, initEvent);
812
+ const preInitialState = this._getPreInitialState(resolvedActorScope, initEvent);
813
+ const contextSpawnEffects = Object.values(preInitialState.children).filter(Boolean).map(actor => createSpawnEffect(actor));
719
814
  let nextState;
720
815
  let initialActions = [];
721
816
  let microsteps = [];
722
817
  let macroState;
723
818
  try {
724
- [nextState, initialActions] = initialMicrostep(this.root, preInitialState, actorScope, initEvent, internalQueue);
819
+ [nextState, initialActions] = initialMicrostep(this.root, preInitialState, resolvedActorScope, initEvent, internalQueue);
725
820
  ({
726
821
  snapshot: macroState,
727
822
  microsteps
728
- } = macrostep(nextState, initEvent, actorScope, internalQueue));
823
+ } = macrostep(nextState, initEvent, resolvedActorScope, internalQueue, [[nextState, [...contextSpawnEffects, ...initialActions]]]));
729
824
  } catch (err) {
730
825
  if (!this.root.config.onError) {
731
826
  throw err;
732
827
  }
733
828
  const errorEvent = createErrorPlatformEvent('execution', err);
734
- const errorMacrostep = macrostep(preInitialState, errorEvent, actorScope, []);
829
+ const errorMacrostep = macrostep(preInitialState, errorEvent, resolvedActorScope, [], [[preInitialState, contextSpawnEffects]]);
735
830
  macroState = errorMacrostep.snapshot;
736
831
  microsteps = errorMacrostep.microsteps;
737
832
  initialActions = [];
738
833
  }
739
- return [macroState, this._collectEffects(microsteps, initialActions)];
834
+ if (usesInertScope) {
835
+ setInertActorScopeSnapshot(resolvedActorScope, macroState, false);
836
+ }
837
+ const returnedSnapshot = usesInertScope ? attachSnapshotActorRef(this, resolvedActorScope, macroState) : this._attachPureActorRef(macroState, resolvedActorScope);
838
+ return [returnedSnapshot, this._collectEffects(microsteps)];
740
839
  }
741
840
  start(snapshot) {
742
841
  // Start rehydrated children that were active when persisted. Freshly
@@ -764,7 +863,9 @@ class StateMachine {
764
863
  getPersistedSnapshot(snapshot, options) {
765
864
  return getPersistedSnapshot(snapshot, options);
766
865
  }
767
- restoreSnapshot(snapshot, _actorScope) {
866
+ restoreSnapshot(snapshot, actorScope) {
867
+ const usesInertScope = !actorScope;
868
+ const resolvedActorScope = actorScope ?? createInertActorScope(this);
768
869
  const persistedVersion = snapshot.version;
769
870
  if (persistedVersion !== this.version) {
770
871
  const migrate = this.config.migrate;
@@ -784,9 +885,9 @@ class StateMachine {
784
885
  if (!logic) {
785
886
  continue;
786
887
  }
787
- const actor = createActor(logic, {
888
+ const actor = resolvedActorScope.system.createActorRef(logic, {
788
889
  id: actorId,
789
- parent: _actorScope.self,
890
+ parent: resolvedActorScope.self,
790
891
  syncSnapshot: actorData.syncSnapshot,
791
892
  snapshot: childState,
792
893
  src,
@@ -797,6 +898,19 @@ class StateMachine {
797
898
  actor._rehydrated = true;
798
899
  children[actorId] = actor;
799
900
  }
901
+ const timers = {};
902
+ const persistedTimers = snapshotData.timers ?? {};
903
+ for (const [id, timer] of Object.entries(persistedTimers)) {
904
+ const target = typeof timer.target === 'string' ? timer.target === 'self' ? 'self' : children[timer.target] : resolvedActorScope.self._parent;
905
+ if (!target) {
906
+ const targetDescription = typeof timer.target === 'string' ? timer.target : timer.target.type;
907
+ throw new Error(`Unable to restore timer '${id}': target actor '${targetDescription}' is unavailable.`);
908
+ }
909
+ timers[id] = {
910
+ ...timer,
911
+ target
912
+ };
913
+ }
800
914
  const reviveHistoryValue = historyValue => {
801
915
  if (!historyValue || typeof historyValue !== 'object') {
802
916
  return {};
@@ -832,11 +946,12 @@ class StateMachine {
832
946
  const restoredSnapshot = createMachineSnapshot({
833
947
  ...persistedRest,
834
948
  children,
949
+ timers,
835
950
  _nodes: nodes,
836
951
  value: snapshotData.value,
837
952
  historyValue: revivedHistoryValue,
838
953
  _stateInputs: snapshotData.stateInputs ?? {}
839
- }, this);
954
+ }, this, resolvedActorScope.self);
840
955
  const seen = new WeakSet();
841
956
  function reviveContext(contextPart) {
842
957
  if (seen.has(contextPart)) {
@@ -855,8 +970,12 @@ class StateMachine {
855
970
  }
856
971
  }
857
972
  reviveContext(restoredSnapshot.context);
858
- return restoredSnapshot;
973
+ if (usesInertScope) {
974
+ setInertActorScopeSnapshot(resolvedActorScope, restoredSnapshot, false);
975
+ return attachSnapshotActorRef(this, resolvedActorScope, restoredSnapshot);
976
+ }
977
+ return this._attachPureActorRef(restoredSnapshot, resolvedActorScope);
859
978
  }
860
979
  }
861
980
 
862
- export { StateMachine as S, StateNode as a };
981
+ export { StateMachine as S, attachSnapshotActorRef as a, getNextSnapshot as b, createInertActorScope as c, StateNode as d, getInitialSnapshot as g, setInertActorScopeSnapshot as s };