xstate 6.0.0-alpha.4 → 6.0.0-alpha.41

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 (100) hide show
  1. package/README.md +19 -17
  2. package/bin/xstate.js +36 -0
  3. package/dist/StateMachine-8e73d782.cjs.js +1200 -0
  4. package/dist/StateMachine-db4e6d4b.development.cjs.js +1232 -0
  5. package/dist/StateMachine-ee89d49f.esm.js +1197 -0
  6. package/dist/StateMachine-f60abe05.development.esm.js +1229 -0
  7. package/dist/createActor-20615484.development.cjs.js +5717 -0
  8. package/dist/createActor-a3f7750f.esm.js +5578 -0
  9. package/dist/createActor-c97c04c9.development.esm.js +5620 -0
  10. package/dist/createActor-f3afd774.cjs.js +5675 -0
  11. package/dist/declarations/src/State.d.ts +17 -4
  12. package/dist/declarations/src/StateMachine.d.ts +37 -16
  13. package/dist/declarations/src/StateNode.d.ts +5 -2
  14. package/dist/declarations/src/actions.d.ts +10 -7
  15. package/dist/declarations/src/actors/callback.d.ts +2 -0
  16. package/dist/declarations/src/actors/logic.d.ts +7 -24
  17. package/dist/declarations/src/actors/observable.d.ts +3 -0
  18. package/dist/declarations/src/actors/promise.d.ts +6 -2
  19. package/dist/declarations/src/createActor.d.ts +64 -20
  20. package/dist/declarations/src/createMachine.d.ts +21 -13
  21. package/dist/declarations/src/createMachineFromConfig.d.ts +64 -30
  22. package/dist/declarations/src/durable/index.d.ts +133 -0
  23. package/dist/declarations/src/effectDescriptor.d.ts +81 -0
  24. package/dist/declarations/src/fsm.d.ts +77 -0
  25. package/dist/declarations/src/index.d.ts +15 -8
  26. package/dist/declarations/src/inspection.d.ts +11 -1
  27. package/dist/declarations/src/machineVersion.types.d.ts +38 -0
  28. package/dist/declarations/src/machineVersions.d.ts +100 -0
  29. package/dist/declarations/src/runtimeHelpers.d.ts +35 -0
  30. package/dist/declarations/src/schema.types.d.ts +5 -0
  31. package/dist/declarations/src/serialize.d.ts +9 -22
  32. package/dist/declarations/src/setup.d.ts +317 -64
  33. package/dist/declarations/src/spawn.d.ts +5 -5
  34. package/dist/declarations/src/stateUtils.d.ts +19 -7
  35. package/dist/declarations/src/system.d.ts +74 -11
  36. package/dist/declarations/src/transitionActions.d.ts +14 -2
  37. package/dist/declarations/src/types.d.ts +318 -134
  38. package/dist/declarations/src/types.v6.d.ts +306 -52
  39. package/dist/declarations/src/utils.d.ts +5 -3
  40. package/dist/declarations/src/validation/index.d.ts +37 -0
  41. package/dist/declarations/src/validation.types.d.ts +22 -0
  42. package/dist/effectDescriptor-57ae11fa.esm.js +250 -0
  43. package/dist/effectDescriptor-b7c48ceb.development.esm.js +250 -0
  44. package/dist/effectDescriptor-ba9e14f0.development.cjs.js +257 -0
  45. package/dist/effectDescriptor-e2bb61e2.cjs.js +257 -0
  46. package/dist/index-7fd92683.cjs.js +941 -0
  47. package/dist/index-a8ce72f1.esm.js +932 -0
  48. package/dist/index-b5b1b2bc.development.esm.js +932 -0
  49. package/dist/index-d42efc07.development.cjs.js +941 -0
  50. package/dist/xstate-actors.cjs.js +6 -5
  51. package/dist/xstate-actors.development.cjs.js +6 -5
  52. package/dist/xstate-actors.development.esm.js +2 -1
  53. package/dist/xstate-actors.esm.js +2 -1
  54. package/dist/xstate-actors.umd.min.js +1 -1
  55. package/dist/xstate-actors.umd.min.js.map +1 -1
  56. package/dist/xstate-durable.cjs.d.mts +2 -0
  57. package/dist/xstate-durable.cjs.d.ts +2 -0
  58. package/dist/xstate-durable.cjs.js +327 -0
  59. package/dist/xstate-durable.cjs.mjs +5 -0
  60. package/dist/xstate-durable.development.cjs.js +327 -0
  61. package/dist/xstate-durable.development.cjs.mjs +5 -0
  62. package/dist/xstate-durable.development.esm.js +321 -0
  63. package/dist/xstate-durable.esm.js +321 -0
  64. package/dist/xstate-durable.umd.min.js +2 -0
  65. package/dist/xstate-durable.umd.min.js.map +1 -0
  66. package/dist/xstate-graph.cjs.js +16 -19
  67. package/dist/xstate-graph.development.cjs.js +16 -19
  68. package/dist/xstate-graph.development.esm.js +13 -16
  69. package/dist/xstate-graph.esm.js +13 -16
  70. package/dist/xstate-graph.umd.min.js +1 -1
  71. package/dist/xstate-graph.umd.min.js.map +1 -1
  72. package/dist/xstate-validation.cjs.d.mts +2 -0
  73. package/dist/xstate-validation.cjs.d.ts +2 -0
  74. package/dist/xstate-validation.cjs.js +277 -0
  75. package/dist/xstate-validation.cjs.mjs +5 -0
  76. package/dist/xstate-validation.development.cjs.js +277 -0
  77. package/dist/xstate-validation.development.cjs.mjs +5 -0
  78. package/dist/xstate-validation.development.esm.js +271 -0
  79. package/dist/xstate-validation.esm.js +271 -0
  80. package/dist/xstate-validation.umd.min.js +2 -0
  81. package/dist/xstate-validation.umd.min.js.map +1 -0
  82. package/dist/xstate.cjs.js +1361 -412
  83. package/dist/xstate.cjs.mjs +9 -0
  84. package/dist/xstate.development.cjs.js +1361 -412
  85. package/dist/xstate.development.cjs.mjs +9 -0
  86. package/dist/xstate.development.esm.js +1332 -392
  87. package/dist/xstate.esm.js +1332 -392
  88. package/dist/xstate.umd.min.js +1 -1
  89. package/dist/xstate.umd.min.js.map +1 -1
  90. package/durable/package.json +8 -0
  91. package/package.json +39 -3
  92. package/validation/package.json +8 -0
  93. package/dist/StateMachine-445a8480.cjs.js +0 -732
  94. package/dist/StateMachine-4deb4090.development.esm.js +0 -746
  95. package/dist/StateMachine-f310bc72.esm.js +0 -729
  96. package/dist/StateMachine-f83f01f9.development.cjs.js +0 -749
  97. package/dist/index-918ab496.cjs.js +0 -4397
  98. package/dist/index-9cce3480.esm.js +0 -4342
  99. package/dist/index-ccbe7c0b.development.esm.js +0 -4381
  100. package/dist/index-ebaf6fd8.development.cjs.js +0 -4436
