xstate 6.0.0-alpha.65 → 6.0.0-alpha.68

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 (73) hide show
  1. package/README.md +4 -4
  2. package/dist/{createActor-b987e971.cjs.js → createActor-009673a7.cjs.js} +554 -424
  3. package/dist/{createActor-4629a290.esm.js → createActor-a8baa71f.esm.js} +547 -418
  4. package/dist/{createActor-1df42c9e.development.cjs.js → createActor-b14a387c.development.cjs.js} +604 -463
  5. package/dist/{createActor-8f57b47b.development.esm.js → createActor-c121cbf9.development.esm.js} +596 -457
  6. package/dist/declarations/src/State.d.ts +30 -6
  7. package/dist/declarations/src/StateMachine.d.ts +5 -6
  8. package/dist/declarations/src/actions.d.ts +5 -3
  9. package/dist/declarations/src/actors/index.d.ts +5 -5
  10. package/dist/declarations/src/actors/listener.d.ts +0 -2
  11. package/dist/declarations/src/actors/logic.d.ts +26 -31
  12. package/dist/declarations/src/actors/promise.d.ts +10 -10
  13. package/dist/declarations/src/actors/subscription.d.ts +0 -2
  14. package/dist/declarations/src/createActor.d.ts +5 -15
  15. package/dist/declarations/src/durable/index.d.ts +9 -9
  16. package/dist/declarations/src/effectDescriptor.d.ts +30 -25
  17. package/dist/declarations/src/index.d.ts +11 -10
  18. package/dist/declarations/src/{createMachineFromConfig.d.ts → machineFromJSON.d.ts} +1 -1
  19. package/dist/declarations/src/machineVersion.types.d.ts +1 -2
  20. package/dist/declarations/src/serialize.d.ts +8 -7
  21. package/dist/declarations/src/setup.d.ts +16 -20
  22. package/dist/declarations/src/stateUtils.d.ts +2 -3
  23. package/dist/declarations/src/system.d.ts +11 -8
  24. package/dist/declarations/src/systemTransition.d.ts +12 -7
  25. package/dist/declarations/src/transition.d.ts +5 -8
  26. package/dist/declarations/src/transitionActions.d.ts +6 -6
  27. package/dist/declarations/src/types.d.ts +109 -62
  28. package/dist/declarations/src/types.v6.d.ts +5 -8
  29. package/dist/declarations/src/utils.d.ts +1 -7
  30. package/dist/declarations/src/validation.types.d.ts +2 -2
  31. package/dist/{effectDescriptor-b2b7deaa.development.cjs.js → effectDescriptor-3e92534c.development.cjs.js} +49 -24
  32. package/dist/{effectDescriptor-c4671afc.development.esm.js → effectDescriptor-7326693b.development.esm.js} +49 -24
  33. package/dist/{effectDescriptor-4cf24593.cjs.js → effectDescriptor-75145bce.cjs.js} +49 -24
  34. package/dist/{effectDescriptor-973fc1ba.esm.js → effectDescriptor-acfd606c.esm.js} +49 -24
  35. package/dist/{index-f201d440.cjs.js → index-45b828dc.cjs.js} +10 -12
  36. package/dist/{index-15382daf.development.esm.js → index-87254d79.development.esm.js} +10 -12
  37. package/dist/{index-52ad3d45.esm.js → index-da387f5d.esm.js} +10 -12
  38. package/dist/{index-0cf33789.development.cjs.js → index-e37fe162.development.cjs.js} +10 -12
  39. package/dist/xstate-actors.cjs.js +3 -5
  40. package/dist/xstate-actors.cjs.mjs +2 -4
  41. package/dist/xstate-actors.development.cjs.js +3 -5
  42. package/dist/xstate-actors.development.cjs.mjs +2 -4
  43. package/dist/xstate-actors.development.esm.js +2 -2
  44. package/dist/xstate-actors.esm.js +2 -2
  45. package/dist/xstate-actors.umd.min.js +1 -1
  46. package/dist/xstate-actors.umd.min.js.map +1 -1
  47. package/dist/xstate-durable.cjs.js +9 -8
  48. package/dist/xstate-durable.development.cjs.js +9 -8
  49. package/dist/xstate-durable.development.esm.js +9 -8
  50. package/dist/xstate-durable.esm.js +9 -8
  51. package/dist/xstate-durable.umd.min.js +1 -1
  52. package/dist/xstate-durable.umd.min.js.map +1 -1
  53. package/dist/xstate-graph.cjs.js +2 -2
  54. package/dist/xstate-graph.development.cjs.js +2 -2
  55. package/dist/xstate-graph.development.esm.js +3 -3
  56. package/dist/xstate-graph.esm.js +3 -3
  57. package/dist/xstate-graph.umd.min.js +1 -1
  58. package/dist/xstate-graph.umd.min.js.map +1 -1
  59. package/dist/xstate-validation.cjs.js +2 -2
  60. package/dist/xstate-validation.development.cjs.js +2 -2
  61. package/dist/xstate-validation.development.esm.js +2 -2
  62. package/dist/xstate-validation.esm.js +2 -2
  63. package/dist/xstate-validation.umd.min.js +1 -1
  64. package/dist/xstate-validation.umd.min.js.map +1 -1
  65. package/dist/xstate.cjs.js +234 -747
  66. package/dist/xstate.cjs.mjs +6 -12
  67. package/dist/xstate.development.cjs.js +238 -752
  68. package/dist/xstate.development.cjs.mjs +6 -12
  69. package/dist/xstate.development.esm.js +235 -743
  70. package/dist/xstate.esm.js +231 -738
  71. package/dist/xstate.umd.min.js +1 -1
  72. package/dist/xstate.umd.min.js.map +1 -1
  73. package/package.json +1 -1
@@ -52,10 +52,13 @@ const TARGETLESS_KEY = '';
52
52
  const NULL_EVENT = '';
53
53
  const STATE_IDENTIFIER = '#';
54
54
  const WILDCARD = '*';
55
- const XSTATE_INIT = '@xstate.init';
55
+ const XSTATE_INIT = 'xstate.init';
56
56
  const XSTATE_START = '@xstate.start';
57
57
  const XSTATE_SPAWN = '@xstate.spawn';
58
- const XSTATE_STOP = '@xstate.stop';
58
+ /** The event an actor receives when it is stopped. */
59
+ const XSTATE_STOP = 'xstate.stop';
60
+ /** The effect that stops a child actor. */
61
+ const XSTATE_STOP_EFFECT = '@xstate.stop';
59
62
  const XSTATE_TERMINATE = '@xstate.terminate';
60
63
  const XSTATE_TIMER = 'xstate.timer';
61
64
  const XSTATE_LOGIC_EFFECT_RESOLVE = 'xstate.logic.effect.resolve';
@@ -76,9 +79,6 @@ function createAfterEvent(delayRef, id) {
76
79
  stateId: id
77
80
  };
78
81
  }
79
- function createAfterEventId(delayRef, id) {
80
- return `xstate.after.${delayRef}.${id}`;
81
- }
82
82
 
83
83
  /**
84
84
  * Returns an event that represents an implicit state-level timeout. Fired when
@@ -88,13 +88,10 @@ function createAfterEventId(delayRef, id) {
88
88
  */
89
89
  function createTimeoutEvent(id) {
90
90
  return {
91
- type: 'xstate.timeout',
91
+ type: 'xstate.timeout.state',
92
92
  stateId: id
93
93
  };
94
94
  }
95
- function createTimeoutEventId(id) {
96
- return `xstate.timeout.${id}`;
97
- }
98
95
 
99
96
  /**
100
97
  * Returns an event that represents an implicit invoke-level timeout. Fired when
@@ -109,9 +106,6 @@ function createInvokeTimeoutEvent(invokeId, sessionId) {
109
106
  sessionId
110
107
  };
111
108
  }
112
- function createInvokeTimeoutEventId(invokeId) {
113
- return `xstate.timeout.actor.${invokeId}`;
114
- }
115
109
 
116
110
  /**
117
111
  * Returns an event that represents that a final state node has been reached in
@@ -183,18 +177,131 @@ function reportUnhandledError(err) {
183
177
 
184
178
  const symbolObservable = (() => typeof Symbol === 'function' && Symbol.observable || '@@observable')();
185
179
 
180
+ /**
181
+ * @internal The identity fields of a built-in timer event (`after`, state and
182
+ * invoke `timeout`), or `undefined` for any other event.
183
+ */
184
+ function getBuiltInTimerIdentity(event) {
185
+ const {
186
+ stateId,
187
+ delay,
188
+ actorId
189
+ } = event;
190
+ switch (event.type) {
191
+ case 'xstate.after':
192
+ // Same field order as the event, so persisted events serialize alike.
193
+ return {
194
+ type: event.type,
195
+ delay,
196
+ stateId
197
+ };
198
+ case 'xstate.timeout.state':
199
+ return {
200
+ type: event.type,
201
+ stateId
202
+ };
203
+ case 'xstate.timeout.actor':
204
+ return {
205
+ type: event.type,
206
+ actorId
207
+ };
208
+ }
209
+ return undefined;
210
+ }
211
+
212
+ /** @internal The key of a logical timer, effect or cancellation. */
213
+ function getTimerKey(timer) {
214
+ if (timer.id !== undefined) {
215
+ return {
216
+ id: timer.id
217
+ };
218
+ }
219
+ if (timer.seq !== undefined) {
220
+ return {
221
+ seq: timer.seq
222
+ };
223
+ }
224
+ return {
225
+ event: getBuiltInTimerIdentity(timer.event) ?? timer.event
226
+ };
227
+ }
228
+
229
+ /**
230
+ * @internal Reads the timer key carried by a firing input or cancellation
231
+ * (`{ id }`, `{ seq }` or `{ event }` fields).
232
+ */
233
+ function readTimerKey(input) {
234
+ const value = input;
235
+ if (typeof value.id === 'string') {
236
+ return {
237
+ id: value.id
238
+ };
239
+ }
240
+ if (typeof value.seq === 'number') {
241
+ return {
242
+ seq: value.seq
243
+ };
244
+ }
245
+ if (value.event && typeof value.event === 'object' && typeof value.event.type === 'string') {
246
+ return {
247
+ event: value.event
248
+ };
249
+ }
250
+ return undefined;
251
+ }
252
+
253
+ /** @internal Whether a logical timer has the given key. */
254
+ function matchesTimerKey(timer, key) {
255
+ if ('id' in key) {
256
+ return timer.id === key.id;
257
+ }
258
+ if (timer.id !== undefined) {
259
+ return false;
260
+ }
261
+ if ('seq' in key) {
262
+ return timer.seq === key.seq;
263
+ }
264
+ if (timer.seq !== undefined) {
265
+ return false;
266
+ }
267
+ const event = timer.event;
268
+ const pattern = key.event;
269
+ for (const field in pattern) {
270
+ if (event[field] !== pattern[field]) {
271
+ return false;
272
+ }
273
+ }
274
+ return true;
275
+ }
276
+
277
+ /** @internal A private string form of a timer key, for in-memory maps. */
278
+ function serializeTimerKey(key) {
279
+ if ('id' in key) {
280
+ return JSON.stringify(['id', key.id]);
281
+ }
282
+ if ('seq' in key) {
283
+ return JSON.stringify(['seq', key.seq]);
284
+ }
285
+ return JSON.stringify(['event', getBuiltInTimerIdentity(key.event) ?? key.event]);
286
+ }
287
+
288
+ /** @internal The private local-scheduler key of an actor's logical timer. */
289
+ function getScheduledTimerKey(actor, key) {
290
+ return `${actor.sessionId}|${serializeTimerKey(key)}`;
291
+ }
292
+
186
293
  // Runtime metadata stays outside pure snapshots. Timer objects survive unrelated
187
294
  // transitions; a cancelled/replaced timer gets a new object and a new deadline.
188
295
  const starts = new WeakMap();
189
296
 
190
297
  /** @internal */
191
298
  function getTimerStart(timer) {
192
- return starts.get(timer) ?? timer.startedAt;
299
+ return starts.get(timer) ?? timer.scheduledAt;
193
300
  }
194
301
 
195
302
  /** @internal */
196
- function recordTimerStart(timer, startedAt) {
197
- starts.set(timer, startedAt);
303
+ function recordTimerStart(timer, scheduledAt) {
304
+ starts.set(timer, scheduledAt);
198
305
  }
199
306
 
200
307
  function assertSendToEvent(event) {
@@ -211,19 +318,27 @@ const builtInActions = {
211
318
  ['@xstate.start']: actor => {
212
319
  return actor.system.startActor(actor);
213
320
  },
214
- ['@xstate.raise']: (actorScope, _event, options) => {
215
- return actorScope.system.scheduleTimer(actorScope.self, options.id, options?.delay ?? 0);
321
+ ['@xstate.raise']: (actorScope, event, options) => {
322
+ return actorScope.system.scheduleTimer(actorScope.self, getTimerKey({
323
+ id: options.id,
324
+ seq: options.seq,
325
+ event
326
+ }), options?.delay ?? 0);
216
327
  },
217
328
  ['@xstate.sendTo']: (actorScope, actor, event, options) => {
218
329
  assertSendToEvent(event);
219
330
  if (options?.delay !== undefined) {
220
- return actorScope.system.scheduleTimer(actorScope.self, options.id, options?.delay ?? 0);
331
+ return actorScope.system.scheduleTimer(actorScope.self, getTimerKey({
332
+ id: options.id,
333
+ seq: options.seq,
334
+ event
335
+ }), options?.delay ?? 0);
221
336
  } else {
222
337
  return actorScope.system._relay(actorScope.self, actor, event);
223
338
  }
224
339
  },
225
- ['@xstate.cancel']: (actorScope, sendId) => {
226
- return actorScope.system.cancelTimer(actorScope.self, sendId);
340
+ ['@xstate.cancel']: (actorScope, key) => {
341
+ return actorScope.system.cancelTimer(actorScope.self, key);
227
342
  },
228
343
  ['@xstate.stop']: (actorScope, actor) => {
229
344
  return actorScope.system.stopActor(actor);
@@ -391,11 +506,10 @@ function createListenerLogic() {
391
506
  }
392
507
  relayMappedToParent(self, system, () => mapper(emittedEvent));
393
508
  });
394
- }, 'xstate.listener');
509
+ }, '@xstate.listener');
395
510
  }
396
511
 
397
- // Singleton logic instance
398
- /** @public */
512
+ /** @internal The logic of helper actors created by `enq.listen()`. */
399
513
  const listenerLogic = /* #__PURE__ */createListenerLogic();
400
514
 
401
515
  /** @public */
@@ -446,88 +560,12 @@ function createSubscriptionLogic() {
446
560
  // Actor completed without output (stopped); no action needed
447
561
  }
448
562
  });
449
- }, 'xstate.subscription');
563
+ }, '@xstate.subscription');
450
564
  }
451
565
 
452
- // Singleton logic instance
453
- /** @public */
566
+ /** @internal The logic of helper actors created by `enq.subscribeTo()`. */
454
567
  const subscriptionLogic = /* #__PURE__ */createSubscriptionLogic();
455
568
 