@@ -0,0 +1,1232 @@
1
+ 'use strict';
2
+
3
+ var createActor = require('./createActor-20615484.development.cjs.js');
4
+ var dist_xstateActors = require('./index-d42efc07.development.cjs.js');
5
+
6
+ function createSpawner(actorScope, actors, spawnedChildren) {
7
+ return (src, options) => {
8
+ const referencedSrc = Object.entries(actors).find(([, logic]) => logic === src)?.[0];
9
+ // Generated ids come from the same transaction allocator as `enq.spawn`,
10
+ // so context-factory allocations persist with the snapshot and never
11
+ // collide with later spawns.
12
+ const id = options?.id ?? createActor.allocateChildId(actorScope, referencedSrc ?? src).id;
13
+ if (options?.id !== undefined) {
14
+ createActor.assertChildIdFree(actorScope, options.id);
15
+ createActor.reserveChildId(actorScope, options.id);
16
+ }
17
+ const actor = actorScope.system.createActorRef(src, {
18
+ id,
19
+ parent: actorScope.self,
20
+ syncSnapshot: options?.syncSnapshot,
21
+ input: options?.input,
22
+ src: referencedSrc ?? src,
23
+ registryKey: options?.registryKey
24
+ });
25
+ spawnedChildren[actor.id] = actor;
26
+ return actor;
27
+ };
28
+ }
29
+
30
+ const cache = new WeakMap();
31
+ function memo(object, key, fn) {
32
+ let memoizedData = cache.get(object);
33
+ if (!memoizedData) {
34
+ memoizedData = {
35
+ [key]: fn()
36
+ };
37
+ cache.set(object, memoizedData);
38
+ } else if (!(key in memoizedData)) {
39
+ memoizedData[key] = fn();
40
+ }
41
+ return memoizedData[key];
42
+ }
43
+
44
+ const EMPTY_OBJECT = {};
45
+ const CHOICE_CONFIG_KEYS = ['invoke', 'after', 'on', 'entry', 'exit', 'always', 'states', 'initial', 'onDone', 'timeout', 'onTimeout', 'history', 'target', 'output'];
46
+ class StateNode {
47
+ constructor(/** The raw config used to create the machine. */
48
+ config, options) {
49
+ this.config = config;
50
+ /**
51
+ * The relative key of the state node, which represents its location in the
52
+ * overall state value.
53
+ */
54
+ this.key = void 0;
55
+ /** The unique ID of the state node. */
56
+ this.id = void 0;
57
+ /**
58
+ * The type of this state node:
59
+ *
60
+ * - `'atomic'` - no child state nodes
61
+ * - `'compound'` - nested child state nodes (XOR)
62
+ * - `'parallel'` - orthogonal nested child state nodes (AND)
63
+ * - `'history'` - history state node
64
+ * - `'choice'` - pure routing decision state node
65
+ * - `'final'` - final state node
66
+ */
67
+ this.type = void 0;
68
+ /** The string path from the root machine node to this node. */
69
+ this.path = void 0;
70
+ /** The child state nodes. */
71
+ this.states = void 0;
72
+ /**
73
+ * The type of history on this state node. Can be:
74
+ *
75
+ * - `'shallow'` - recalls only top-level historical state value
76
+ * - `'deep'` - recalls historical state value at all levels
77
+ */
78
+ this.history = void 0;
79
+ /** The action(s) to be executed upon entering the state node. */
80
+ this.entry = void 0;
81
+ /** The action(s) to be executed upon exiting the state node. */
82
+ this.exit = void 0;
83
+ /** The parent state node. */
84
+ this.parent = void 0;
85
+ /** The root machine node. */
86
+ this.machine = void 0;
87
+ /**
88
+ * The meta data associated with this state node, which will be returned in
89
+ * State instances.
90
+ */
91
+ this.meta = void 0;
92
+ /**
93
+ * The output data sent with the `xstate.done.state` event if this is a final
94
+ * state node.
95
+ */
96
+ this.output = void 0;
97
+ /**
98
+ * The order this state node appears. Corresponds to the implicit document
99
+ * order.
100
+ */
101
+ this.order = -1;
102
+ this.description = void 0;
103
+ this.schemas = void 0;
104
+ this.tags = [];
105
+ this.transitions = void 0;
106
+ this.always = void 0;
107
+ this.invoke = void 0;
108
+ this.on = void 0;
109
+ this.after = void 0;
110
+ this.events = void 0;
111
+ this.ownEvents = void 0;
112
+ this._candidateCache = void 0;
113
+ this.parent = options._parent;
114
+ this.key = options._key;
115
+ this.machine = options._machine;
116
+ this.path = this.parent ? this.parent.path.concat(this.key) : [];
117
+ const firstStateKey = this.config.states ? Object.keys(this.config.states)[0] : undefined;
118
+ this.id = this.config.id || [this.machine.id, ...this.path].join(createActor.STATE_DELIMITER);
119
+ this.type = this.config.type || (firstStateKey !== undefined ? 'compound' : this.config.history ? 'history' : 'atomic');
120
+ this.description = this.config.description;
121
+ this.schemas = this.config.schemas;
122
+ validateStateNodeConfig(this);
123
+ this.order = this.machine.idMap.size;
124
+ this.machine.idMap.set(this.id, this);
125
+ this.states = this.config.states ? createActor.mapValues(this.config.states, (stateConfig, key) => {
126
+ const stateNode = new StateNode(stateConfig, {
127
+ _parent: this,
128
+ _key: key,
129
+ _machine: this.machine
130
+ });
131
+ return stateNode;
132
+ }) : EMPTY_OBJECT;
133
+ if (this.type === 'compound' && !this.config.initial) {
134
+ throw new Error(`No initial state specified for compound state node "#${this.id}". Try adding { initial: "${firstStateKey}" } to the state config.` );
135
+ }
136
+
137
+ // History config
138
+ this.history = this.config.history === true ? 'shallow' : this.config.history || false;
139
+ this.entry = this.config.entry;
140
+ this.exit = this.config.exit;
141
+ if (this.entry) {
142
+ // @ts-expect-error _special is an internal marker not on the Action type
143
+ this.entry._special = true;
144
+ }
145
+ if (this.exit) {
146
+ // @ts-expect-error _special is an internal marker not on the Action type
147
+ this.exit._special = true;
148
+ }
149
+ this.meta = this.config.meta;
150
+ this.output = this.type === 'final' || !this.parent ? this.config.output : undefined;
151
+ this.tags = createActor.toArray(config.tags).slice();
152
+ this.invoke = createActor.toArray(this.config.invoke).map((invokeConfig, i) => {
153
+ const {
154
+ src,
155
+ registryKey
156
+ } = invokeConfig;
157
+ const invokeId = createActor.createInvokeId(this.id, i);
158
+ const resolvedId = invokeConfig.id ?? invokeId;
159
+ // Referenced (string) actors keep their logical name so persisted
160
+ // snapshots reference `src: 'fetchUser'` rather than a positional id;
161
+ // only inline logic gets the synthetic source name.
162
+ const sourceName = typeof src === 'string' ? src : `xstate.invoke.${invokeId}`;
163
+ return {
164
+ ...invokeConfig,
165
+ src: sourceName,
166
+ logic: src,
167
+ id: resolvedId,
168
+ registryKey
169
+ };
170
+ });
171
+ }
172
+
173
+ /** @internal */
174
+ _initialize() {
175
+ this.after = createActor.getDelayedTransitions(this);
176
+ this.transitions = formatTransitions(this);
177
+ if (this.type === 'choice') {
178
+ this.always = formatChoiceTransitions(this);
179
+ } else if (this.config.always) {
180
+ this.always = mapTransitionConfigs(this.config.always, transition => createActor.formatTransition(this, createActor.NULL_EVENT, transition));
181
+ }
182
+ for (const key of Object.keys(this.states)) {
183
+ this.states[key]._initialize();
184
+ }
185
+ this._refreshEventMetadata();
186
+ }
187
+
188
+ /** @internal */
189
+ _refreshEventMetadata() {
190
+ const on = {};
191
+ const ownEvents = [];
192
+ for (const [descriptor, transitions] of this.transitions) {
193
+ on[descriptor] = transitions.slice();
194
+ if (transitions.some(transition => transition.target || transition.reenter || transition.to)) {
195
+ ownEvents.push(descriptor);
196
+ }
197
+ }
198
+ this.on = on;
199
+ this.ownEvents = ownEvents;
200
+ const events = new Set(ownEvents);
201
+ for (const state of Object.values(this.states)) {
202
+ for (const event of state.events) {
203
+ events.add(event);
204
+ }
205
+ }
206
+ this.events = Array.from(events);
207
+ }
208
+ get initial() {
209
+ return memo(this, 'initial', () => formatInitialTransition(this, this.config.initial));
210
+ }
211
+
212
+ /** @internal */
213
+ next(snapshot, event, actorScope, selectionResults) {
214
+ const descriptorKey = createActor.getEventDescriptorKey(event);
215
+ let candidates = this._candidateCache?.get(descriptorKey);
216
+ if (!candidates) {
217
+ candidates = createActor.getCandidates(this, event);
218
+ (this._candidateCache ??= new Map()).set(descriptorKey, candidates);
219
+ }
220
+ for (const candidate of candidates) {
221
+ const guardPassed = createActor.evaluateCandidate(candidate, event, snapshot, this, actorScope, selectionResults);
222
+ if (guardPassed) {
223
+ return [candidate];
224
+ }
225
+ }
226
+ return undefined;
227
+ }
228
+ }
229
+ function validateStateNodeConfig(stateNode) {
230
+ const config = stateNode.config;
231
+ if (stateNode.type === 'history' && !(typeof config.target === 'string' && config.target.trim().length > 0 || Array.isArray(config.target) && config.target.length > 0 && config.target.every(target => typeof target === 'string' && target.trim().length > 0))) {
232
+ throw new Error(`History state "${stateNode.id}" must declare a non-empty \`target\`.` );
233
+ }
234
+ if (stateNode.type !== 'choice') {
235
+ if (config.choice !== undefined) {
236
+ throw new Error(`State "${stateNode.id}" has \`choice\`, but \`choice\` can only be used with \`type: 'choice'\`.`);
237
+ }
238
+ return;
239
+ }
240
+ if (typeof config.choice !== 'function') {
241
+ throw new Error(`Choice state "${stateNode.id}" must declare a \`choice\` function.` );
242
+ }
243
+ {
244
+ for (const key of CHOICE_CONFIG_KEYS) {
245
+ if (config[key] !== undefined) {
246
+ throw new Error(`Choice state "${stateNode.id}" cannot declare \`${key}\`.`);
247
+ }
248
+ }
249
+ }
250
+ }
251
+ function formatChoiceTransitions(stateNode) {
252
+ const choice = stateNode.config.choice;
253
+ const validateChoiceResult = result => {
254
+ if (!result || result.target === undefined) {
255
+ throw new Error(`Choice state "${stateNode.id}" must resolve to a target.` );
256
+ }
257
+ {
258
+ for (const key of ['actions', 'to']) {
259
+ if (result[key] !== undefined) {
260
+ throw new Error(`Choice state "${stateNode.id}" cannot declare \`${key}\` on a choice.`);
261
+ }
262
+ }
263
+ }
264
+ return result;
265
+ };
266
+ return [createActor.formatTransition(stateNode, createActor.NULL_EVENT, {
267
+ to: args => validateChoiceResult(choice(args))
268
+ })];
269
+ }
270
+ function mapTransitionConfigs(transitionsConfig, mapper) {
271
+ const transitionConfigs = createActor.toTransitionConfigArray(transitionsConfig);
272
+ const transitions = new Array(transitionConfigs.length);
273
+ for (let i = 0; i < transitionConfigs.length; i++) {
274
+ transitions[i] = mapper(transitionConfigs[i]);
275
+ }
276
+ return transitions;
277
+ }
278
+ function formatTransitions(stateNode) {
279
+ const transitions = new Map();
280
+ const addTransitions = (descriptor, additions) => {
281
+ transitions.set(descriptor, [...(transitions.get(descriptor) ?? []), ...additions]);
282
+ };
283
+ if (stateNode.config.on) {
284
+ for (const descriptor of Object.keys(stateNode.config.on)) {
285
+ if (descriptor === createActor.NULL_EVENT) {
286
+ throw new Error('Null events ("") cannot be specified as a transition key. Use `always: { ... }` instead.' );
287
+ }
288
+ const transitionsConfig = stateNode.config.on[descriptor];
289
+ transitions.set(descriptor, mapTransitionConfigs(transitionsConfig, transition => createActor.formatTransition(stateNode, descriptor, transition)));
290
+ }
291
+ }
292
+ if (stateNode.config.onDone) {
293
+ const descriptor = 'xstate.done.state';
294
+ addTransitions(descriptor, mapTransitionConfigs(stateNode.config.onDone, transition => createActor.formatTransition(stateNode, descriptor, {
295
+ ...transition,
296
+ matches: {
297
+ ...transition.matches,
298
+ stateId: stateNode.id
299
+ }
300
+ })));
301
+ }
302
+ if (stateNode.config.onError) {
303
+ const descriptor = 'xstate.error.*';
304
+ transitions.set(descriptor, mapTransitionConfigs(stateNode.config.onError, transition => createActor.formatTransition(stateNode, descriptor, transition)));
305
+ }
306
+ const createCancelInvokeTimeoutTransition = (descriptor, timeoutEventId, actorId) => createActor.formatTransition(stateNode, descriptor, {
307
+ matches: {
308
+ actorId
309
+ },
310
+ _eventMatcher: (event, snapshot) => createActor.matchesActorSession(event, snapshot, actorId),
311
+ to: (_args, enq) => {
312
+ enq.cancel(timeoutEventId);
313
+ return {};
314
+ }
315
+ });
316
+ const formatInvokeCompletionTransition = (descriptor, transitionConfig, timeoutEventId) => {
317
+ const {
318
+ target,
319
+ to,
320
+ reenter,
321
+ ...rest
322
+ } = transitionConfig;
323
+ return createActor.formatTransition(stateNode, descriptor, {
324
+ ...rest,
325
+ reenter,
326
+ to: (args, enq) => {
327
+ if (to) {
328
+ let didEnqueue = false;
329
+ const trackingEnqueue = new Proxy(enq, {
330
+ apply(target, thisArg, argArray) {
331
+ didEnqueue = true;
332
+ return Reflect.apply(target, thisArg, argArray);
333
+ },
334
+ get(target, prop, receiver) {
335
+ const value = Reflect.get(target, prop, receiver);
336
+ if (typeof value !== 'function') {
337
+ return value;
338
+ }
339
+ return (...argArray) => {
340
+ didEnqueue = true;
341
+ return value.apply(target, argArray);
342
+ };
343
+ }
344
+ });
345
+ const result = to(args, trackingEnqueue);
346
+ if (result !== undefined || didEnqueue) {
347
+ enq.cancel(timeoutEventId);
348
+ }
349
+ return result;
350
+ }
351
+ enq.cancel(timeoutEventId);
352
+ return {
353
+ target,
354
+ reenter
355
+ };
356
+ }
357
+ });
358
+ };
359
+ for (const invokeDef of stateNode.invoke) {
360
+ const withInvokeMatch = transition => ({
361
+ ...transition,
362
+ matches: {
363
+ ...transition.matches,
364
+ actorId: invokeDef.id
365
+ },
366
+ _eventMatcher: (event, snapshot) => createActor.matchesActorSession(event, snapshot, invokeDef.id)
367
+ });
368
+ const invokeTimeoutEventId = invokeDef.timeout !== undefined ? createActor.createInvokeTimeoutEventId(invokeDef.id) : undefined;
369
+ if (invokeDef.onDone) {
370
+ const descriptor = 'xstate.done.actor';
371
+ const invokeDoneTransitions = mapTransitionConfigs(invokeDef.onDone, rawTransition => {
372
+ const transition = withInvokeMatch(rawTransition);
373
+ return invokeTimeoutEventId ? formatInvokeCompletionTransition(descriptor, transition, invokeTimeoutEventId) : createActor.formatTransition(stateNode, descriptor, transition);
374
+ });
375
+ if (invokeTimeoutEventId) {
376
+ invokeDoneTransitions.push(createCancelInvokeTimeoutTransition(descriptor, invokeTimeoutEventId, invokeDef.id));
377
+ }
378
+ addTransitions(descriptor, invokeDoneTransitions);
379
+ } else if (invokeTimeoutEventId) {
380
+ const descriptor = 'xstate.done.actor';
381
+ addTransitions(descriptor, [createCancelInvokeTimeoutTransition(descriptor, invokeTimeoutEventId, invokeDef.id)]);
382
+ }
383
+ if (invokeDef.onError) {
384
+ const descriptor = 'xstate.error.actor';
385
+ addTransitions(descriptor, mapTransitionConfigs(invokeDef.onError, rawTransition => {
386
+ const transition = withInvokeMatch(rawTransition);
387
+ return invokeTimeoutEventId ? formatInvokeCompletionTransition(descriptor, transition, invokeTimeoutEventId) : createActor.formatTransition(stateNode, descriptor, transition);
388
+ }));
389
+ }
390
+ if (invokeDef.onSnapshot) {
391
+ const descriptor = 'xstate.snapshot.actor';
392
+ addTransitions(descriptor, mapTransitionConfigs(invokeDef.onSnapshot, transition => createActor.formatTransition(stateNode, descriptor, withInvokeMatch(transition))));
393
+ }
394
+ }
395
+ for (const delayedTransition of stateNode.after) {
396
+ let existing = transitions.get(delayedTransition.eventType);
397
+ if (!existing) {
398
+ existing = [];
399
+ transitions.set(delayedTransition.eventType, existing);
400
+ }
401
+ existing.push(delayedTransition);
402
+ }
403
+ return transitions;
404
+ }
405
+ function formatInitialTransition(stateNode, _target) {
406
+ const targetString = typeof _target === 'object' && _target !== null ? _target.target : _target;
407
+ const input = typeof _target === 'object' && _target !== null ? _target.input : undefined;
408
+ const resolvedTarget = typeof targetString === 'string' ? stateNode.states[targetString] : undefined;
409
+ if (!resolvedTarget && targetString) {
410
+ throw new Error(`Initial state node "${targetString}" not found on parent state node #${stateNode.id}` );
411
+ }
412
+ const transition = {
413
+ source: stateNode,
414
+ target: resolvedTarget ? [resolvedTarget] : undefined,
415
+ input
416
+ };
417
+ return transition;
418
+ }
419
+
420
+ const STATE_IDENTIFIER = '#';
421
+ let emptyCanActor;
422
+ let emptyCanActorScope;
423
+ function getEmptyCanActor() {
424
+ // A minimal inert actor used purely as the `self`/`parent` argument when
425
+ // dry-running transitions for `snapshot.can(...)`. Intentionally not built
426
+ // on `createLogic` so `can()` does not pull that machinery into bundles.
427
+ return emptyCanActor ??= createActor.createActor({
428
+ transition: snapshot => [snapshot, []],
429
+ initialTransition: () => [{
430
+ status: 'active',
431
+ output: undefined,
432
+ error: undefined
433
+ }, []],
434
+ getInitialSnapshot: () => ({
435
+ status: 'active',
436
+ output: undefined,
437
+ error: undefined
438
+ }),
439
+ getPersistedSnapshot: snapshot => snapshot
440
+ });
441
+ }
442
+ function getEmptyCanActorScope() {
443
+ if (emptyCanActorScope) {
444
+ return emptyCanActorScope;
445
+ }
446
+ const actor = getEmptyCanActor();
447
+ emptyCanActorScope = {
448
+ self: actor,
449
+ logger: () => {},
450
+ id: '',
451
+ sessionId: '',
452
+ defer: () => {},
453
+ system: actor.system,
454
+ stopChild: () => {},
455
+ emit: () => {},
456
+ actionExecutor: () => {}
457
+ };
458
+ return emptyCanActorScope;
459
+ }
460
+ class StateMachine {
461
+ constructor(/** The raw config used to create the machine. */
462
+ config, sources, validator) {
463
+ this.config = config;
464
+ this.validator = validator;
465
+ /** The machine's own version. */
466
+ this.version = void 0;
467
+ this.schemas = void 0;
468
+ /** Standard Schema for snapshots persisted by this machine version. */
469
+ this.snapshotSchema = void 0;
470
+ /** Standard Schema for complete events accepted by this machine version. */
471
+ this.eventSchema = void 0;
472
+ this.sources = void 0;
473
+ /** Runtime options for machine execution. */
474
+ this.options = void 0;
475
+ /** @internal */
476
+ this.idMap = new Map();
477
+ this.root = void 0;
478
+ this.id = void 0;
479
+ this.states = void 0;
480
+ this.events = void 0;
481
+ this.internalEventDescriptors = void 0;
482
+ /** @internal Skips eventless-selection scans for machines without `always`. */
483
+ this._hasEventlessTransitions = void 0;
484
+ /**
485
+ * The original JSON definition this machine was created from (set by
486
+ * `createMachineFromConfig`), if any. Used by `serializeMachine` for lossless
487
+ * round-trips.
488
+ *
489
+ * @internal
490
+ */
491
+ this._json = void 0;
492
+ this.id = config.id || '(machine)';
493
+ this.sources = {
494
+ actors: config.actors ?? {},
495
+ actions: config.actions ?? {},
496
+ delays: config.delays ?? {},
497
+ guards: config.guards ?? {},
498
+ ...sources
499
+ };
500
+ {
501
+ // The `@xstate.` prefix is reserved for built-in serialized action and
502
+ // guard descriptors — user source names must not collide.
503
+ for (const kind of ['actions', 'guards', 'actors', 'delays']) {
504
+ for (const key of Object.keys(this.sources[kind])) {
505
+ if (key.startsWith('@xstate.')) {
506
+ throw new Error(`Invalid ${kind} name '${key}': the '@xstate.' prefix is reserved for built-in descriptors.`);
507
+ }
508
+ }
509
+ }
510
+ }
511
+ this.version = this.config.version;
512
+ this.schemas = this.config.schemas;
513
+ this.snapshotSchema = {
514
+ '~standard': {
515
+ version: 1,
516
+ vendor: 'xstate',
517
+ validate: async value => {
518
+ if (value === null || typeof value !== 'object') {
519
+ return {
520
+ issues: [{
521
+ message: 'Expected a persisted snapshot.'
522
+ }]
523
+ };
524
+ }
525
+ const snapshot = {
526
+ historyValue: {},
527
+ timers: {},
528
+ ...value
529
+ };
530
+ const contextSchema = this.schemas?.context;
531
+ let context = snapshot.context;
532
+ if (contextSchema) {
533
+ const result = await contextSchema['~standard'].validate(context);
534
+ if (result.issues) {
535
+ return {
536
+ issues: [{
537
+ message: `Invalid context for machine '${this.id}' version '${this.version}': ${result.issues[0]?.message}`
538
+ }]
539
+ };
540
+ }
541
+ context = result.value;
542
+ }
543
+ for (const key of ['value', 'children']) {
544
+ if (!(key in snapshot)) {
545
+ return {
546
+ issues: [{
547
+ message: `Persisted snapshot is missing '${key}'.`
548
+ }]
549
+ };
550
+ }
551
+ }
552
+ if (!['active', 'done', 'error', 'stopped'].includes(snapshot.status)) {
553
+ return {
554
+ issues: [{
555
+ message: 'Persisted snapshot has invalid status.'
556
+ }]
557
+ };
558
+ }
559
+ for (const key of ['children', 'historyValue', 'timers']) {
560
+ if (snapshot[key] === null || typeof snapshot[key] !== 'object' || Array.isArray(snapshot[key])) {
561
+ return {
562
+ issues: [{
563
+ message: `Persisted snapshot has invalid '${key}'.`
564
+ }]
565
+ };
566
+ }
567
+ }
568
+ try {
569
+ this.resolveState({
570
+ value: snapshot.value,
571
+ context
572
+ });
573
+ } catch (error) {
574
+ return {
575
+ issues: [{
576
+ message: error instanceof Error ? error.message : 'Persisted snapshot has invalid state value.'
577
+ }]
578
+ };
579
+ }
580
+ return {
581
+ value: {
582
+ ...snapshot,
583
+ context
584
+ }
585
+ };
586
+ }
587
+ }
588
+ };
589
+ this.eventSchema = {
590
+ '~standard': {
591
+ version: 1,
592
+ vendor: 'xstate',
593
+ validate: async value => {
594
+ if (value === null || typeof value !== 'object' || typeof value.type !== 'string') {
595
+ return {
596
+ issues: [{
597
+ message: 'Expected an event object.'
598
+ }]
599
+ };
600
+ }
601
+ const event = value;
602
+ const eventSchemas = this.schemas?.events;
603
+ const isFrameworkEvent = event.type.startsWith('xstate.') || event.type.startsWith('@xstate.');
604
+ const schema = eventSchemas && Object.hasOwn(eventSchemas, event.type) ? eventSchemas[event.type] : undefined;
605
+ if (eventSchemas && !schema && !isFrameworkEvent) {
606
+ return {
607
+ issues: [{
608
+ message: `Unknown event '${event.type}' for machine '${this.id}' version '${this.version}'.`
609
+ }]
610
+ };
611
+ }
612
+ if (!schema) {
613
+ return {
614
+ value: event
615
+ };
616
+ }
617
+ const {
618
+ type,
619
+ ...payload
620
+ } = event;
621
+ const result = await schema['~standard'].validate(payload);
622
+ if (result.issues) {
623
+ return result;
624
+ }
625
+ if (result.value === null || typeof result.value !== 'object') {
626
+ return {
627
+ issues: [{
628
+ message: 'Expected an event payload.'
629
+ }]
630
+ };
631
+ }
632
+ return {
633
+ value: {
634
+ ...result.value,
635
+ type
636
+ }
637
+ };
638
+ }
639
+ }
640
+ };
641
+ this.internalEventDescriptors = this.config.internalEvents ?? [];
642
+ this.options = {
643
+ maxIterations: Infinity,
644
+ ...this.config.options
645
+ };
646
+ this.transition = this.transition.bind(this);
647
+ this.initialTransition = this.initialTransition.bind(this);
648
+ this.getInitialSnapshot = this.getInitialSnapshot.bind(this);
649
+ this.getPersistedSnapshot = this.getPersistedSnapshot.bind(this);
650
+ this.restoreSnapshot = this.restoreSnapshot.bind(this);
651
+ this.start = this.start.bind(this);
652
+ this.root = new StateNode(config, {
653
+ _key: this.id,
654
+ _machine: this
655
+ });
656
+ this.root._initialize();
657
+ createActor.formatRouteTransitions(this.root);
658
+ this.root._refreshEventMetadata();
659
+ this._hasEventlessTransitions = Array.from(this.idMap.values()).some(stateNode => !!stateNode.always?.length);
660
+ this.states = this.root.states; // TODO: remove!
661
+ this.events = this.root.events;
662
+ }
663
+
664
+ /**
665
+ * Clones this state machine with the provided sources.
666
+ *
667
+ * @param sources Options (`actions`, `guards`, `actors`, `delays`) to
668
+ * recursively merge with the existing options.
669
+ * @returns A new `StateMachine` instance with the provided sources.
670
+ */
671
+ provide(sources) {
672
+ const {
673
+ actions,
674
+ guards,
675
+ actors,
676
+ delays
677
+ } = this.sources;
678
+ const provided = new StateMachine(this.config, {
679
+ actions: {
680
+ ...actions,
681
+ ...sources.actions
682
+ },
683
+ guards: {
684
+ ...guards,
685
+ ...sources.guards
686
+ },
687
+ actors: {
688
+ ...actors,
689
+ ...sources.actors
690
+ },
691
+ delays: {
692
+ ...delays,
693
+ ...sources.delays
694
+ }
695
+ }, this.validator);
696
+ // Providing sources does not change the serializable definition.
697
+ provided._json = this._json;
698
+ return provided;
699
+ }
700
+ resolveState(config) {
701
+ const resolvedStateValue = createActor.resolveStateValue(this.root, config.value);
702
+ const nodeSet = createActor.getAllStateNodes(createActor.getStateNodes(this.root, resolvedStateValue));
703
+ const nodes = [...nodeSet];
704
+ return createActor.createMachineSnapshot({
705
+ _nodes: nodes,
706
+ value: resolvedStateValue,
707
+ context: config.context || {},
708
+ children: {},
709
+ status: createActor.isInFinalState(nodeSet, this.root) ? 'done' : config.status || 'active',
710
+ output: config.output,
711
+ error: config.error,
712
+ historyValue: config.historyValue
713
+ }, this);
714
+ }
715
+
716
+ /**
717
+ * Determines the next snapshot given the current `snapshot` and received
718
+ * `event`. Calculates a full macrostep from all microsteps.
719
+ *
720
+ * @param snapshot The current snapshot
721
+ * @param event The received event
722
+ */
723
+ transition(snapshot, event, actorScope) {
724
+ const usesInertScope = !actorScope;
725
+ const resolvedActorScope = actorScope ?? createActor.createInertActorScope(this, snapshot);
726
+ if (this.validator) {
727
+ dist_xstateActors.assertValid(this.validator, {
728
+ kind: 'event',
729
+ logic: this,
730
+ event,
731
+ eventOrigin: actorScope && actorScope.self._lastSourceRef ? 'actor' : 'external'
732
+ });
733
+ }
734
+ if (usesInertScope) {
735
+ createActor.setInertActorScopeSnapshot(resolvedActorScope, snapshot, false);
736
+ }
737
+ createActor.beginSpawnAllocation(resolvedActorScope);
738
+ const fastSnapshot = this._transitionFast(snapshot, event, resolvedActorScope);
739
+ if (fastSnapshot) {
740
+ if (usesInertScope) {
741
+ createActor.setInertActorScopeSnapshot(resolvedActorScope, fastSnapshot, false);
742
+ }
743
+ const returnedSnapshot = usesInertScope && fastSnapshot !== snapshot ? createActor.attachSnapshotActorRef(resolvedActorScope, fastSnapshot) : this._attachPureActorRef(fastSnapshot, resolvedActorScope);
744
+ if (this.validator) {
745
+ dist_xstateActors.assertValid(this.validator, {
746
+ kind: 'result',
747
+ logic: this,
748
+ snapshot: returnedSnapshot,
749
+ effects: []
750
+ });
751
+ }
752
+ return [returnedSnapshot, []];
753
+ }
754
+ const {
755
+ snapshot: nextSnapshot,
756
+ microsteps
757
+ } = createActor.macrostep(snapshot, event, resolvedActorScope, []);
758
+ if (usesInertScope) {
759
+ createActor.setInertActorScopeSnapshot(resolvedActorScope, nextSnapshot, false);
760
+ }
761
+ const returnedSnapshot = usesInertScope ? nextSnapshot === snapshot ? nextSnapshot : createActor.attachSnapshotActorRef(resolvedActorScope, nextSnapshot) : this._attachPureActorRef(nextSnapshot, resolvedActorScope);
762
+ const effects = this._collectEffects(microsteps);
763
+ if (this.validator) {
764
+ dist_xstateActors.assertValid(this.validator, {
765
+ kind: 'result',
766
+ logic: this,
767
+ snapshot: returnedSnapshot,
768
+ effects
769
+ });
770
+ }
771
+ return [returnedSnapshot, effects];
772
+ }
773
+ _collectEffects(microsteps) {
774
+ return microsteps.flatMap(([, actions]) => actions);
775
+ }
776
+ _attachPureActorRef(snapshot, actorScope, skipInitializingActor = false) {
777
+ if (createActor.isInertActorScope(actorScope)) {
778
+ return snapshot;
779
+ }
780
+ if (skipInitializingActor && actorScope.self._actorScope === actorScope && actorScope.self._snapshot === undefined) {
781
+ return snapshot;
782
+ }
783
+ createActor.setSnapshotActorRef(snapshot, actorScope.self, actorScope.system);
784
+ return snapshot;
785
+ }
786
+ _transitionFast(snapshot, event, actorScope) {
787
+ if (snapshot.status !== 'active' || typeof snapshot.value !== 'string' || this.root.always?.length) {
788
+ return undefined;
789
+ }
790
+ const sourceNode = this.root.states[snapshot.value];
791
+ if (!sourceNode || sourceNode.type !== 'atomic' || sourceNode.exit || sourceNode.invoke.length || sourceNode.always?.length || sourceNode.after?.length) {
792
+ return undefined;
793
+ }
794
+ const transitions = sourceNode.transitions.get(event.type);
795
+ if (transitions?.length !== 1) {
796
+ return undefined;
797
+ }
798
+ const selected = transitions[0];
799
+ if (selected.guard || selected.actions || selected.to || selected.reenter || selected.input || typeof selected.context === 'function' || selected.target && selected.target.length !== 1) {
800
+ return undefined;
801
+ }
802
+ const targetNode = selected.target?.[0] ?? sourceNode;
803
+ const stateChanged = targetNode !== sourceNode;
804
+ if (targetNode.parent !== this.root || targetNode.type !== 'atomic' || stateChanged && (targetNode.entry || targetNode.invoke.length || targetNode.always?.length || targetNode.after?.length)) {
805
+ return undefined;
806
+ }
807
+ const context = selected.context !== undefined ? {
808
+ ...snapshot.context,
809
+ ...selected.context
810
+ } : snapshot.context;
811
+ if (!createActor.isInertActorScope(actorScope) && (actorScope.system._hasInspectionObservers?.() ?? true)) {
812
+ const collectedMicrosteps = actorScope.self._collectedMicrosteps || [];
813
+ collectedMicrosteps.push(selected);
814
+ actorScope.self._collectedMicrosteps = collectedMicrosteps;
815
+ }
816
+ return createActor.cloneMachineSnapshot(snapshot, {
817
+ ...(context !== snapshot.context ? {
818
+ context
819
+ } : {}),
820
+ ...(stateChanged ? {
821
+ _nodes: [this.root, targetNode]
822
+ } : {})
823
+ });
824
+ }
825
+
826
+ /**
827
+ * Determines the next state given the current `state` and `event`. Calculates
828
+ * a microstep.
829
+ *
830
+ * @param state The current state
831
+ * @param event The received event
832
+ */
833
+ microstep(snapshot, event, actorScope) {
834
+ const {
835
+ microsteps
836
+ } = createActor.macrostep(snapshot, event, actorScope, []);
837
+ const snapshots = new Array(microsteps.length);
838
+ for (let i = 0; i < microsteps.length; i++) {
839
+ snapshots[i] = microsteps[i][0];
840
+ }
841
+ return snapshots;
842
+ }
843
+ getTransitionData(snapshot, event, actorScope, selectionResults) {
844
+ return createActor.transitionNode(this.root, snapshot.value, snapshot, event, actorScope, selectionResults) || [];
845
+ }
846
+ isInternalEventType(eventType) {
847
+ if (eventType === createActor.XSTATE_TIMER) {
848
+ return true;
849
+ }
850
+ for (const descriptor of this.internalEventDescriptors) {
851
+ if (createActor.matchesEventDescriptor(eventType, descriptor)) {
852
+ return true;
853
+ }
854
+ }
855
+ return false;
856
+ }
857
+
858
+ /**
859
+ * Determines whether sending the `event` to the given snapshot would select a
860
+ * non-forbidden transition. Backs `snapshot.can(...)`; lives here so that
861
+ * non-machine bundles don't pay for the transition-resolution machinery.
862
+ *
863
+ * @internal
864
+ */
865
+ _canTransition(snapshot, event) {
866
+ const emptyActorScope = getEmptyCanActorScope();
867
+ const transitionData = this.getTransitionData(snapshot, event, emptyActorScope);
868
+ if (!transitionData?.length) {
869
+ return false;
870
+ }
871
+
872
+ // Check that at least one transition is not forbidden
873
+ for (const transition of transitionData) {
874
+ if (transition.target !== undefined) {
875
+ return true;
876
+ }
877
+ const res = createActor.getTransitionResult(transition, snapshot, event, emptyActorScope, {
878
+ resolveActions: false
879
+ });
880
+ if (res.targets?.length || res.context || createActor.hasEffect(transition, snapshot.context, event, snapshot, emptyActorScope)) {
881
+ return true;
882
+ }
883
+ }
884
+ return false;
885
+ }
886
+
887
+ /**
888
+ * Returns the error event that the actor should transition with to recover
889
+ * from an execution error, if any active state node declares `onError`.
890
+ *
891
+ * @internal
892
+ */
893
+ getExecutionErrorEvent(snapshot, error) {
894
+ if (snapshot?.status !== 'active' || !snapshot.nodes?.some(stateNode => stateNode.config.onError)) {
895
+ return undefined;
896
+ }
897
+ return createActor.createErrorPlatformEvent('execution', error);
898
+ }
899
+
900
+ /**
901
+ * The initial state _before_ evaluating any microsteps. This "pre-initial"
902
+ * state is provided to initial actions executed in the initial state.
903
+ *
904
+ * @internal
905
+ */
906
+ _getPreInitialState(actorScope, initEvent) {
907
+ const {
908
+ context
909
+ } = this.config;
910
+ const preInitial = createActor.createMachineSnapshot({
911
+ context: typeof context !== 'function' && context ? context : {},
912
+ _nodes: [this.root],
913
+ children: {},
914
+ status: 'active'
915
+ }, this);
916
+ if (typeof context === 'function') {
917
+ const children = {};
918
+ const spawn = createSpawner(actorScope, this.sources.actors, children);
919
+ const resolvedContext = context(createActor.withActorSelf({
920
+ spawn,
921
+ input: initEvent.input,
922
+ actors: this.sources.actors
923
+ }, actorScope));
924
+ const [nextState] = createActor.resolveActionsWithContext(preInitial, initEvent, actorScope, []);
925
+ if (resolvedContext) {
926
+ nextState.context = resolvedContext;
927
+ }
928
+ if (Object.keys(children).length > 0) {
929
+ nextState.children = {
930
+ ...nextState.children,
931
+ ...children
932
+ };
933
+ // Commit the transaction counters so context-factory allocations
934
+ // persist with the snapshot: a freed id is never handed out again
935
+ // after a restore or in a fresh replay process. (The spawner already
936
+ // registered each child for string-id resolution.)
937
+ const counters = createActor.takeSpawnAllocationCounters(actorScope);
938
+ if (counters) {
939
+ nextState._nextActorIds = createActor.mergeActorIdCounters(nextState._nextActorIds, counters);
940
+ }
941
+ }
942
+ return nextState;
943
+ }
944
+ return preInitial;
945
+ }
946
+
947
+ /**
948
+ * Returns the initial `State` instance, with reference to `self` as an
949
+ * `ActorRef`.
950
+ */
951
+ getInitialSnapshot(actorScope, input) {
952
+ return this.initialTransition(input, actorScope)[0];
953
+ }
954
+ initialTransition(input, actorScope) {
955
+ if (this.validator) {
956
+ dist_xstateActors.assertValid(this.validator, {
957
+ kind: 'input',
958
+ logic: this,
959
+ input
960
+ });
961
+ }
962
+ const usesInertScope = !actorScope;
963
+ const resolvedActorScope = actorScope ?? createActor.createInertActorScope(this);
964
+ createActor.beginSpawnAllocation(resolvedActorScope);
965
+ const initEvent = createActor.createInitEvent(input); // TODO: fix;
966
+ const internalQueue = [];
967
+ const preInitialState = this._getPreInitialState(resolvedActorScope, initEvent);
968
+ const contextSpawnEffects = Object.values(preInitialState.children).filter(Boolean).map(actor => createActor.createSpawnEffect(actor));
969
+ const finalizeInitialResult = (macroState, microsteps) => {
970
+ if (usesInertScope) {
971
+ createActor.setInertActorScopeSnapshot(resolvedActorScope, macroState, false);
972
+ }
973
+ const returnedSnapshot = usesInertScope ? createActor.attachSnapshotActorRef(resolvedActorScope, macroState) : this._attachPureActorRef(macroState, resolvedActorScope, true);
974
+ const effects = this._collectEffects(microsteps);
975
+ if (this.validator) {
976
+ dist_xstateActors.assertValid(this.validator, {
977
+ kind: 'result',
978
+ logic: this,
979
+ snapshot: returnedSnapshot,
980
+ effects
981
+ });
982
+ }
983
+ return [returnedSnapshot, effects];
984
+ };
985
+ try {
986
+ const [nextState, initialActions] = createActor.initialMicrostep(this.root, preInitialState, resolvedActorScope, initEvent, internalQueue);
987
+ const {
988
+ snapshot: macroState,
989
+ microsteps
990
+ } = createActor.macrostep(nextState, initEvent, resolvedActorScope, internalQueue, [[nextState, [...contextSpawnEffects, ...initialActions]]]);
991
+ return finalizeInitialResult(macroState, microsteps);
992
+ } catch (err) {
993
+ if (!this.root.config.onError) {
994
+ throw err;
995
+ }
996
+ const errorEvent = createActor.createErrorPlatformEvent('execution', err);
997
+ const errorMacrostep = createActor.macrostep(preInitialState, errorEvent, resolvedActorScope, [], [[preInitialState, contextSpawnEffects]]);
998
+ return finalizeInitialResult(errorMacrostep.snapshot, errorMacrostep.microsteps);
999
+ }
1000
+ }
1001
+ start(snapshot) {
1002
+ // Start rehydrated children that were active when persisted. Freshly
1003
+ // invoked/spawned children are NOT started here — they start via deferred
1004
+ // `@xstate.start` actions so sync start errors route to `onError`.
1005
+ if (!snapshot?.children) {
1006
+ return;
1007
+ }
1008
+ const children = snapshot.children;
1009
+ for (const childId in children) {
1010
+ if (!Object.hasOwn(children, childId)) {
1011
+ continue;
1012
+ }
1013
+ const child = children[childId];
1014
+ if (child._rehydrated && child.getSnapshot?.().status === 'active') {
1015
+ child.start();
1016
+ }
1017
+ }
1018
+ }
1019
+ getStateNodeById(stateId) {
1020
+ const fullPath = createActor.toStatePath(stateId);
1021
+ const relativePath = fullPath.slice(1);
1022
+ const resolvedStateId = createActor.isStateId(fullPath[0]) ? fullPath[0].slice(STATE_IDENTIFIER.length) : fullPath[0];
1023
+ const stateNode = this.idMap.get(resolvedStateId);
1024
+ if (!stateNode) {
1025
+ throw new Error(`Child state node '#${resolvedStateId}' does not exist on machine '${this.id}'`);
1026
+ }
1027
+ return createActor.getStateNodeByPath(stateNode, relativePath);
1028
+ }
1029
+ getPersistedSnapshot(snapshot, options) {
1030
+ return createActor.getPersistedSnapshot(snapshot, options);
1031
+ }
1032
+ restoreSnapshot(snapshot, actorScope) {
1033
+ const usesInertScope = !actorScope;
1034
+ const resolvedActorScope = actorScope ?? createActor.createInertActorScope(this);
1035
+ const persistedMachine = snapshot.machine;
1036
+ const legacyPersistedVersion = snapshot.version;
1037
+ const persistedVersion = typeof persistedMachine?.version === 'string' ? persistedMachine.version : legacyPersistedVersion;
1038
+ if (legacyPersistedVersion !== undefined && persistedMachine?.version !== undefined && persistedMachine.version !== legacyPersistedVersion) {
1039
+ throw new Error(`Persisted snapshot version '${legacyPersistedVersion}' conflicts with machine version '${persistedMachine.version}'.`);
1040
+ }
1041
+ if (persistedMachine && typeof persistedMachine.id === 'string' && persistedMachine.id !== this.id) {
1042
+ throw new Error(`Machine ID mismatch: persisted snapshot was created by machine '${persistedMachine.id}', but machine '${this.id}' was provided.` );
1043
+ }
1044
+ if (persistedVersion !== this.version) {
1045
+ const migrate = this.config.migrate;
1046
+ if (typeof migrate !== 'function') {
1047
+ throw new Error(`Persisted snapshot version '${persistedVersion}' does not match machine version '${this.version}' for machine '${this.id}'. Provide a \`migrate(persistedSnapshot, fromVersion)\` function in the machine config to migrate old snapshots.` );
1048
+ }
1049
+ snapshot = migrate(snapshot, persistedVersion);
1050
+ }
1051
+ const snapshotData = snapshot;
1052
+ const children = {};
1053
+ const snapshotChildren = snapshotData.children;
1054
+ for (const actorId of Object.keys(snapshotChildren)) {
1055
+ const actorData = snapshotChildren[actorId];
1056
+ if (actorData.remote === true && actorData.address !== undefined) {
1057
+ if (typeof actorData.src !== 'string') {
1058
+ // Fail loudly instead of fabricating a source key that hosts would
1059
+ // route by.
1060
+ throw new Error(`Unable to restore remote child '${actorId}': a child referenced by address requires a registered source key.`);
1061
+ }
1062
+ // The child's state lives with another runtime; restore a
1063
+ // location-transparent handle constructed from its identity alone.
1064
+ // The handle keeps its persisted address verbatim: the owning
1065
+ // runtime's identity for the child wins over the local parent chain.
1066
+ const handle = createActor.createRemoteActorRef(resolvedActorScope.system, {
1067
+ id: actorId,
1068
+ address: actorData.address,
1069
+ src: actorData.src,
1070
+ parent: resolvedActorScope.self,
1071
+ registryKey: actorData.registryKey,
1072
+ syncSnapshot: actorData.syncSnapshot,
1073
+ incarnation: actorData.incarnation
1074
+ });
1075
+ if (actorData.registryKey) {
1076
+ resolvedActorScope.system._set(actorData.registryKey, handle);
1077
+ }
1078
+ children[actorId] = handle;
1079
+ continue;
1080
+ }
1081
+ const childState = actorData.snapshot;
1082
+ const src = actorData.src;
1083
+ const logic = typeof src === 'string' ? createActor.resolveReferencedActor(this, src) : src;
1084
+ if (!logic) {
1085
+ const sourceId = typeof src === 'string' ? src : '<unknown>';
1086
+ throw new Error(`Unable to restore child actor '${actorId}': child source '${sourceId}' is not provided in machine '${this.id}'.`);
1087
+ }
1088
+ const actor = resolvedActorScope.system.createActorRef(logic, {
1089
+ id: actorId,
1090
+ parent: resolvedActorScope.self,
1091
+ syncSnapshot: actorData.syncSnapshot,
1092
+ snapshot: childState,
1093
+ src,
1094
+ registryKey: actorData.registryKey
1095
+ });
1096
+ // Mark so `start()` knows to start this child (freshly invoked/spawned
1097
+ // children are started via deferred `@xstate.start` actions instead).
1098
+ actor._rehydrated = true;
1099
+ children[actorId] = actor;
1100
+ }
1101
+ const timers = {};
1102
+ const persistedTimers = snapshotData.timers ?? {};
1103
+ for (const [id, timer] of Object.entries(persistedTimers)) {
1104
+ let event = timer.event;
1105
+ if (event.type === 'xstate.timeout.actor') {
1106
+ const actorId = event.actorId;
1107
+ const child = children[actorId];
1108
+ if (child) {
1109
+ event = createActor.createInvokeTimeoutEvent(actorId, child.sessionId);
1110
+ }
1111
+ }
1112
+ const target = typeof timer.target === 'string' ? timer.target === 'self' ? 'self' : children[timer.target] : resolvedActorScope.self._parent;
1113
+ if (!target) {
1114
+ const targetDescription = typeof timer.target === 'string' ? timer.target : timer.target.type;
1115
+ throw new Error(`Unable to restore timer '${id}': target actor '${targetDescription}' is unavailable.`);
1116
+ }
1117
+ timers[id] = {
1118
+ ...timer,
1119
+ event,
1120
+ target
1121
+ };
1122
+ }
1123
+ const reviveHistoryValue = historyValue => {
1124
+ if (!historyValue || typeof historyValue !== 'object') {
1125
+ return {};
1126
+ }
1127
+ const revived = {};
1128
+ for (const key of Object.keys(historyValue)) {
1129
+ const arr = historyValue[key];
1130
+ for (const item of arr) {
1131
+ let resolved;
1132
+ if (item instanceof StateNode) {
1133
+ resolved = item;
1134
+ } else {
1135
+ try {
1136
+ resolved = this.root.machine.getStateNodeById(item.id);
1137
+ } catch {
1138
+ {
1139
+ console.warn(`Could not resolve StateNode for id: ${item.id}`);
1140
+ }
1141
+ }
1142
+ }
1143
+ if (!resolved) {
1144
+ continue;
1145
+ }
1146
+ revived[key] ??= [];
1147
+ revived[key].push(resolved);
1148
+ }
1149
+ }
1150
+ return revived;
1151
+ };
1152
+ const revivedHistoryValue = reviveHistoryValue(snapshotData.historyValue);
1153
+ const validateStateValue = (stateValue, node, path) => {
1154
+ const missingStateError = statePath => new Error(`Persisted snapshot references state '${statePath.join('.')}' which does not exist on machine '${this.id}'.`);
1155
+ if (typeof stateValue === 'string') {
1156
+ if (!node.states[stateValue]) {
1157
+ throw missingStateError(path.concat(stateValue));
1158
+ }
1159
+ return;
1160
+ }
1161
+ if (!stateValue || typeof stateValue !== 'object') {
1162
+ return;
1163
+ }
1164
+ for (const key of Object.keys(stateValue)) {
1165
+ const childNode = node.states[key];
1166
+ if (!childNode) {
1167
+ throw missingStateError(path.concat(key));
1168
+ }
1169
+ validateStateValue(stateValue[key], childNode, path.concat(key));
1170
+ }
1171
+ };
1172
+ validateStateValue(snapshotData.value, this.root, []);
1173
+ const nodes = Array.from(createActor.getAllStateNodes(createActor.getStateNodes(this.root, snapshotData.value)));
1174
+ const {
1175
+ version: _persistedSnapshotVersion,
1176
+ // The legacy system-wide counter: superseded by per-snapshot
1177
+ // `_nextActorIds` plus the child-id fold below; dropped so old and new
1178
+ // snapshots round-trip to the same shape.
1179
+ _nextActorId: _legacyNextActorId,
1180
+ ...persistedRest
1181
+ } = snapshot;
1182
+ // Fold generated-shaped child ids into the counters as a floor: snapshots
1183
+ // persisted before per-actor counters (or hand-crafted ones) still must
1184
+ // never reuse a live child's id.
1185
+ let restoredCounters = persistedRest._nextActorIds;
1186
+ for (const childId of Object.keys(snapshotChildren)) {
1187
+ const generated = createActor.parseGeneratedActorId(childId);
1188
+ if (generated && (restoredCounters?.[generated.prefix] ?? 0) <= generated.index) {
1189
+ restoredCounters = {
1190
+ ...restoredCounters,
1191
+ [generated.prefix]: generated.index + 1
1192
+ };
1193
+ }
1194
+ }
1195
+ const restoredSnapshot = createActor.createMachineSnapshot({
1196
+ ...persistedRest,
1197
+ children,
1198
+ timers,
1199
+ _nextActorIds: restoredCounters,
1200
+ _nodes: nodes,
1201
+ value: snapshotData.value,
1202
+ historyValue: revivedHistoryValue,
1203
+ _stateInputs: snapshotData.stateInputs ?? {}
1204
+ }, this, resolvedActorScope.self);
1205
+ const seen = new WeakSet();
1206
+ function reviveContext(contextPart) {
1207
+ if (seen.has(contextPart)) {
1208
+ return;
1209
+ }
1210
+ seen.add(contextPart);
1211
+ for (const key of Object.keys(contextPart)) {
1212
+ const value = contextPart[key];
1213
+ if (value && typeof value === 'object') {
1214
+ if ('xstate$type' in value && value.xstate$type === createActor.ACTOR_REF_TYPE) {
1215
+ contextPart[key] = children[value.id];
1216
+ continue;
1217
+ }
1218
+ reviveContext(value);
1219
+ }
1220
+ }
1221
+ }
1222
+ reviveContext(restoredSnapshot.context);
1223
+ if (usesInertScope) {
1224
+ createActor.setInertActorScopeSnapshot(resolvedActorScope, restoredSnapshot, false);
1225
+ return createActor.attachSnapshotActorRef(resolvedActorScope, restoredSnapshot);
1226
+ }
1227
+ return this._attachPureActorRef(restoredSnapshot, resolvedActorScope);
1228
+ }
1229
+ }
1230
+
1231
+ exports.StateMachine = StateMachine;
1232
+ exports.StateNode = StateNode;