456
- /** Marks the internal lazy scope without imposing structure on custom runtimes. @internal */
457
- const lazyActorScope = Symbol();
458
- /** Whether actor capabilities are represented by a lazy pure-transition scope. @internal */
459
- function isLazyActorScope(actorScope) {
460
- return !!actorScope[lazyActorScope];
461
- }
462
-
463
- /** Reads parent metadata without otherwise touching actor capabilities. @internal */
464
- function getActorScopeParent(actorScope) {
465
- return isLazyActorScope(actorScope) ? actorScope._parent : actorScope.self._parent;
466
- }
467
-
468
- /** Adds only `self`, preserving callback surfaces that expose no other capabilities. @internal */
469
- function withActorSelf(args, actorScope) {
470
- if (!isLazyActorScope(actorScope)) {
471
- return Object.assign(args, {
472
- self: actorScope.self
473
- });
474
- }
475
- Object.defineProperty(args, 'self', {
476
- enumerable: true,
477
- get: () => actorScope.self
478
- });
479
- return args;
480
- }
481
-
482
- /** Adds the actor reference and parent without exposing the system. @internal */
483
- function withActorSelfAndParent(args, actorScope) {
484
- if (!isLazyActorScope(actorScope)) {
485
- const self = actorScope.self;
486
- return Object.assign(args, {
487
- self,
488
- parent: self._parent
489
- });
490
- }
491
- Object.defineProperties(args, {
492
- self: {
493
- enumerable: true,
494
- get: () => actorScope.self
495
- },
496
- parent: {
497
- enumerable: true,
498
- get: () => getActorScopeParent(actorScope)
499
- }
500
- });
501
- return args;
502
- }
503
-
504
- /** Adds actor capabilities without reading them until the callback does. @internal */
505
- function withActorScope(args, actorScope) {
506
- if (!isLazyActorScope(actorScope)) {
507
- const actorArgs = args;
508
- const self = actorScope.self;
509
- actorArgs.self = self;
510
- actorArgs.system = actorScope.system;
511
- actorArgs.parent = self._parent;
512
- return actorArgs;
513
- }
514
- Object.defineProperties(args, {
515
- self: {
516
- enumerable: true,
517
- get: () => actorScope.self
518
- },
519
- system: {
520
- enumerable: true,
521
- get: () => actorScope.system
522
- },
523
- parent: {
524
- enumerable: true,
525
- get: () => getActorScopeParent(actorScope)
526
- }
527
- });
528
- return args;
529
- }
530
-
531
569
  function execCustomEffect() {
532
570
  const result = this.action?.(...this.args);
533
571
  return result;
@@ -628,54 +666,68 @@ function execTerminateEffect(runtime = this.actor.system) {
628
666
  return runtime.terminateActor(this.actor, termination);
629
667
  }
630
668
  function execRaiseEffect(runtime = this.source.system) {
631
- return runtime.scheduleTimer(this.source, this.id, this.delay ?? 0);
669
+ return runtime.scheduleTimer(this.source, getTimerKey(this), this.delay ?? 0);
632
670
  }
633
671
  function execSendToEffect(runtime = this.source.system) {
634
672
  assertSendToEvent(this.event);
635
673
  if (this.delay !== undefined) {
636
- return runtime.scheduleTimer(this.source, this.id, this.delay);
674
+ return runtime.scheduleTimer(this.source, getTimerKey(this), this.delay);
637
675
  }
638
676
  return runtime.sendEvent(this.source, this.target, this.event);
639
677
  }
640
678
  function execCancelEffect(runtime = this.source.system) {
641
- return runtime.cancelTimer(this.source, this.id);
679
+ return runtime.cancelTimer(this.source, readTimerKey(this));
642
680
  }
643
681
  function updateLogicalTimers(snapshot, effect, actorScope) {
644
- if (!isBuiltInExecutableAction(effect)) {
682
+ if (!isBuiltInExecutableEffect(effect)) {
645
683
  return snapshot;
646
684
  }
647
685
  if (effect.type === '@xstate.cancel') {
648
- if (!snapshot.timers?.[effect.id]) {
686
+ const key = readTimerKey(effect);
687
+ if (!snapshot.timers?.some(timer => matchesTimerKey(timer, key))) {
649
688
  return snapshot;
650
689
  }
651
- const timers = {
652
- ...snapshot.timers
653
- };
654
- delete timers[effect.id];
655
690
  return {
656
691
  ...snapshot,
657
- timers
692
+ timers: snapshot.timers.filter(timer => !matchesTimerKey(timer, key))
658
693
  };
659
694
  }
660
695
  if (effect.type !== '@xstate.raise' && effect.type !== '@xstate.sendTo' || effect.delay === undefined) {
661
696
  return snapshot;
662
697
  }
698
+
699
+ // A delayed raise or send without an `id` is numbered by the actor's
700
+ // timer sequence. Built-in timers (`after`, `timeout`) have neither; their
701
+ // event identifies them.
663
702
  let nextTimerId = snapshot._nextTimerId ?? 0;
664
- const id = effect.id ?? `xstate.timer.auto.${nextTimerId++}`;
665
- effect.id = id;
703
+ if (effect.id === undefined && !getBuiltInTimerIdentity(effect.event)) {
704
+ effect.seq = nextTimerId++;
705
+ const args = effect.args;
706
+ args[args.length - 1] = {
707
+ ...args[args.length - 1],
708
+ seq: effect.seq
709
+ };
710
+ }
666
711
  const target = effect.type === '@xstate.raise' || effect.target === actorScope.self ? 'self' : effect.target;
712
+ const timer = {
713
+ ...(effect.id !== undefined && {
714
+ id: effect.id
715
+ }),
716
+ ...(effect.seq !== undefined && {
717
+ seq: effect.seq
718
+ }),
719
+ delay: effect.delay,
720
+ type: effect.type,
721
+ event: effect.event,
722
+ target
723
+ };
724
+ // Scheduling a timer that is already pending replaces it in place.
725
+ const key = getTimerKey(timer);
726
+ const timers = snapshot.timers ?? [];
727
+ const index = timers.findIndex(pending => matchesTimerKey(pending, key));
667
728
  return {
668
729
  ...snapshot,
669
- timers: {
670
- ...snapshot.timers,
671
- [id]: {
672
- id,
673
- delay: effect.delay,
674
- type: effect.type,
675
- event: effect.event,
676
- target
677
- }
678
- },
730
+ timers: index === -1 ? [...timers, timer] : timers.map((pending, i) => i === index ? timer : pending),
679
731
  _nextTimerId: nextTimerId
680
732
  };
681
733
  }
@@ -810,10 +862,10 @@ function resolveTransitionSpawnSource(actorScope, source) {
810
862
 
811
863
  /**
812
864
  * Internal helper actors (listeners, subscriptions) number their ids from
813
- * system-level counters under `xstate.`-prefixed names; snapshot-owned
865
+ * system-level counters under `@xstate.`-prefixed names; snapshot-owned
814
866
  * children number from per-snapshot counters. The two spaces only stay
815
867
  * collision-free because their prefixes are disjoint, so user sources must
816
- * not enter the reserved namespace.
868
+ * not enter the reserved `xstate.` / `@xstate.` namespaces.
817
869
  */
818
870
  function assertUnreservedPrefix(prefix) {
819
871
  }
@@ -928,7 +980,9 @@ function createTransitionEnqueue(actorScope, actions, internalEvents, actorSubsc
928
980
  const localAllocation = spawnAllocations.get(actorScope) ?? createSpawnAllocation();
929
981
  const props = {
930
982
  cancel: id => {
931
- pushBuiltInAction(actions, builtInActions['@xstate.cancel'], actorScope, id);
983
+ pushBuiltInAction(actions, builtInActions['@xstate.cancel'], actorScope, typeof id === 'string' ? {
984
+ id
985
+ } : id);
932
986
  },
933
987
  emit: emittedEvent => {
934
988
  actions.push(emittedEvent);
@@ -1127,13 +1181,13 @@ function getBuiltInActionFields(action, args) {
1127
1181
  }
1128
1182
  case builtInActions['@xstate.cancel']:
1129
1183
  {
1130
- const [, id] = args;
1184
+ const [, key] = args;
1131
1185
  return {
1132
1186
  type: '@xstate.cancel',
1133
1187
  kind: 'builtin',
1134
1188
  exec: execCancelEffect,
1135
1189
  source: args[0].self,
1136
- id
1190
+ ...key
1137
1191
  };
1138
1192
  }
1139
1193
  case builtInActions['@xstate.stop']:
@@ -1173,6 +1227,7 @@ function createTimerEffect(actorScope, timer, delay) {
1173
1227
  const source = actorScope.self;
1174
1228
  const options = {
1175
1229
  id: timer.id,
1230
+ seq: timer.seq,
1176
1231
  delay
1177
1232
  };
1178
1233
  if (timer.type === '@xstate.raise') {
@@ -1182,6 +1237,9 @@ function createTimerEffect(actorScope, timer, delay) {
1182
1237
  source,
1183
1238
  event: timer.event,
1184
1239
  id: timer.id,
1240
+ ...(timer.seq !== undefined && {
1241
+ seq: timer.seq
1242
+ }),
1185
1243
  delay,
1186
1244
  params: undefined,
1187
1245
  args: [actorScope, timer.event, options],
@@ -1196,6 +1254,9 @@ function createTimerEffect(actorScope, timer, delay) {
1196
1254
  target,
1197
1255
  event: timer.event,
1198
1256
  id: timer.id,
1257
+ ...(timer.seq !== undefined && {
1258
+ seq: timer.seq
1259
+ }),
1199
1260
  delay,
1200
1261
  params: undefined,
1201
1262
  args: [actorScope, target, timer.event, options],
@@ -1286,7 +1347,7 @@ function deriveDeferredStarts(effects) {
1286
1347
  const attachedStarts = [];
1287
1348
  const childStarts = [];
1288
1349
  for (const effect of effects) {
1289
- if (!isBuiltInExecutableAction(effect) || effect.type !== XSTATE_SPAWN) {
1350
+ if (!isBuiltInExecutableEffect(effect) || effect.type !== XSTATE_SPAWN) {
1290
1351
  continue;
1291
1352
  }
1292
1353
  const {
@@ -1304,7 +1365,7 @@ function deriveDeferredStarts(effects) {
1304
1365
  }
1305
1366
 
1306
1367
  /** @public */
1307
- function isBuiltInExecutableAction(action) {
1368
+ function isBuiltInExecutableEffect(action) {
1308
1369
  return action.kind === 'builtin';
1309
1370
  }
1310
1371
 
@@ -1318,28 +1379,10 @@ async function executeEffects(effects, runtime) {
1318
1379
  await effect.exec(runtime);
1319
1380
  }
1320
1381
  }
1321
- function resolveActionsWithContext(currentSnapshot, event, actorScope, actions) {
1382
+ function resolveActionsWithContext(currentSnapshot, _event, actorScope, actions) {
1322
1383
  let intermediateSnapshot = currentSnapshot;
1323
1384
  const executableActions = [];
1324
1385
  for (const action of actions) {
1325
- const actionArgs = isLazyActorScope(actorScope) ? withActorScope({
1326
- context: intermediateSnapshot.context,
1327
- event,
1328
- output: getEventOutput(event),
1329
- children: intermediateSnapshot.children,
1330
- actions: currentSnapshot.machine.sources.actions,
1331
- actors: currentSnapshot.machine.sources.actors
1332
- }, actorScope) : {
1333
- context: intermediateSnapshot.context,
1334
- event,
1335
- output: getEventOutput(event),
1336
- self: actorScope.self,
1337
- system: actorScope.system,
1338
- parent: actorScope.self._parent,
1339
- children: intermediateSnapshot.children,
1340
- actions: currentSnapshot.machine.sources.actions,
1341
- actors: currentSnapshot.machine.sources.actors
1342
- };
1343
1386
  const isInline = typeof action === 'function';
1344
1387
  const actionRecord = getTransitionActionRecord(action);
1345
1388
  let resolvedActionArgs = actionRecord?.args;
@@ -1354,6 +1397,10 @@ function resolveActionsWithContext(currentSnapshot, event, actorScope, actions)
1354
1397
  }
1355
1398
  resolvedActionArgs = [actionRecord.args[0], target, ...actionRecord.args.slice(2)];
1356
1399
  }
1400
+ // A ref that went through JSON stays address-backed through effects and
1401
+ // timers: delivery resolves it to whichever actor is live at the address
1402
+ // then, routes it through a host runtime, or reports a dead letter.
1403
+
1357
1404
  const resolvedAction = isInline ? action : actionRecord ? actionRecord.action.bind(null, ...resolvedActionArgs) : false;
1358
1405
  let actionParams = undefined;
1359
1406
  if (typeof action === 'object' && action !== null) {
@@ -1367,33 +1414,6 @@ function resolveActionsWithContext(currentSnapshot, event, actorScope, actions)
1367
1414
  if (actionRecord?.childUpdate) {
1368
1415
  intermediateSnapshot = applyChildUpdate(intermediateSnapshot, actionRecord.childUpdate, actorScope);
1369
1416
  }
1370
- if (resolvedAction && '_special' in resolvedAction) {
1371
- executableActions.push({
1372
- kind: 'action',
1373
- exec: execCustomEffect,
1374
- type: typeof action === 'object' ? 'action' in action && typeof action.action === 'function' ? action.action.name ?? '(anonymous)' : action.type ?? '(anonymous)' : action.name || '(anonymous)',
1375
- params: actionParams,
1376
- args: [],
1377
- action: undefined
1378
- });
1379
- const specialAction = resolvedAction;
1380
- const res = specialAction(actionArgs, emptyEnqueueObject);
1381
- if (res && ('context' in res || 'children' in res)) {
1382
- // Special-action patches never change `nodes`, so a shallow clone is
1383
- // equivalent to `cloneMachineSnapshot` — and keeps this module (and
1384
- // non-machine logic like `createFSM`) independent of State.ts.
1385
- intermediateSnapshot = {
1386
- ...intermediateSnapshot,
1387
- ...(res.context !== undefined ? {
1388
- context: mergeContextPatch(intermediateSnapshot.context, res.context)
1389
- } : {}),
1390
- ...('children' in res ? {
1391
- children: res.children
1392
- } : {})
1393
- };
1394
- }
1395
- continue;
1396
- }
1397
1417
  if (!resolvedAction || !('resolve' in resolvedAction)) {
1398
1418
  const builtInFields = typeof action === 'object' && action !== null && 'action' in action && typeof action.action === 'function' ? getBuiltInActionFields(action.action, resolvedActionArgs) : undefined;
1399
1419
  const isEmittedEvent = typeof action === 'object' && action !== null && !actionRecord;
@@ -1413,9 +1433,9 @@ function resolveActionsWithContext(currentSnapshot, event, actorScope, actions)
1413
1433
  } : {}),
1414
1434
  ...builtInFields
1415
1435
  };
1416
- const typedExecutableAction = executableAction;
1417
- intermediateSnapshot = updateLogicalTimers(intermediateSnapshot, typedExecutableAction, actorScope);
1418
- executableActions.push(typedExecutableAction);
1436
+ const typedExecutableEffect = executableAction;
1437
+ intermediateSnapshot = updateLogicalTimers(intermediateSnapshot, typedExecutableEffect, actorScope);
1438
+ executableActions.push(typedExecutableEffect);
1419
1439
  continue;
1420
1440
  }
1421
1441
  }
@@ -1441,7 +1461,6 @@ function createEnqueueObject(props, action) {
1441
1461
  }
1442
1462
  const noop = () => {};
1443
1463
  const emptyActor = () => ({});
1444
- const emptyEnqueueObject = createEnqueueObject({}, noop);
1445
1464
 
1446
1465
  function parseDurationToMilliseconds(duration) {
1447
1466
  const normalizedDuration = duration.trim();
@@ -1773,6 +1792,81 @@ function setSnapshotActorRef(snapshot, actor, baseSystem = actor.system, previou
1773
1792
  });
1774
1793
  }
1775
1794
 
1795
+ /** Marks the internal lazy scope without imposing structure on custom runtimes. @internal */
1796
+ const lazyActorScope = Symbol();
1797
+ /** Whether actor capabilities are represented by a lazy pure-transition scope. @internal */
1798
+ function isLazyActorScope(actorScope) {
1799
+ return !!actorScope[lazyActorScope];
1800
+ }
1801
+
1802
+ /** Reads parent metadata without otherwise touching actor capabilities. @internal */
1803
+ function getActorScopeParent(actorScope) {
1804
+ return isLazyActorScope(actorScope) ? actorScope._parent : actorScope.self._parent;
1805
+ }
1806
+
1807
+ /** Adds only `self`, preserving callback surfaces that expose no other capabilities. @internal */
1808
+ function withActorSelf(args, actorScope) {
1809
+ if (!isLazyActorScope(actorScope)) {
1810
+ return Object.assign(args, {
1811
+ self: actorScope.self
1812
+ });
1813
+ }
1814
+ Object.defineProperty(args, 'self', {
1815
+ enumerable: true,
1816
+ get: () => actorScope.self
1817
+ });
1818
+ return args;
1819
+ }
1820
+
1821
+ /** Adds the actor reference and parent without exposing the system. @internal */
1822
+ function withActorSelfAndParent(args, actorScope) {
1823
+ if (!isLazyActorScope(actorScope)) {
1824
+ const self = actorScope.self;
1825
+ return Object.assign(args, {
1826
+ self,
1827
+ parent: self._parent
1828
+ });
1829
+ }
1830
+ Object.defineProperties(args, {
1831
+ self: {
1832
+ enumerable: true,
1833
+ get: () => actorScope.self
1834
+ },
1835
+ parent: {
1836
+ enumerable: true,
1837
+ get: () => getActorScopeParent(actorScope)
1838
+ }
1839
+ });
1840
+ return args;
1841
+ }
1842
+
1843
+ /** Adds actor capabilities without reading them until the callback does. @internal */
1844
+ function withActorScope(args, actorScope) {
1845
+ if (!isLazyActorScope(actorScope)) {
1846
+ const actorArgs = args;
1847
+ const self = actorScope.self;
1848
+ actorArgs.self = self;
1849
+ actorArgs.system = actorScope.system;
1850
+ actorArgs.parent = self._parent;
1851
+ return actorArgs;
1852
+ }
1853
+ Object.defineProperties(args, {
1854
+ self: {
1855
+ enumerable: true,
1856
+ get: () => actorScope.self
1857
+ },
1858
+ system: {
1859
+ enumerable: true,
1860
+ get: () => actorScope.system
1861
+ },
1862
+ parent: {
1863
+ enumerable: true,
1864
+ get: () => getActorScopeParent(actorScope)
1865
+ }
1866
+ });
1867
+ return args;
1868
+ }
1869
+
1776
1870
  /** @internal */
1777
1871
  function setInertActorScopeSnapshot(actorScope, snapshot, attachActorRef = true) {
1778
1872
  const lazyState = getLazyInertActorState(actorScope);
@@ -2082,33 +2176,6 @@ function isInFinalState(stateNodeSet, stateNode) {
2082
2176
  return stateNode.type === 'final';
2083
2177
  }
2084
2178
  const isStateId = str => str[0] === STATE_IDENTIFIER;
2085
- function getLegacyEventType(event) {
2086
- switch (event.type) {
2087
- case 'xstate.done.actor':
2088
- case 'xstate.error.actor':
2089
- return `${event.type}.${event.actorId}`;
2090
- case 'xstate.snapshot.actor':
2091
- return `xstate.snapshot.${event.actorId}`;
2092
- case 'xstate.done.state':
2093
- return `xstate.done.state.${event.stateId}`;
2094
- case 'xstate.after':
2095
- return `xstate.after.${event.delay}.${event.stateId}`;
2096
- case 'xstate.timeout':
2097
- return `xstate.timeout.${event.stateId}`;
2098
- case 'xstate.timeout.actor':
2099
- return `xstate.timeout.actor.${event.actorId}`;
2100
- default:
2101
- return undefined;
2102
- }
2103
- }
2104
- function getEventTypeAliases(event) {
2105
- const legacyType = getLegacyEventType(event);
2106
- return legacyType ? [event.type, legacyType] : [event.type];
2107
- }
2108
- function getEventDescriptorKey(event) {
2109
- const legacyType = getLegacyEventType(event);
2110
- return legacyType ? `${event.type}|${legacyType}` : event.type;
2111
- }
2112
2179
  function matchesActorSession(event, snapshot, actorId) {
2113
2180
  const child = snapshot.children[actorId];
2114
2181
  if (!child || !('sessionId' in event)) {
@@ -2119,49 +2186,19 @@ function matchesActorSession(event, snapshot, actorId) {
2119
2186
  // runtime that owns the child.
2120
2187
  return child.sessionId === undefined || child.sessionId === event.sessionId;
2121
2188
  }
2122
- function normalizeLegacyInternalEvent(event, machine) {
2123
- if (event.type === 'xstate.done.actor' || event.type === 'xstate.error.actor' || event.type === 'xstate.snapshot.actor' || event.type === 'xstate.done.state' || event.type === 'xstate.after' || event.type === 'xstate.timeout' || event.type === 'xstate.timeout.actor') {
2124
- return event;
2125
- }
2126
- const normalizeWithId = (prefix, type, idKey) => event.type.startsWith(prefix) ? {
2127
- ...event,
2128
- type,
2129
- [idKey]: event[idKey] ?? event.type.slice(prefix.length)
2130
- } : undefined;
2131
- const normalized = normalizeWithId('xstate.done.actor.', 'xstate.done.actor', 'actorId') ?? normalizeWithId('xstate.error.actor.', 'xstate.error.actor', 'actorId') ?? normalizeWithId('xstate.snapshot.', 'xstate.snapshot.actor', 'actorId') ?? normalizeWithId('xstate.done.state.', 'xstate.done.state', 'stateId') ?? normalizeWithId('xstate.timeout.actor.', 'xstate.timeout.actor', 'actorId') ?? normalizeWithId('xstate.timeout.', 'xstate.timeout', 'stateId');
2132
- if (normalized) {
2133
- return normalized;
2134
- }
2135
- const afterPrefix = 'xstate.after.';
2136
- if (!event.type.startsWith(afterPrefix)) {
2137
- return event;
2138
- }
2139
- const stateId = [...machine.idMap.keys()].sort((a, b) => b.length - a.length).find(id => event.type.endsWith(`.${id}`));
2140
- if (!stateId) {
2141
- return event;
2142
- }
2143
- const delayText = event.type.slice(afterPrefix.length, -stateId.length - 1);
2144
- return {
2145
- ...event,
2146
- type: 'xstate.after',
2147
- delay: Number.isNaN(+delayText) ? delayText : +delayText,
2148
- stateId
2149
- };
2150
- }
2151
2189
  function getCandidates(stateNode, event) {
2152
- const eventTypes = getEventTypeAliases(event);
2153
- const exactMatches = eventTypes.flatMap(eventType => stateNode.transitions.get(eventType) ?? []);
2154
- const wildcardCandidates = [...stateNode.transitions.keys()].filter(eventDescriptor => !eventTypes.includes(eventDescriptor) && eventTypes.some(eventType => matchesEventDescriptor(eventType, eventDescriptor))).sort((a, b) => b.length - a.length).flatMap(key => stateNode.transitions.get(key));
2190
+ const exactMatches = stateNode.transitions.get(event.type) ?? [];
2191
+ const wildcardCandidates = [...stateNode.transitions.keys()].filter(eventDescriptor => eventDescriptor !== event.type && matchesEventDescriptor(event.type, eventDescriptor)).sort((a, b) => b.length - a.length).flatMap(key => stateNode.transitions.get(key));
2155
2192
  return exactMatches.length ? [...exactMatches, ...wildcardCandidates] : wildcardCandidates;
2156
2193
  }
2157
- function scheduleDelayedEvent(stateNode, timerId, resolveEvent, resolveScheduledDelay) {
2194
+ function scheduleDelayedEvent(stateNode, timerEvent, resolveEvent, resolveScheduledDelay) {
2158
2195
  const oldEntry = stateNode.entry;
2159
2196
  stateNode.entry = (x, enq) => {
2160
2197
  const result = typeof oldEntry === 'function' ? oldEntry(x, enq) : undefined;
2161
2198
  // The entry context patch is applied by the caller after this wrapper returns.
2162
2199
  const context = result?.context !== undefined ? mergeContextPatch(x.context, result.context) : x.context;
2200
+ // Built-in timers have no id: the event identifies them.
2163
2201
  enq.raise(resolveEvent(x), {
2164
- id: timerId,
2165
2202
  delay: resolveScheduledDelay({
2166
2203
  context,
2167
2204
  event: x.event,
@@ -2173,7 +2210,9 @@ function scheduleDelayedEvent(stateNode, timerId, resolveEvent, resolveScheduled
2173
2210
  };
2174
2211
  const oldExit = stateNode.exit;
2175
2212
  stateNode.exit = (_, enq) => {
2176
- enq.cancel(timerId);
2213
+ enq.cancel({
2214
+ event: getBuiltInTimerIdentity(timerEvent)
2215
+ });
2177
2216
  return typeof oldExit === 'function' ? oldExit(_, enq) : undefined;
2178
2217
  };
2179
2218
  }
@@ -2194,7 +2233,7 @@ function getDelayedTransitions(stateNode) {
2194
2233
  // differ only in the event raised, the transition(s) caught, and whether the
2195
2234
  // delay resolves against the machine's `delays` map (invoke timeouts do not).
2196
2235
  //
2197
- // `xstate.timeout` is a dedicated event category so a state-level `timeout`
2236
+ // `xstate.timeout.state` is a dedicated event category so a state-level `timeout`
2198
2237
  // cannot collide with an explicit `after` entry on the same state. Invoke
2199
2238
  // timeouts are scheduled on the enclosing state; completion transitions
2200
2239
  // cancel the timer separately, so it clears even when the parent stays active.
@@ -2204,7 +2243,6 @@ function getDelayedTransitions(stateNode) {
2204
2243
  const delay = Number.isNaN(+key) ? key : +key;
2205
2244
  sources.push({
2206
2245
  event: createAfterEvent(delay, stateNode.id),
2207
- timerId: createAfterEventId(delay, stateNode.id),
2208
2246
  delay,
2209
2247
  transitions: afterConfig[key],
2210
2248
  fromDelaysMap: true
@@ -2214,7 +2252,6 @@ function getDelayedTransitions(stateNode) {
2214
2252
  if (timeoutConfig !== undefined && onTimeoutConfig) {
2215
2253
  sources.push({
2216
2254
  event: createTimeoutEvent(stateNode.id),
2217
- timerId: createTimeoutEventId(stateNode.id),
2218
2255
  delay: timeoutConfig,
2219
2256
  transitions: onTimeoutConfig,
2220
2257
  fromDelaysMap: true
@@ -2223,7 +2260,6 @@ function getDelayedTransitions(stateNode) {
2223
2260
  for (const invokeDef of invokeDefs) {
2224
2261
  sources.push({
2225
2262
  event: createInvokeTimeoutEvent(invokeDef.id),
2226
- timerId: createInvokeTimeoutEventId(invokeDef.id),
2227
2263
  resolveEvent: ({
2228
2264
  children
2229
2265
  }) => createInvokeTimeoutEvent(invokeDef.id, children[invokeDef.id]?.sessionId),
@@ -2240,14 +2276,13 @@ function getDelayedTransitions(stateNode) {
2240
2276
  const delayedTransitions = [];
2241
2277
  for (const {
2242
2278
  event,
2243
- timerId,
2244
2279
  resolveEvent,
2245
2280
  eventMatcher,
2246
2281
  delay,
2247
2282
  transitions,
2248
2283
  fromDelaysMap
2249
2284
  } of sources) {
2250
- scheduleDelayedEvent(stateNode, timerId, resolveEvent ?? (() => event), x => resolveDelay(delay, fromDelaysMap ? x.delays : {}, {
2285
+ scheduleDelayedEvent(stateNode, event, resolveEvent ?? (() => event), x => resolveDelay(delay, fromDelaysMap ? x.delays : {}, {
2251
2286
  context: x.context,
2252
2287
  event: x.event,
2253
2288
  stateNode,
@@ -2859,75 +2894,47 @@ function microstep(transitions, currentSnapshot, actorScope, event, isInitial, i
2859
2894
  return !!targets?.length || !!reenter;
2860
2895
  });
2861
2896
  const getStateActionsAndContext = (transitionFn, context, children, input, kind, stateNode) => {
2862
- if (transitionFn.length === 2) {
2863
- // enqueue action; retrieve
2864
- const actions = [];
2865
- const internalEvents = [];
2866
- let updatedContext;
2867
- const enqueue = createTransitionEnqueue(actorScope, actions, internalEvents, true);
2868
- const args = isLazyActorScope(actorScope) ? withActorScope({
2869
- context,
2870
- event,
2871
- children,
2872
- actions: currentSnapshot.machine.sources.actions,
2873
- actors: currentSnapshot.machine.sources.actors,
2874
- guards: currentSnapshot.machine.sources.guards,
2875
- delays: currentSnapshot.machine.sources.delays,
2876
- input,
2877
- stateNode
2878
- }, actorScope) : {
2879
- context,
2880
- event,
2881
- parent: actorScope.self._parent,
2882
- self: actorScope.self,
2883
- children,
2884
- system: actorScope.system,
2885
- actions: currentSnapshot.machine.sources.actions,
2886
- actors: currentSnapshot.machine.sources.actors,
2887
- guards: currentSnapshot.machine.sources.guards,
2888
- delays: currentSnapshot.machine.sources.delays,
2889
- input,
2890
- stateNode
2891
- };
2892
- let res;
2893
- try {
2894
- res = transitionFn(args, enqueue);
2895
- } finally {
2896
- closeTransitionEnqueue(enqueue);
2897
- }
2898
- assertSyncTransitionResult(res, event, stateNode.id, kind);
2899
- if (res?.context !== undefined) {
2900
- updatedContext = mergeContextPatch(context, res.context);
2901
- }
2902
- return [actions, updatedContext, internalEvents];
2903
- }
2904
-
2905
- // For 1-argument actions, wrap them to include input
2906
- // Preserve _special flag if present (for entry/exit actions)
2907
- const wrappedAction = Object.assign((args, enqueue) => transitionFn(isLazyActorScope(actorScope) ? withActorScope({
2908
- context: args.context,
2909
- event: args.event,
2910
- output: args.output,
2911
- children: args.children,
2912
- actions: args.actions,
2913
- actors: args.actors,
2897
+ const actions = [];
2898
+ const internalEvents = [];
2899
+ let updatedContext;
2900
+ const enqueue = createTransitionEnqueue(actorScope, actions, internalEvents, true);
2901
+ const args = isLazyActorScope(actorScope) ? withActorScope({
2902
+ context,
2903
+ event,
2904
+ output: getEventOutput(event),
2905
+ children,
2906
+ actions: currentSnapshot.machine.sources.actions,
2907
+ actors: currentSnapshot.machine.sources.actors,
2914
2908
  guards: currentSnapshot.machine.sources.guards,
2915
2909
  delays: currentSnapshot.machine.sources.delays,
2916
2910
  input,
2917
2911
  stateNode
2918
2912
  }, actorScope) : {
2919
- ...args,
2913
+ context,
2914
+ event,
2915
+ output: getEventOutput(event),
2916
+ parent: actorScope.self._parent,
2917
+ self: actorScope.self,
2918
+ children,
2919
+ system: actorScope.system,
2920
+ actions: currentSnapshot.machine.sources.actions,
2921
+ actors: currentSnapshot.machine.sources.actors,
2920
2922
  guards: currentSnapshot.machine.sources.guards,
2921
2923
  delays: currentSnapshot.machine.sources.delays,
2922
2924
  input,
2923
2925
  stateNode
2924
- },
2925
- // This function runs during action resolution, where enqueued
2926
- // effects are no longer collected.
2927
- enqueue), '_special' in transitionFn ? {
2928
- _special: true
2929
- } : {});
2930
- return [[wrappedAction], undefined, undefined];
2926
+ };
2927
+ let res;
2928
+ try {
2929
+ res = transitionFn(args, enqueue);
2930
+ } finally {
2931
+ closeTransitionEnqueue(enqueue);
2932
+ }
2933
+ assertSyncTransitionResult(res, event, stateNode.id, kind);
2934
+ if (res?.context !== undefined) {
2935
+ updatedContext = mergeContextPatch(context, res.context);
2936
+ }
2937
+ return [actions, updatedContext, internalEvents, res?.children];
2931
2938
  };
2932
2939
  let nextState = currentSnapshot;
2933
2940
  const getInvokeStopActions = (stateNode, children) => {
@@ -2962,13 +2969,18 @@ function microstep(transitions, currentSnapshot, actorScope, event, isInitial, i
2962
2969
  }
2963
2970
  for (const exitStateNode of statesToExit) {
2964
2971
  const stateInput = getStateInput(currentSnapshot, exitStateNode.id);
2965
- const [exitActions, nextContext, internalEvents] = exitStateNode.exit ? getStateActionsAndContext(exitStateNode.exit, nextState.context, nextState.children, stateInput, 'exit', exitStateNode) : [[], undefined, undefined];
2972
+ const [exitActions, nextContext, internalEvents, nextChildren] = exitStateNode.exit ? getStateActionsAndContext(exitStateNode.exit, nextState.context, nextState.children, stateInput, 'exit', exitStateNode) : [[], undefined, undefined, undefined];
2966
2973
  if (internalEvents?.length) {
2967
2974
  internalQueue.push(...internalEvents);
2968
2975
  }
2969
- if (nextContext) {
2976
+ if (nextContext || nextChildren) {
2970
2977
  nextState = cloneMachineSnapshot(nextState, {
2971
- context: nextContext
2978
+ ...(nextContext ? {
2979
+ context: nextContext
2980
+ } : {}),
2981
+ ...(nextChildren ? {
2982
+ children: nextChildren
2983
+ } : {})
2972
2984
  });
2973
2985
  }
2974
2986
  const [resolvedState, resolvedActions] = resolveActionsWithContext(nextState, event, actorScope, exitActions);
@@ -3153,10 +3165,19 @@ function microstep(transitions, currentSnapshot, actorScope, event, isInitial, i
3153
3165
  statesForDefaultEntry.add(stateNode);
3154
3166
  }
3155
3167
  }
3156
- const stateInputMap = {
3157
- ...currentSnapshot._stateInputs
3158
- };
3168
+
3169
+ // Keep only the inputs of states still active after exiting, so exited
3170
+ // (and re-entered) states never see a stale input.
3171
+ const stateInputMap = {};
3159
3172
  let stateInputsChanged = false;
3173
+ const activeIds = new Set([...mutStateNodeSet].map(sn => sn.id));
3174
+ for (const [id, input] of Object.entries(currentSnapshot._stateInputs ?? {})) {
3175
+ if (activeIds.has(id)) {
3176
+ stateInputMap[id] = input;
3177
+ } else {
3178
+ stateInputsChanged = true;
3179
+ }
3180
+ }
3160
3181
  for (const transition of filteredTransitions) {
3161
3182
  const {
3162
3183
  targets,
@@ -3229,7 +3250,7 @@ function microstep(transitions, currentSnapshot, actorScope, event, isInitial, i
3229
3250
  let contextChangedByEntry = false;
3230
3251
  const stateInput = stateInputMap[stateNodeToEnter.id];
3231
3252
  if (stateNodeToEnter.entry) {
3232
- const [resultActions, nextContext, nextInternalEvents] = getStateActionsAndContext(stateNodeToEnter.entry, context, children, stateInput, 'entry', stateNodeToEnter);
3253
+ const [resultActions, nextContext, nextInternalEvents, nextChildren] = getStateActionsAndContext(stateNodeToEnter.entry, context, children, stateInput, 'entry', stateNodeToEnter);
3233
3254
  actions.push(...resultActions);
3234
3255
  if (nextInternalEvents?.length) {
3235
3256
  internalQueue.push(...nextInternalEvents);
@@ -3238,6 +3259,11 @@ function microstep(transitions, currentSnapshot, actorScope, event, isInitial, i
3238
3259
  context = nextContext;
3239
3260
  contextChangedByEntry = true;
3240
3261
  }
3262
+ if (nextChildren) {
3263
+ nextState = cloneMachineSnapshot(nextState, {
3264
+ children: nextChildren
3265
+ });
3266
+ }
3241
3267
  }
3242
3268
  if (contextChangedByEntry) {
3243
3269
  nextState.context = context;
@@ -3317,9 +3343,9 @@ function microstep(transitions, currentSnapshot, actorScope, event, isInitial, i
3317
3343
  };
3318
3344
 
3319
3345
  // Execute transition content
3320
- const [resolvedTransitionState, transitionExecutableActions] = resolveActionsWithContext(nextState, event, actorScope, transitionActions);
3346
+ const [resolvedTransitionState, transitionExecutableEffects] = resolveActionsWithContext(nextState, event, actorScope, transitionActions);
3321
3347
  nextState = resolvedTransitionState;
3322
- executableActions.push(...transitionExecutableActions);
3348
+ executableActions.push(...transitionExecutableEffects);
3323
3349
  if (context && context !== currentSnapshot.context) {
3324
3350
  nextState = cloneMachineSnapshot(nextState, {
3325
3351
  context
@@ -3337,10 +3363,15 @@ function microstep(transitions, currentSnapshot, actorScope, event, isInitial, i
3337
3363
  nextStateNodesToExit.forEach(stateNode => {
3338
3364
  if (stateNode.exit) {
3339
3365
  const stateInput = getStateInput(nextState, stateNode.id);
3340
- const [exitActions, nextContext, nextInternalEvents] = getStateActionsAndContext(stateNode.exit, nextState.context, nextState.children, stateInput, 'exit', stateNode);
3341
- if (nextContext) {
3366
+ const [exitActions, nextContext, nextInternalEvents, nextChildren] = getStateActionsAndContext(stateNode.exit, nextState.context, nextState.children, stateInput, 'exit', stateNode);
3367
+ if (nextContext || nextChildren) {
3342
3368
  nextState = cloneMachineSnapshot(nextState, {
3343
- context: nextContext
3369
+ ...(nextContext ? {
3370
+ context: nextContext
3371
+ } : {}),
3372
+ ...(nextChildren ? {
3373
+ children: nextChildren
3374
+ } : {})
3344
3375
  });
3345
3376
  }
3346
3377
  allExitActions.push(...exitActions);
@@ -3579,16 +3610,15 @@ function macrostep(snapshot, event, actorScope, internalQueue, initialMicrosteps
3579
3610
  addMicrostep([nextSnapshot, [...stopEffects, ...cancelEffects]], []);
3580
3611
  return completeMacrostep();
3581
3612
  }
3582
- let nextEvent = normalizeLegacyInternalEvent(event, snapshot.machine);
3613
+ let nextEvent = event;
3583
3614
  if (event.type === XSTATE_TIMER) {
3584
- const timer = nextSnapshot.timers[event.id];
3585
- if (!timer) {
3615
+ const key = readTimerKey(event);
3616
+ const index = key ? nextSnapshot.timers.findIndex(timer => matchesTimerKey(timer, key)) : -1;
3617
+ if (index === -1) {
3586
3618
  return completeMacrostep();
3587
3619
  }
3588
- const timers = {
3589
- ...nextSnapshot.timers
3590
- };
3591
- delete timers[timer.id];
3620
+ const timer = nextSnapshot.timers[index];
3621
+ const timers = nextSnapshot.timers.filter((_, i) => i !== index);
3592
3622
  nextSnapshot = cloneMachineSnapshot(nextSnapshot, {
3593
3623
  timers
3594
3624
  });
@@ -3614,7 +3644,6 @@ function macrostep(snapshot, event, actorScope, internalQueue, initialMicrosteps
3614
3644
  }
3615
3645
  // TODO: we should likely only allow transitions selected by very explicit descriptors
3616
3646
  // `*` shouldn't be matched, likely `xstate.error.*` shouldn't be either
3617
- // similarly `xstate.error.actor.*` and `xstate.error.actor.todo.*` have to be considered too
3618
3647
  nextSnapshot = cloneMachineSnapshot(snapshot, {
3619
3648
  status: 'error',
3620
3649
  error: currentEvent.error
@@ -3782,14 +3811,13 @@ function stopChildren(snapshot, event, actorScope) {
3782
3811
  return resolveActionsWithContext(snapshot, event, actorScope, actions);
3783
3812
  }
3784
3813
  function cancelTimers(snapshot, event, actorScope) {
3785
- const timerIds = Object.keys(snapshot.timers);
3786
- if (!timerIds.length) {
3814
+ if (!snapshot.timers.length) {
3787
3815
  return [snapshot, []];
3788
3816
  }
3789
3817
  const actions = [];
3790
3818
  const enqueue = createTransitionEnqueue(actorScope, actions, []);
3791
- for (const id of timerIds) {
3792
- enqueue.cancel(id);
3819
+ for (const timer of snapshot.timers) {
3820
+ enqueue.cancel(getTimerKey(timer));
3793
3821
  }
3794
3822
  return resolveActionsWithContext(snapshot, event, actorScope, actions);
3795
3823
  }
@@ -3853,6 +3881,44 @@ function isRemoteActorRef(actorRef) {
3853
3881
  return actorRef._remote === true;
3854
3882
  }
3855
3883
 
3884
+ /**
3885
+ * @internal Whether a send target is an actor reference that went through
3886
+ * JSON (`actor.toJSON()`): plain data carrying an address, not an actor.
3887
+ */
3888
+ function isSerializedActorRef(target) {
3889
+ if (typeof target !== 'object' || target === null || Array.isArray(target) || typeof target.$actor !== 'string') {
3890
+ return false;
3891
+ }
3892
+ for (const key in target) {
3893
+ if (key !== '$actor' && key !== 'incarnation') {
3894
+ return false;
3895
+ }
3896
+ }
3897
+ const incarnation = target.incarnation;
3898
+ return incarnation === undefined || typeof incarnation === 'string';
3899
+ }
3900
+
3901
+ /** @internal The actor id that the last segment of an address encodes. */
3902
+ function getAddressId(address) {
3903
+ const segment = address.slice(address.lastIndexOf('/') + 1);
3904
+ return segment.includes('%') ? segment.replaceAll('%2F', '/').replaceAll('%25', '%') : segment;
3905
+ }
3906
+
3907
+ /** @internal The error reported when no live actor has a serialized address. */
3908
+ function createMissingAddressError(target) {
3909
+ return new Error(target.incarnation === undefined ? `Unable to send event to actor '${target.$actor}': no live actor has that address` : `Unable to send event to actor '${target.$actor}' (incarnation '${target.incarnation}'): no live actor has that address and incarnation`);
3910
+ }
3911
+
3912
+ /**
3913
+ * @internal The live actor a serialized ref names: the actor at its address,
3914
+ * and, when the ref carries an `incarnation`, only that incarnation. A ref
3915
+ * without one follows whichever actor is live at the address.
3916
+ */
3917
+ function resolveSerializedActorRef(system, target) {
3918
+ const live = system._getByAddress?.(target.$actor);
3919
+ return live && (target.incarnation === undefined || live.sessionId === target.incarnation) ? live : undefined;
3920
+ }
3921
+
3856
3922
  /**
3857
3923
  * The lifecycle-only snapshot a remote handle exposes. `active` is accurate
3858
3924
  * by construction: a completion removes the child from its parent's
@@ -3940,13 +4006,10 @@ function createRemoteActorRef(system, options) {
3940
4006
  return false;
3941
4007
  },
3942
4008
  // The same shape Actor.toJSON produces, so serialized snapshots carry
3943
- // one actor-reference marker whether a child is co-located or remote.
4009
+ // one actor-reference shape whether a child is co-located or remote.
3944
4010
  toJSON() {
3945
4011
  return {
3946
- xstate$type: ACTOR_REF_TYPE,
3947
- id: options.id,
3948
- address: options.address,
3949
- src: options.src
4012
+ $actor: options.address
3950
4013
  };
3951
4014
  }
3952
4015
  };
@@ -3956,6 +4019,10 @@ function createRemoteActorRef(system, options) {
3956
4019
  }
3957
4020
 
3958
4021
  const emptySnapshotRecord = Object.freeze({});
4022
+ const emptyTimers = Object.freeze([]);
4023
+ function compactTimers(timers) {
4024
+ return timers?.length ? timers : emptyTimers;
4025
+ }
3959
4026
  function compactSnapshotRecord(value) {
3960
4027
  if (value === emptySnapshotRecord) {
3961
4028
  return value;
@@ -3974,14 +4041,32 @@ function isMachineSnapshot(value) {
3974
4041
  * Non-literal state values accept any value.
3975
4042
  */
3976
4043
 
4044
+ /**
4045
+ * `true` if `TTestStateValue` can match `TStateValue`, checked per position:
4046
+ * each literal key names a state at its level and each literal child matches
4047
+ * that state. A non-literal value (`string`, or a map with `string` keys)
4048
+ * passes at its own position only, so `{ checkout: string }` is accepted and
4049
+ * `{ nope: 'payment', checkout: string }` is not.
4050
+ */
4051
+
3977
4052
  /**
3978
4053
  * `unknown` if `matches(...)` accepts `TTestStateValue` for `TStateValue`,
3979
- * otherwise `never`. Non-literal test values are always accepted.
4054
+ * otherwise `never`. Literal values must name states; a non-literal value
4055
+ * (such as a `string` leaf) is accepted at its own position.
4056
+ */
4057
+
4058
+ /**
4059
+ * The `#id` references a snapshot (or union of snapshots) accepts, read from
4060
+ * its `getMeta()` keys so the overload does not depend on the state schema.
3980
4061
  */
3981
4062
 
3982
4063
  /** @public */
3983
4064
 
3984
4065
  const machineSnapshotMatches = function matches(testValue) {
4066
+ if (typeof testValue === 'string' && isStateId(testValue)) {
4067
+ const stateNode = this.machine.getStateNodeById(testValue);
4068
+ return this.nodes.includes(stateNode);
4069
+ }
3985
4070
  return matchesState(testValue, this.value);
3986
4071
  };
3987
4072
  const machineSnapshotHasTag = function hasTag(tag) {
@@ -4044,7 +4129,7 @@ function createMachineSnapshot(config, machine, actorRef) {
4044
4129
  value: config.value ?? getStateValue(machine.root, config._nodes),
4045
4130
  tags: collectTags(config._nodes),
4046
4131
  children: compactSnapshotRecord(config.children),
4047
- timers: compactSnapshotRecord(config.timers),
4132
+ timers: compactTimers(config.timers),
4048
4133
  historyValue: compactSnapshotRecord(config.historyValue),
4049
4134
  _stateInputs: compactSnapshotRecord(config._stateInputs),
4050
4135
  _nextTimerId: config._nextTimerId ?? 0,
@@ -4077,7 +4162,7 @@ function cloneMachineSnapshot(snapshot, config = {}) {
4077
4162
  value: snapshot.value,
4078
4163
  tags: snapshot.tags,
4079
4164
  children: compactSnapshotRecord(configWithSnapshot.children),
4080
- timers: compactSnapshotRecord(configWithSnapshot.timers),
4165
+ timers: compactTimers(configWithSnapshot.timers),
4081
4166
  historyValue: compactSnapshotRecord(configWithSnapshot.historyValue),
4082
4167
  _stateInputs: compactSnapshotRecord(configWithSnapshot._stateInputs),
4083
4168
  _nextTimerId: configWithSnapshot._nextTimerId ?? 0,
@@ -4129,7 +4214,7 @@ function getPersistedSnapshot(snapshot, options) {
4129
4214
  ...jsonValues
4130
4215
  } = snapshot;
4131
4216
  const childrenJson = {};
4132
- const timersJson = {};
4217
+ const timersJson = [];
4133
4218
  const embedChildren = options?.embedChildren !== false;
4134
4219
  for (const id in children) {
4135
4220
  const child = children[id];
@@ -4172,8 +4257,7 @@ function getPersistedSnapshot(snapshot, options) {
4172
4257
  // pending delay instantly. Pure-transition snapshots have no local
4173
4258
  // schedule; durable executions record an accepted start separately.
4174
4259
  const scheduledTimers = snapshotActor?.system?._clock?.now ? undefined : snapshotActor?.system?._snapshot?._scheduledTimers;
4175
- for (const id in timers) {
4176
- const timer = timers[id];
4260
+ for (const timer of timers) {
4177
4261
  let event = timer.event;
4178
4262
  if (event.type === 'xstate.timeout.actor') {
4179
4263
  event = {
@@ -4184,6 +4268,11 @@ function getPersistedSnapshot(snapshot, options) {
4184
4268
  let target;
4185
4269
  if (timer.target === 'self') {
4186
4270
  target = 'self';
4271
+ } else if (isSerializedActorRef(timer.target)) {
4272
+ // An address-backed target resolves when the timer fires.
4273
+ target = {
4274
+ ...timer.target
4275
+ };
4187
4276
  } else {
4188
4277
  const childId = Object.entries(children).find(([, child]) => child === timer.target)?.[0];
4189
4278
  if (childId) {
@@ -4193,7 +4282,7 @@ function getPersistedSnapshot(snapshot, options) {
4193
4282
  type: 'parent'
4194
4283
  };
4195
4284
  } else {
4196
- throw new Error(`Unable to persist timer '${id}': target actor '${timer.target.id}' is no longer addressable from this snapshot.`);
4285
+ throw new Error(`Unable to persist timer ${timer.id !== undefined ? `'${timer.id}'` : `for event '${timer.event.type}'`}: target actor '${timer.target.id}' is no longer addressable from this snapshot.`);
4197
4286
  }
4198
4287
  }
4199
4288
  // A live runtime knows when the timer is due; persist the wall-clock
@@ -4203,18 +4292,23 @@ function getPersistedSnapshot(snapshot, options) {
4203
4292
  // (a restored-but-never-started actor, a pure-transition snapshot) the
4204
4293
  // timer's accepted durable start or carried-in start passes through,
4205
4294
  // so re-persisting cannot push the deadline back.
4206
- const scheduled = scheduledTimers?.[`${snapshotActor.sessionId}.${id}`];
4207
- const startedAt = scheduled ? scheduled.dueAt - timer.delay : getTimerStart(timer);
4208
- timersJson[id] = {
4209
- id: timer.id,
4295
+ const scheduled = scheduledTimers?.[getScheduledTimerKey(snapshotActor, getTimerKey(timer))];
4296
+ const scheduledAt = scheduled ? scheduled.dueAt - timer.delay : getTimerStart(timer);
4297
+ timersJson.push({
4298
+ ...(timer.id !== undefined && {
4299
+ id: timer.id
4300
+ }),
4301
+ ...(timer.seq !== undefined && {
4302
+ seq: timer.seq
4303
+ }),
4210
4304
  delay: timer.delay,
4211
4305
  type: timer.type,
4212
4306
  event,
4213
4307
  target,
4214
- ...(startedAt !== undefined && {
4215
- startedAt
4308
+ ...(scheduledAt !== undefined && {
4309
+ scheduledAt
4216
4310
  })
4217
- };
4311
+ });
4218
4312
  }
4219
4313
  const persisted = {
4220
4314
  ...jsonValues,
@@ -4231,7 +4325,6 @@ function getPersistedSnapshot(snapshot, options) {
4231
4325
  id: machine.id,
4232
4326
  version: machine.version
4233
4327
  };
4234
- persisted.version = machine.version;
4235
4328
  }
4236
4329
  return persisted;
4237
4330
  }
@@ -4247,9 +4340,9 @@ function persistContext(contextPart, getActorId, path = 'context', ancestors = [
4247
4340
  copy ??= Array.isArray(contextPart) ? contextPart.slice() : {
4248
4341
  ...contextPart
4249
4342
  };
4343
+ // The address lets refs to non-children still route after restore.
4250
4344
  copy[key] = {
4251
- xstate$type: ACTOR_REF_TYPE,
4252
- id: value.id
4345
+ $actor: value.address
4253
4346
  };
4254
4347
  } else {
4255
4348
  const valuePath = Array.isArray(contextPart) ? `${path}[${key}]` : `${path}.${key}`;
@@ -4293,13 +4386,15 @@ function matchesState(parentStateId, childStateId) {
4293
4386
  });
4294
4387
  }
4295
4388
 
4296
- /** @public */
4297
- function checkStateIn(snapshot, stateValue) {
4298
- if (typeof stateValue === 'string' && isStateId(stateValue)) {
4299
- const target = snapshot.machine.getStateNodeById(stateValue);
4300
- return snapshot.nodes.some(sn => sn === target);
4389
+ /**
4390
+ * @internal Throws when a user source name (action, guard, actor or delay)
4391
+ * enters the `xstate.` / `@xstate.` namespaces, which are reserved for
4392
+ * built-in events, effects and source keys.
4393
+ */
4394
+ function assertUnreservedSourceName(kind, name) {
4395
+ if (name.startsWith('xstate.') || name.startsWith('@xstate.')) {
4396
+ throw new Error(`Invalid ${kind} name '${name}': the 'xstate.' and '@xstate.' prefixes are reserved for built-in names.`);
4301
4397
  }
4302
- return snapshot.matches(stateValue);
4303
4398
  }
4304
4399
  function toStatePath(stateId) {
4305
4400
  if (isArray(stateId)) {
@@ -4339,7 +4434,7 @@ function toStateValue(stateValue) {
4339
4434
  return pathToStateValue(statePath);
4340
4435
  }
4341
4436
 
4342
- /** @public */
4437
+ /** @internal */
4343
4438
  function pathToStateValue(statePath) {
4344
4439
  if (statePath.length === 1) {
4345
4440
  return statePath[0];
@@ -4440,7 +4535,7 @@ function normalizeTarget(target) {
4440
4535
  return toArray(target);
4441
4536
  }
4442
4537
 
4443
- /** @public */
4538
+ /** @experimental Used by framework integrations; not part of the stable API. */
4444
4539
  function toObserver(nextHandler, errorHandler, completionHandler) {
4445
4540
  const isObserver = typeof nextHandler === 'object';
4446
4541
  const self = isObserver ? nextHandler : undefined;
@@ -4474,11 +4569,6 @@ function resolveReferencedActor(machine, src) {
4474
4569
  return typeof configSrc === 'string' ? machine.sources.actors[configSrc] : configSrc;
4475
4570
  }
4476
4571
 
4477
- /** @experimental */
4478
- function getAllOwnEventDescriptors(snapshot) {
4479
- return [...new Set([...snapshot.nodes.flatMap(sn => sn.ownEvents)])];
4480
- }
4481
-
4482
4572
  /**
4483
4573
  * Returns one event per transition of the active state nodes of `snapshot`,
4484
4574
  * including the internal events for invoked actors (`xstate.done.actor`,
@@ -4641,6 +4731,23 @@ async function runStep(actor, key, exec, sendSelf = event => void actor.system.s
4641
4731
  * @experimental
4642
4732
  */
4643
4733
  function deliverEvent(source, target, event) {
4734
+ if (isSerializedActorRef(target)) {
4735
+ const serialized = target;
4736
+ const system = source?.system;
4737
+ const live = system && resolveSerializedActorRef(system, serialized);
4738
+ if (!live) {
4739
+ const error = createMissingAddressError(serialized);
4740
+ if (!system) {
4741
+ throw error;
4742
+ }
4743
+ void system.deadLetter(source, undefined, event, 'missingTarget', {
4744
+ targetId: getAddressId(serialized.$actor),
4745
+ error
4746
+ });
4747
+ return;
4748
+ }
4749
+ target = live;
4750
+ }
4644
4751
  if (rejectUndeliverableEvent(source, target, event)) {
4645
4752
  return;
4646
4753
  }
@@ -4701,14 +4808,14 @@ function stopActor(actor) {
4701
4808
  actor._stop();
4702
4809
  }
4703
4810
 
4704
- let systemIdPrefix;
4705
- let nextSystemId = 0;
4811
+ let executionIdPrefix;
4812
+ let nextExecutionId = 0;
4706
4813
 
4707
4814
  /** @internal */
4708
4815
  const transitionEffectSignal = new Error('Transition effect');
4709
4816
  /** @internal */
4710
4817
  const transitionEffectTargets = [];
4711
- function createSystemIdPrefix() {
4818
+ function createExecutionIdPrefix() {
4712
4819
  let crypto;
4713
4820
  try {
4714
4821
  crypto = globalThis.crypto;
@@ -4733,9 +4840,9 @@ function createSystemIdPrefix() {
4733
4840
  }
4734
4841
  return `xstate-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;
4735
4842
  }
4736
- function createSystemId() {
4737
- systemIdPrefix ??= createSystemIdPrefix();
4738
- return `${systemIdPrefix}:${(nextSystemId++).toString(36)}`;
4843
+ function createExecutionId() {
4844
+ executionIdPrefix ??= createExecutionIdPrefix();
4845
+ return `${executionIdPrefix}:${(nextExecutionId++).toString(36)}`;
4739
4846
  }
4740
4847
 
4741
4848
  /**
@@ -4866,7 +4973,7 @@ function resolveActorId(system, requestedId, options) {
4866
4973
 
4867
4974
  /** @internal */
4868
4975
  function bookSessionId(system) {
4869
- return `${system._identity.systemId}:${system._identity.nextSessionId++}`;
4976
+ return `${system._identity.executionId}:${system._identity.nextSessionId++}`;
4870
4977
  }
4871
4978
 
4872
4979
  /**
@@ -4911,8 +5018,11 @@ const RUNTIME_OPERATIONS = ['spawnActor', 'startActor', 'stopActor', 'terminateA
4911
5018
  // batch.
4912
5019
  ];
4913
5020
  const emptyScheduledTimers = Object.freeze({});
4914
- function createScheduledTimerId(actor, id) {
4915
- return `${actor.sessionId}.${id}`;
5021
+ function createScheduledTimerId(actor, key) {
5022
+ return getScheduledTimerKey(actor, key);
5023
+ }
5024
+ function findLogicalTimer(source, key) {
5025
+ return source.getSnapshot()?.timers?.find(timer => matchesTimerKey(timer, key));
4916
5026
  }
4917
5027
 
4918
5028
  /** @public */
@@ -4959,7 +5069,7 @@ class RuntimeSystem {
4959
5069
  constructor(_rootActor, options) {
4960
5070
  this._rootActor = _rootActor;
4961
5071
  this._identity = ambientExecutionIdentity ?? {
4962
- systemId: createSystemId(),
5072
+ executionId: createExecutionId(),
4963
5073
  nextSessionId: 0
4964
5074
  };
4965
5075
  this._snapshot = void 0;
@@ -5002,25 +5112,24 @@ class RuntimeSystem {
5002
5112
  id
5003
5113
  });
5004
5114
  }
5005
- schedule(source, id, delay) {
5006
- const existingId = createScheduledTimerId(source, id);
5007
- if (this._timerMap?.[existingId] !== undefined) {
5008
- this.cancel(source, id);
5115
+ schedule(source, key, delay) {
5116
+ const scheduledTimerId = createScheduledTimerId(source, key);
5117
+ if (this._timerMap?.[scheduledTimerId] !== undefined) {
5118
+ this.cancel(source, key);
5009
5119
  }
5010
- const timer = source.getSnapshot()?.timers?.[id];
5120
+ const timer = findLogicalTimer(source, key);
5011
5121
  if (timer) {
5012
5122
  const target = timer.target === 'self' ? source : timer.target;
5013
- this._recordSent(source, target, timer.event, delay, id);
5123
+ this._recordSent(source, target, timer.event, delay, timer.id);
5014
5124
  }
5015
5125
  const scheduledAt = this._clock.now?.() ?? Date.now();
5016
5126
  const scheduledTimer = {
5017
5127
  source,
5018
5128
  delay,
5019
- id,
5129
+ key,
5020
5130
  scheduledAt,
5021
5131
  dueAt: scheduledAt + delay
5022
5132
  };
5023
- const scheduledTimerId = createScheduledTimerId(source, id);
5024
5133
  if (this._snapshot._scheduledTimers === emptyScheduledTimers) {
5025
5134
  this._snapshot._scheduledTimers = {};
5026
5135
  }
@@ -5034,13 +5143,13 @@ class RuntimeSystem {
5034
5143
  markSystemSnapshotDirty(this);
5035
5144
  this._deliver(source, source, {
5036
5145
  type: XSTATE_TIMER,
5037
- id
5146
+ ...key
5038
5147
  });
5039
5148
  }, delay);
5040
5149
  (this._timerMap ??= {})[scheduledTimerId] = timeout;
5041
5150
  }
5042
- cancel(source, id) {
5043
- const scheduledTimerId = createScheduledTimerId(source, id);
5151
+ cancel(source, key) {
5152
+ const scheduledTimerId = createScheduledTimerId(source, key);
5044
5153
  const timeout = this._timerMap?.[scheduledTimerId];
5045
5154
  if (this._timerMap) {
5046
5155
  delete this._timerMap[scheduledTimerId];
@@ -5057,7 +5166,7 @@ class RuntimeSystem {
5057
5166
  for (const scheduledTimerId in this._snapshot._scheduledTimers) {
5058
5167
  const scheduledTimer = this._snapshot._scheduledTimers[scheduledTimerId];
5059
5168
  if (scheduledTimer.source === actor) {
5060
- this.cancel(actor, scheduledTimer.id);
5169
+ this.cancel(actor, scheduledTimer.key);
5061
5170
  }
5062
5171
  }
5063
5172
  }
@@ -5076,6 +5185,18 @@ class RuntimeSystem {
5076
5185
  markSystemSnapshotDirty(this);
5077
5186
  return sessionId;
5078
5187
  }
5188
+ _getByAddress(address) {
5189
+ const root = this._getRootActor();
5190
+ if (root?.address === address) {
5191
+ return root;
5192
+ }
5193
+ for (const actor of this._children?.values() ?? []) {
5194
+ if (actor.address === address && actor._isRunning()) {
5195
+ return actor;
5196
+ }
5197
+ }
5198
+ return undefined;
5199
+ }
5079
5200
  _unregister(actor) {
5080
5201
  let changed;
5081
5202
  // Remote handles have no sessionId and are never in the session map;
@@ -5176,6 +5297,23 @@ class RuntimeSystem {
5176
5297
  terminateActor(actor, termination);
5177
5298
  }
5178
5299
  sendEvent(source, target, event) {
5300
+ if (isSerializedActorRef(target)) {
5301
+ // A ref that went through JSON resolves by address to the live actor.
5302
+ // A host runtime may own actors this system cannot see, so an
5303
+ // unresolved address is its to route; locally it is a dead letter.
5304
+ const live = resolveSerializedActorRef(this, target);
5305
+ if (live) {
5306
+ target = live;
5307
+ } else if (
5308
+ // A live actor of another incarnation is stale locally; an
5309
+ // address this system cannot see may belong to a host runtime.
5310
+ this._getByAddress(target.$actor) || !this.runtime?.sendEvent) {
5311
+ return this.deadLetter(source, undefined, event, 'missingTarget', {
5312
+ targetId: getAddressId(target.$actor),
5313
+ error: createMissingAddressError(target)
5314
+ });
5315
+ }
5316
+ }
5179
5317
  if (rejectUndeliverableEvent(source, target, event)) {
5180
5318
  return;
5181
5319
  }
@@ -5237,26 +5375,26 @@ class RuntimeSystem {
5237
5375
  }
5238
5376
  return exec();
5239
5377
  }
5240
- scheduleTimer(source, id, delay) {
5378
+ scheduleTimer(source, key, delay) {
5241
5379
  const override = this.runtime?.scheduleTimer;
5242
5380
  if (override) {
5243
5381
  // The local scheduler records delayed sends for inspection inside
5244
5382
  // `schedule`; keep that parity for host runtimes.
5245
- const timer = source.getSnapshot()?.timers?.[id];
5383
+ const timer = findLogicalTimer(source, key);
5246
5384
  if (timer) {
5247
5385
  const target = timer.target === 'self' ? source : timer.target;
5248
- this._recordSent(source, target, timer.event, delay, id);
5386
+ this._recordSent(source, target, timer.event, delay, timer.id);
5249
5387
  }
5250
- return override(source, id, delay);
5388
+ return override(source, key, delay);
5251
5389
  }
5252
- this.schedule(source, id, delay);
5390
+ this.schedule(source, key, delay);
5253
5391
  }
5254
- cancelTimer(source, id) {
5392
+ cancelTimer(source, key) {
5255
5393
  const override = this.runtime?.cancelTimer;
5256
5394
  if (override) {
5257
- return override(source, id);
5395
+ return override(source, key);
5258
5396
  }
5259
- this.cancel(source, id);
5397
+ this.cancel(source, key);
5260
5398
  }
5261
5399
  cancelAllTimers(source) {
5262
5400
  const override = this.runtime?.cancelAllTimers;
@@ -5291,9 +5429,9 @@ class RuntimeSystem {
5291
5429
  const {
5292
5430
  source,
5293
5431
  dueAt,
5294
- id
5432
+ key
5295
5433
  } = scheduledTimers[scheduledId];
5296
- this.scheduleTimer(source, id, Math.max(0, dueAt - (this._clock.now?.() ?? Date.now())));
5434
+ this.scheduleTimer(source, key, Math.max(0, dueAt - (this._clock.now?.() ?? Date.now())));
5297
5435
  }
5298
5436
  }
5299
5437
  }
@@ -5309,12 +5447,6 @@ function createRuntimeSystem(rootActor, options) {
5309
5447
  // oxlint-enable no-unused-vars
5310
5448
 
5311
5449
  let executingCustomAction = false;
5312
-
5313
- /**
5314
- * Marks a serialized object as an actor reference (`xstate$type` in JSON
5315
- * output and persisted context).
5316
- */
5317
- const ACTOR_REF_TYPE = 'actorRef';
5318
5450
  const emptyInspectionRecords = Object.freeze([]);
5319
5451
 
5320
5452
  // those values are currently used by @xstate/react directly so it's important to keep the assigned values in sync
@@ -5984,21 +6116,21 @@ class Actor {
5984
6116
  this.update(this._snapshot, createInitEvent(this.options.input));
5985
6117
  }
5986
6118
  if (this._restored) {
5987
- const timers = this._snapshot.timers ?? {};
5988
- // startedAt is only persisted from — and only meaningful under — the
6119
+ const timers = this._snapshot.timers ?? [];
6120
+ // scheduledAt is only persisted from — and only meaningful under — the
5989
6121
  // wall clock; a custom clock (a simulated clock, a monotonic counter)
5990
6122
  // restores every timer with its declared delay. The clamp bounds
5991
6123
  // remaining time by the declared delay in case the wall clock moved
5992
6124
  // backwards between persist and restore.
5993
6125
  const wallClock = !this.system._clock.now;
5994
6126
  const now = Date.now();
5995
- for (const timer of Object.values(timers)) {
6127
+ for (const timer of timers) {
5996
6128
  // A timer persisted from a live runtime carries its wall-clock start;
5997
6129
  // honor the absolute deadline instead of restarting the full delay.
5998
6130
  // Without a start (a pure-transition snapshot, or an older snapshot)
5999
6131
  // the declared delay is all there is.
6000
- const delay = wallClock && timer.startedAt !== undefined ? Math.min(timer.delay, Math.max(0, timer.startedAt + timer.delay - now)) : timer.delay;
6001
- this.system.scheduleTimer(this, timer.id, delay);
6132
+ const delay = wallClock && timer.scheduledAt !== undefined ? Math.min(timer.delay, Math.max(0, timer.scheduledAt + timer.delay - now)) : timer.delay;
6133
+ this.system.scheduleTimer(this, getTimerKey(timer), delay);
6002
6134
  }
6003
6135
  this._restored = false;
6004
6136
  }
@@ -6239,15 +6371,12 @@ class Actor {
6239
6371
  }
6240
6372
 
6241
6373
  /**
6242
- * Returns the actor's serializable logical identity: its `id`, `address`,
6243
- * and registered source key (when the actor was created from one).
6374
+ * Returns the actor's serializable logical identity: `{ $actor: address }`.
6375
+ * The result can be used as an `enq.sendTo(...)` target.
6244
6376
  */
6245
6377
  toJSON() {
6246
6378
  return {
6247
- xstate$type: ACTOR_REF_TYPE,
6248
- id: this.id,
6249
- address: this.address,
6250
- src: typeof this.src === 'string' ? this.src : undefined
6379
+ $actor: this.address
6251
6380
  };
6252
6381
  }
6253
6382
 
@@ -6349,7 +6478,7 @@ class Actor {
6349
6478
  * @param logic - The actor logic to create an actor from. For a state machine
6350
6479
  * actor logic creator, see {@link createMachine}. Other actor logic creators
6351
6480
  * include {@link createCallbackLogic}, {@link createEventObservableLogic},
6352
- * {@link createObservableLogic}, {@link createLogic}, and
6481
+ * {@link createObservableLogic}, {@link createStepLogic}, and
6353
6482
  * {@link createAsyncLogic}.
6354
6483
  * @param options - Actor options
6355
6484
  * @public
@@ -6358,7 +6487,6 @@ function createActor(logic, ...[options]) {
6358
6487
  return new Actor(logic, options);
6359
6488
  }
6360
6489
 
6361
- exports.ACTOR_REF_TYPE = ACTOR_REF_TYPE;
6362
6490
  exports.Actor = Actor;
6363
6491
  exports.InfiniteTransitionError = InfiniteTransitionError;
6364
6492
  exports.NULL_EVENT = NULL_EVENT;
@@ -6370,12 +6498,13 @@ exports.XSTATE_LOGIC_EFFECT_REJECT = XSTATE_LOGIC_EFFECT_REJECT;
6370
6498
  exports.XSTATE_LOGIC_EFFECT_RESOLVE = XSTATE_LOGIC_EFFECT_RESOLVE;
6371
6499
  exports.XSTATE_LOGIC_EFFECT_START = XSTATE_LOGIC_EFFECT_START;
6372
6500
  exports.XSTATE_STOP = XSTATE_STOP;
6501
+ exports.XSTATE_STOP_EFFECT = XSTATE_STOP_EFFECT;
6373
6502
  exports.XSTATE_TIMER = XSTATE_TIMER;
6374
6503
  exports.allocateChildId = allocateChildId;
6375
6504
  exports.assertChildIdFree = assertChildIdFree;
6505
+ exports.assertUnreservedSourceName = assertUnreservedSourceName;
6376
6506
  exports.attachSnapshotActorRef = attachSnapshotActorRef;
6377
6507
  exports.beginSpawnAllocation = beginSpawnAllocation;
6378
- exports.checkStateIn = checkStateIn;
6379
6508
  exports.cloneMachineSnapshot = cloneMachineSnapshot;
6380
6509
  exports.createActor = createActor;
6381
6510
  exports.createCustomEffect = createCustomEffect;
@@ -6388,7 +6517,6 @@ exports.createInertActorScope = createInertActorScope;
6388
6517
  exports.createInitEvent = createInitEvent;
6389
6518
  exports.createInvokeId = createInvokeId;
6390
6519
  exports.createInvokeTimeoutEvent = createInvokeTimeoutEvent;
6391
- exports.createInvokeTimeoutEventId = createInvokeTimeoutEventId;
6392
6520
  exports.createListenerLogic = createListenerLogic;
6393
6521
  exports.createMachineSnapshot = createMachineSnapshot;
6394
6522
  exports.createRemoteActorRef = createRemoteActorRef;
@@ -6405,18 +6533,17 @@ exports.finalizeTransitionResult = finalizeTransitionResult;
6405
6533
  exports.formatRouteTransitions = formatRouteTransitions;
6406
6534
  exports.formatTransition = formatTransition;
6407
6535
  exports.getActorIdPrefix = getActorIdPrefix;
6408
- exports.getAllOwnEventDescriptors = getAllOwnEventDescriptors;
6409
6536
  exports.getAllOwnEvents = getAllOwnEvents;
6410
6537
  exports.getAllStateNodes = getAllStateNodes;
6411
6538
  exports.getCandidates = getCandidates;
6412
6539
  exports.getDelayedTransitions = getDelayedTransitions;
6413
- exports.getEventDescriptorKey = getEventDescriptorKey;
6414
6540
  exports.getPersistedSnapshot = getPersistedSnapshot;
6415
6541
  exports.getProperAncestors = getProperAncestors;
6416
6542
  exports.getRootActorId = getRootActorId;
6417
6543
  exports.getSnapshotActorRef = getSnapshotActorRef;
6418
6544
  exports.getStateNodeByPath = getStateNodeByPath;
6419
6545
  exports.getStateNodes = getStateNodes;
6546
+ exports.getTimerKey = getTimerKey;
6420
6547
  exports.getTimerStart = getTimerStart;
6421
6548
  exports.getTransitionResult = getTransitionResult;
6422
6549
  exports.hasAmbientInspector = hasAmbientInspector;
@@ -6424,11 +6551,12 @@ exports.hasEffect = hasEffect;
6424
6551
  exports.initialMicrostep = initialMicrostep;
6425
6552
  exports.isActorRefLike = isActorRefLike;
6426
6553
  exports.isAtomicStateNode = isAtomicStateNode;
6427
- exports.isBuiltInExecutableAction = isBuiltInExecutableAction;
6554
+ exports.isBuiltInExecutableEffect = isBuiltInExecutableEffect;
6428
6555
  exports.isInFinalState = isInFinalState;
6429
6556
  exports.isInertActorScope = isInertActorScope;
6430
6557
  exports.isMachineSnapshot = isMachineSnapshot;
6431
6558
  exports.isRemoteActorRef = isRemoteActorRef;
6559
+ exports.isSerializedActorRef = isSerializedActorRef;
6432
6560
  exports.isStateId = isStateId;
6433
6561
  exports.listenerLogic = listenerLogic;
6434
6562
  exports.macrostep = macrostep;
@@ -6437,10 +6565,11 @@ exports.matchesActorSession = matchesActorSession;
6437
6565
  exports.matchesEvent = matchesEvent;
6438
6566
  exports.matchesEventDescriptor = matchesEventDescriptor;
6439
6567
  exports.matchesState = matchesState;
6568
+ exports.matchesTimerKey = matchesTimerKey;
6440
6569
  exports.mergeActorIdCounters = mergeActorIdCounters;
6441
6570
  exports.parseDelayToMilliseconds = parseDelayToMilliseconds;
6442
6571
  exports.parseGeneratedActorId = parseGeneratedActorId;
6443
- exports.pathToStateValue = pathToStateValue;
6572
+ exports.readTimerKey = readTimerKey;
6444
6573
  exports.recordTimerStart = recordTimerStart;
6445
6574
  exports.reserveChildId = reserveChildId;
6446
6575
  exports.resolveActionsWithContext = resolveActionsWithContext;
@@ -6448,6 +6577,7 @@ exports.resolveReferencedActor = resolveReferencedActor;
6448
6577
  exports.resolveRegisteredActorSource = resolveRegisteredActorSource;
6449
6578
  exports.resolveStateValue = resolveStateValue;
6450
6579
  exports.runStep = runStep;
6580
+ exports.serializeTimerKey = serializeTimerKey;
6451
6581
  exports.setInertActorScopeSnapshot = setInertActorScopeSnapshot;
6452
6582
  exports.setSnapshotActorRef = setSnapshotActorRef;
6453
6583
  exports.stopActor = stopActor;