@incodetech/core 2.0.0-alpha.1 → 2.0.0-alpha.10

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 (106) hide show
  1. package/dist/Manager-BGfxEmyv.d.ts +19 -0
  2. package/dist/OpenViduLogger-BdPfiZO6.esm.js +3 -0
  3. package/dist/OpenViduLogger-CQyDxBvM.esm.js +803 -0
  4. package/dist/StateMachine-DRE1oH2B.d.ts +2 -0
  5. package/dist/addEvent-W0ORK0jT.esm.js +16 -0
  6. package/dist/chunk-C_Yo44FK.esm.js +49 -0
  7. package/dist/email.d.ts +264 -0
  8. package/dist/email.esm.js +479 -0
  9. package/dist/endpoints-BSTFaHYo.esm.js +1706 -0
  10. package/dist/flow.d.ts +578 -0
  11. package/dist/flow.esm.js +628 -0
  12. package/dist/index.d.ts +226 -0
  13. package/dist/index.esm.js +155 -0
  14. package/dist/lib-Bu9XGMBW.esm.js +11700 -0
  15. package/dist/permissionServices-I6vX6DBy.esm.js +72 -0
  16. package/dist/phone.d.ts +292 -0
  17. package/dist/phone.esm.js +550 -0
  18. package/dist/selfie.d.ts +759 -0
  19. package/dist/selfie.esm.js +995 -0
  20. package/dist/types-iZi2rawo.d.ts +5 -0
  21. package/dist/warmup-CEJTfxQr.d.ts +55 -0
  22. package/dist/xstate.esm-B_rda9yU.esm.js +3261 -0
  23. package/package.json +14 -11
  24. package/src/camera/cameraActor.ts +0 -21
  25. package/src/camera/cameraService.test.ts +0 -437
  26. package/src/camera/cameraService.ts +0 -165
  27. package/src/camera/cameraServices.test.ts +0 -66
  28. package/src/camera/cameraServices.ts +0 -26
  29. package/src/camera/cameraStateMachine.test.ts +0 -602
  30. package/src/camera/cameraStateMachine.ts +0 -264
  31. package/src/camera/index.ts +0 -5
  32. package/src/camera/types.ts +0 -17
  33. package/src/device/getBrowser.ts +0 -31
  34. package/src/device/getDeviceClass.ts +0 -29
  35. package/src/device/index.ts +0 -2
  36. package/src/email/__mocks__/emailMocks.ts +0 -59
  37. package/src/email/emailActor.ts +0 -15
  38. package/src/email/emailManager.test.ts +0 -573
  39. package/src/email/emailManager.ts +0 -427
  40. package/src/email/emailServices.ts +0 -66
  41. package/src/email/emailStateMachine.test.ts +0 -741
  42. package/src/email/emailStateMachine.ts +0 -367
  43. package/src/email/index.ts +0 -39
  44. package/src/email/types.ts +0 -60
  45. package/src/events/addEvent.ts +0 -20
  46. package/src/events/types.ts +0 -7
  47. package/src/flow/__mocks__/flowMocks.ts +0 -84
  48. package/src/flow/flowActor.ts +0 -13
  49. package/src/flow/flowAnalyzer.test.ts +0 -266
  50. package/src/flow/flowAnalyzer.ts +0 -37
  51. package/src/flow/flowCompletionService.ts +0 -21
  52. package/src/flow/flowManager.test.ts +0 -560
  53. package/src/flow/flowManager.ts +0 -235
  54. package/src/flow/flowServices.test.ts +0 -109
  55. package/src/flow/flowServices.ts +0 -13
  56. package/src/flow/flowStateMachine.test.ts +0 -334
  57. package/src/flow/flowStateMachine.ts +0 -182
  58. package/src/flow/index.ts +0 -21
  59. package/src/flow/moduleLoader.test.ts +0 -136
  60. package/src/flow/moduleLoader.ts +0 -73
  61. package/src/flow/orchestratedFlowManager.test.ts +0 -240
  62. package/src/flow/orchestratedFlowManager.ts +0 -231
  63. package/src/flow/orchestratedFlowStateMachine.test.ts +0 -199
  64. package/src/flow/orchestratedFlowStateMachine.ts +0 -325
  65. package/src/flow/types.ts +0 -434
  66. package/src/http/__mocks__/api.ts +0 -88
  67. package/src/http/api.test.ts +0 -231
  68. package/src/http/api.ts +0 -90
  69. package/src/http/endpoints.ts +0 -17
  70. package/src/index.ts +0 -33
  71. package/src/permissions/index.ts +0 -2
  72. package/src/permissions/permissionServices.ts +0 -31
  73. package/src/permissions/types.ts +0 -3
  74. package/src/phone/__mocks__/phoneMocks.ts +0 -71
  75. package/src/phone/index.ts +0 -39
  76. package/src/phone/phoneActor.ts +0 -15
  77. package/src/phone/phoneManager.test.ts +0 -393
  78. package/src/phone/phoneManager.ts +0 -458
  79. package/src/phone/phoneServices.ts +0 -98
  80. package/src/phone/phoneStateMachine.test.ts +0 -918
  81. package/src/phone/phoneStateMachine.ts +0 -422
  82. package/src/phone/types.ts +0 -83
  83. package/src/recordings/recordingsRepository.test.ts +0 -87
  84. package/src/recordings/recordingsRepository.ts +0 -48
  85. package/src/recordings/streamingEvents.ts +0 -10
  86. package/src/selfie/__mocks__/selfieMocks.ts +0 -26
  87. package/src/selfie/index.ts +0 -14
  88. package/src/selfie/selfieActor.ts +0 -17
  89. package/src/selfie/selfieErrorUtils.test.ts +0 -116
  90. package/src/selfie/selfieErrorUtils.ts +0 -66
  91. package/src/selfie/selfieManager.test.ts +0 -297
  92. package/src/selfie/selfieManager.ts +0 -301
  93. package/src/selfie/selfieServices.ts +0 -362
  94. package/src/selfie/selfieStateMachine.test.ts +0 -283
  95. package/src/selfie/selfieStateMachine.ts +0 -804
  96. package/src/selfie/selfieUploadService.test.ts +0 -90
  97. package/src/selfie/selfieUploadService.ts +0 -81
  98. package/src/selfie/types.ts +0 -103
  99. package/src/session/index.ts +0 -5
  100. package/src/session/sessionService.ts +0 -78
  101. package/src/setup.test.ts +0 -61
  102. package/src/setup.ts +0 -171
  103. package/tsconfig.json +0 -13
  104. package/tsdown.config.ts +0 -22
  105. package/vitest.config.ts +0 -37
  106. package/vitest.setup.ts +0 -135
@@ -0,0 +1,3261 @@
1
+ //#region ../../node_modules/.pnpm/xstate@5.24.0/node_modules/xstate/dev/dist/xstate-dev.esm.js
2
+ function getGlobal() {
3
+ if (typeof globalThis !== "undefined") return globalThis;
4
+ if (typeof self !== "undefined") return self;
5
+ if (typeof window !== "undefined") return window;
6
+ if (typeof global !== "undefined") return global;
7
+ }
8
+ function getDevTools() {
9
+ const w = getGlobal();
10
+ if (w.__xstate__) return w.__xstate__;
11
+ }
12
+ const devToolsAdapter = (service) => {
13
+ if (typeof window === "undefined") return;
14
+ const devTools = getDevTools();
15
+ if (devTools) devTools.register(service);
16
+ };
17
+
18
+ //#endregion
19
+ //#region ../../node_modules/.pnpm/xstate@5.24.0/node_modules/xstate/dist/raise-9ad1c5c6.esm.js
20
+ var Mailbox = class {
21
+ constructor(_process) {
22
+ this._process = _process;
23
+ this._active = false;
24
+ this._current = null;
25
+ this._last = null;
26
+ }
27
+ start() {
28
+ this._active = true;
29
+ this.flush();
30
+ }
31
+ clear() {
32
+ if (this._current) {
33
+ this._current.next = null;
34
+ this._last = this._current;
35
+ }
36
+ }
37
+ enqueue(event) {
38
+ const enqueued = {
39
+ value: event,
40
+ next: null
41
+ };
42
+ if (this._current) {
43
+ this._last.next = enqueued;
44
+ this._last = enqueued;
45
+ return;
46
+ }
47
+ this._current = enqueued;
48
+ this._last = enqueued;
49
+ if (this._active) this.flush();
50
+ }
51
+ flush() {
52
+ while (this._current) {
53
+ const consumed = this._current;
54
+ this._process(consumed.value);
55
+ this._current = consumed.next;
56
+ }
57
+ this._last = null;
58
+ }
59
+ };
60
+ const STATE_DELIMITER = ".";
61
+ const TARGETLESS_KEY = "";
62
+ const NULL_EVENT = "";
63
+ const STATE_IDENTIFIER = "#";
64
+ const WILDCARD = "*";
65
+ const XSTATE_INIT = "xstate.init";
66
+ const XSTATE_ERROR = "xstate.error";
67
+ const XSTATE_STOP = "xstate.stop";
68
+ /**
69
+ * Returns an event that represents an implicit event that is sent after the
70
+ * specified `delay`.
71
+ *
72
+ * @param delayRef The delay in milliseconds
73
+ * @param id The state node ID where this event is handled
74
+ */
75
+ function createAfterEvent(delayRef, id) {
76
+ return { type: `xstate.after.${delayRef}.${id}` };
77
+ }
78
+ /**
79
+ * Returns an event that represents that a final state node has been reached in
80
+ * the parent state node.
81
+ *
82
+ * @param id The final state node's parent state node `id`
83
+ * @param output The data to pass into the event
84
+ */
85
+ function createDoneStateEvent(id, output) {
86
+ return {
87
+ type: `xstate.done.state.${id}`,
88
+ output
89
+ };
90
+ }
91
+ /**
92
+ * Returns an event that represents that an invoked service has terminated.
93
+ *
94
+ * An invoked service is terminated when it has reached a top-level final state
95
+ * node, but not when it is canceled.
96
+ *
97
+ * @param invokeId The invoked service ID
98
+ * @param output The data to pass into the event
99
+ */
100
+ function createDoneActorEvent(invokeId, output) {
101
+ return {
102
+ type: `xstate.done.actor.${invokeId}`,
103
+ output,
104
+ actorId: invokeId
105
+ };
106
+ }
107
+ function createErrorActorEvent(id, error) {
108
+ return {
109
+ type: `xstate.error.actor.${id}`,
110
+ error,
111
+ actorId: id
112
+ };
113
+ }
114
+ function createInitEvent(input) {
115
+ return {
116
+ type: XSTATE_INIT,
117
+ input
118
+ };
119
+ }
120
+ /**
121
+ * This function makes sure that unhandled errors are thrown in a separate
122
+ * macrotask. It allows those errors to be detected by global error handlers and
123
+ * reported to bug tracking services without interrupting our own stack of
124
+ * execution.
125
+ *
126
+ * @param err Error to be thrown
127
+ */
128
+ function reportUnhandledError(err) {
129
+ setTimeout(() => {
130
+ throw err;
131
+ });
132
+ }
133
+ const symbolObservable = (() => typeof Symbol === "function" && Symbol.observable || "@@observable")();
134
+ function matchesState(parentStateId, childStateId) {
135
+ const parentStateValue = toStateValue(parentStateId);
136
+ const childStateValue = toStateValue(childStateId);
137
+ if (typeof childStateValue === "string") {
138
+ if (typeof parentStateValue === "string") return childStateValue === parentStateValue;
139
+ return false;
140
+ }
141
+ if (typeof parentStateValue === "string") return parentStateValue in childStateValue;
142
+ return Object.keys(parentStateValue).every((key) => {
143
+ if (!(key in childStateValue)) return false;
144
+ return matchesState(parentStateValue[key], childStateValue[key]);
145
+ });
146
+ }
147
+ function toStatePath(stateId) {
148
+ if (isArray(stateId)) return stateId;
149
+ const result = [];
150
+ let segment = "";
151
+ for (let i = 0; i < stateId.length; i++) {
152
+ switch (stateId.charCodeAt(i)) {
153
+ case 92:
154
+ segment += stateId[i + 1];
155
+ i++;
156
+ continue;
157
+ case 46:
158
+ result.push(segment);
159
+ segment = "";
160
+ continue;
161
+ }
162
+ segment += stateId[i];
163
+ }
164
+ result.push(segment);
165
+ return result;
166
+ }
167
+ function toStateValue(stateValue) {
168
+ if (isMachineSnapshot(stateValue)) return stateValue.value;
169
+ if (typeof stateValue !== "string") return stateValue;
170
+ return pathToStateValue(toStatePath(stateValue));
171
+ }
172
+ function pathToStateValue(statePath) {
173
+ if (statePath.length === 1) return statePath[0];
174
+ const value = {};
175
+ let marker = value;
176
+ for (let i = 0; i < statePath.length - 1; i++) if (i === statePath.length - 2) marker[statePath[i]] = statePath[i + 1];
177
+ else {
178
+ const previous = marker;
179
+ marker = {};
180
+ previous[statePath[i]] = marker;
181
+ }
182
+ return value;
183
+ }
184
+ function mapValues(collection, iteratee) {
185
+ const result = {};
186
+ const collectionKeys = Object.keys(collection);
187
+ for (let i = 0; i < collectionKeys.length; i++) {
188
+ const key = collectionKeys[i];
189
+ result[key] = iteratee(collection[key], key, collection, i);
190
+ }
191
+ return result;
192
+ }
193
+ function toArrayStrict(value) {
194
+ if (isArray(value)) return value;
195
+ return [value];
196
+ }
197
+ function toArray(value) {
198
+ if (value === void 0) return [];
199
+ return toArrayStrict(value);
200
+ }
201
+ function resolveOutput(mapper, context, event, self$1) {
202
+ if (typeof mapper === "function") return mapper({
203
+ context,
204
+ event,
205
+ self: self$1
206
+ });
207
+ return mapper;
208
+ }
209
+ function isArray(value) {
210
+ return Array.isArray(value);
211
+ }
212
+ function isErrorActorEvent(event) {
213
+ return event.type.startsWith("xstate.error.actor");
214
+ }
215
+ function toTransitionConfigArray(configLike) {
216
+ return toArrayStrict(configLike).map((transitionLike) => {
217
+ if (typeof transitionLike === "undefined" || typeof transitionLike === "string") return { target: transitionLike };
218
+ return transitionLike;
219
+ });
220
+ }
221
+ function normalizeTarget(target) {
222
+ if (target === void 0 || target === TARGETLESS_KEY) return;
223
+ return toArray(target);
224
+ }
225
+ function toObserver(nextHandler, errorHandler, completionHandler) {
226
+ const isObserver = typeof nextHandler === "object";
227
+ const self$1 = isObserver ? nextHandler : void 0;
228
+ return {
229
+ next: (isObserver ? nextHandler.next : nextHandler)?.bind(self$1),
230
+ error: (isObserver ? nextHandler.error : errorHandler)?.bind(self$1),
231
+ complete: (isObserver ? nextHandler.complete : completionHandler)?.bind(self$1)
232
+ };
233
+ }
234
+ function createInvokeId(stateNodeId, index) {
235
+ return `${index}.${stateNodeId}`;
236
+ }
237
+ function resolveReferencedActor(machine, src) {
238
+ const match = src.match(/^xstate\.invoke\.(\d+)\.(.*)/);
239
+ if (!match) return machine.implementations.actors[src];
240
+ const [, indexStr, nodeId] = match;
241
+ const invokeConfig = machine.getStateNodeById(nodeId).config.invoke;
242
+ return (Array.isArray(invokeConfig) ? invokeConfig[indexStr] : invokeConfig).src;
243
+ }
244
+ function createScheduledEventId(actorRef, id) {
245
+ return `${actorRef.sessionId}.${id}`;
246
+ }
247
+ let idCounter = 0;
248
+ function createSystem(rootActor, options) {
249
+ const children = /* @__PURE__ */ new Map();
250
+ const keyedActors = /* @__PURE__ */ new Map();
251
+ const reverseKeyedActors = /* @__PURE__ */ new WeakMap();
252
+ const inspectionObservers = /* @__PURE__ */ new Set();
253
+ const timerMap = {};
254
+ const { clock, logger } = options;
255
+ const scheduler = {
256
+ schedule: (source, target, event, delay, id = Math.random().toString(36).slice(2)) => {
257
+ const scheduledEvent = {
258
+ source,
259
+ target,
260
+ event,
261
+ delay,
262
+ id,
263
+ startedAt: Date.now()
264
+ };
265
+ const scheduledEventId = createScheduledEventId(source, id);
266
+ system._snapshot._scheduledEvents[scheduledEventId] = scheduledEvent;
267
+ timerMap[scheduledEventId] = clock.setTimeout(() => {
268
+ delete timerMap[scheduledEventId];
269
+ delete system._snapshot._scheduledEvents[scheduledEventId];
270
+ system._relay(source, target, event);
271
+ }, delay);
272
+ },
273
+ cancel: (source, id) => {
274
+ const scheduledEventId = createScheduledEventId(source, id);
275
+ const timeout = timerMap[scheduledEventId];
276
+ delete timerMap[scheduledEventId];
277
+ delete system._snapshot._scheduledEvents[scheduledEventId];
278
+ if (timeout !== void 0) clock.clearTimeout(timeout);
279
+ },
280
+ cancelAll: (actorRef) => {
281
+ for (const scheduledEventId in system._snapshot._scheduledEvents) {
282
+ const scheduledEvent = system._snapshot._scheduledEvents[scheduledEventId];
283
+ if (scheduledEvent.source === actorRef) scheduler.cancel(actorRef, scheduledEvent.id);
284
+ }
285
+ }
286
+ };
287
+ const sendInspectionEvent = (event) => {
288
+ if (!inspectionObservers.size) return;
289
+ const resolvedInspectionEvent = {
290
+ ...event,
291
+ rootId: rootActor.sessionId
292
+ };
293
+ inspectionObservers.forEach((observer) => observer.next?.(resolvedInspectionEvent));
294
+ };
295
+ const system = {
296
+ _snapshot: { _scheduledEvents: (options?.snapshot && options.snapshot.scheduler) ?? {} },
297
+ _bookId: () => `x:${idCounter++}`,
298
+ _register: (sessionId, actorRef) => {
299
+ children.set(sessionId, actorRef);
300
+ return sessionId;
301
+ },
302
+ _unregister: (actorRef) => {
303
+ children.delete(actorRef.sessionId);
304
+ const systemId = reverseKeyedActors.get(actorRef);
305
+ if (systemId !== void 0) {
306
+ keyedActors.delete(systemId);
307
+ reverseKeyedActors.delete(actorRef);
308
+ }
309
+ },
310
+ get: (systemId) => {
311
+ return keyedActors.get(systemId);
312
+ },
313
+ getAll: () => {
314
+ return Object.fromEntries(keyedActors.entries());
315
+ },
316
+ _set: (systemId, actorRef) => {
317
+ const existing = keyedActors.get(systemId);
318
+ if (existing && existing !== actorRef) throw new Error(`Actor with system ID '${systemId}' already exists.`);
319
+ keyedActors.set(systemId, actorRef);
320
+ reverseKeyedActors.set(actorRef, systemId);
321
+ },
322
+ inspect: (observerOrFn) => {
323
+ const observer = toObserver(observerOrFn);
324
+ inspectionObservers.add(observer);
325
+ return { unsubscribe() {
326
+ inspectionObservers.delete(observer);
327
+ } };
328
+ },
329
+ _sendInspectionEvent: sendInspectionEvent,
330
+ _relay: (source, target, event) => {
331
+ system._sendInspectionEvent({
332
+ type: "@xstate.event",
333
+ sourceRef: source,
334
+ actorRef: target,
335
+ event
336
+ });
337
+ target._send(event);
338
+ },
339
+ scheduler,
340
+ getSnapshot: () => {
341
+ return { _scheduledEvents: { ...system._snapshot._scheduledEvents } };
342
+ },
343
+ start: () => {
344
+ const scheduledEvents = system._snapshot._scheduledEvents;
345
+ system._snapshot._scheduledEvents = {};
346
+ for (const scheduledId in scheduledEvents) {
347
+ const { source, target, event, delay, id } = scheduledEvents[scheduledId];
348
+ scheduler.schedule(source, target, event, delay, id);
349
+ }
350
+ },
351
+ _clock: clock,
352
+ _logger: logger
353
+ };
354
+ return system;
355
+ }
356
+ let executingCustomAction = false;
357
+ const $$ACTOR_TYPE = 1;
358
+ let ProcessingStatus = /* @__PURE__ */ function(ProcessingStatus$1) {
359
+ ProcessingStatus$1[ProcessingStatus$1["NotStarted"] = 0] = "NotStarted";
360
+ ProcessingStatus$1[ProcessingStatus$1["Running"] = 1] = "Running";
361
+ ProcessingStatus$1[ProcessingStatus$1["Stopped"] = 2] = "Stopped";
362
+ return ProcessingStatus$1;
363
+ }({});
364
+ const defaultOptions = {
365
+ clock: {
366
+ setTimeout: (fn, ms) => {
367
+ return setTimeout(fn, ms);
368
+ },
369
+ clearTimeout: (id) => {
370
+ return clearTimeout(id);
371
+ }
372
+ },
373
+ logger: console.log.bind(console),
374
+ devTools: false
375
+ };
376
+ /**
377
+ * An Actor is a running process that can receive events, send events and change
378
+ * its behavior based on the events it receives, which can cause effects outside
379
+ * of the actor. When you run a state machine, it becomes an actor.
380
+ */
381
+ var Actor = class {
382
+ /**
383
+ * Creates a new actor instance for the given logic with the provided options,
384
+ * if any.
385
+ *
386
+ * @param logic The logic to create an actor from
387
+ * @param options Actor options
388
+ */
389
+ constructor(logic, options) {
390
+ this.logic = logic;
391
+ /** The current internal state of the actor. */
392
+ this._snapshot = void 0;
393
+ /**
394
+ * The clock that is responsible for setting and clearing timeouts, such as
395
+ * delayed events and transitions.
396
+ */
397
+ this.clock = void 0;
398
+ this.options = void 0;
399
+ /** The unique identifier for this actor relative to its parent. */
400
+ this.id = void 0;
401
+ this.mailbox = new Mailbox(this._process.bind(this));
402
+ this.observers = /* @__PURE__ */ new Set();
403
+ this.eventListeners = /* @__PURE__ */ new Map();
404
+ this.logger = void 0;
405
+ /** @internal */
406
+ this._processingStatus = ProcessingStatus.NotStarted;
407
+ this._parent = void 0;
408
+ /** @internal */
409
+ this._syncSnapshot = void 0;
410
+ this.ref = void 0;
411
+ this._actorScope = void 0;
412
+ this.systemId = void 0;
413
+ /** The globally unique process ID for this invocation. */
414
+ this.sessionId = void 0;
415
+ /** The system to which this actor belongs. */
416
+ this.system = void 0;
417
+ this._doneEvent = void 0;
418
+ this.src = void 0;
419
+ this._deferred = [];
420
+ const resolvedOptions = {
421
+ ...defaultOptions,
422
+ ...options
423
+ };
424
+ const { clock, logger, parent, syncSnapshot, id, systemId, inspect } = resolvedOptions;
425
+ this.system = parent ? parent.system : createSystem(this, {
426
+ clock,
427
+ logger
428
+ });
429
+ if (inspect && !parent) this.system.inspect(toObserver(inspect));
430
+ this.sessionId = this.system._bookId();
431
+ this.id = id ?? this.sessionId;
432
+ this.logger = options?.logger ?? this.system._logger;
433
+ this.clock = options?.clock ?? this.system._clock;
434
+ this._parent = parent;
435
+ this._syncSnapshot = syncSnapshot;
436
+ this.options = resolvedOptions;
437
+ this.src = resolvedOptions.src ?? logic;
438
+ this.ref = this;
439
+ this._actorScope = {
440
+ self: this,
441
+ id: this.id,
442
+ sessionId: this.sessionId,
443
+ logger: this.logger,
444
+ defer: (fn) => {
445
+ this._deferred.push(fn);
446
+ },
447
+ system: this.system,
448
+ stopChild: (child) => {
449
+ if (child._parent !== this) throw new Error(`Cannot stop child actor ${child.id} of ${this.id} because it is not a child`);
450
+ child._stop();
451
+ },
452
+ emit: (emittedEvent) => {
453
+ const listeners = this.eventListeners.get(emittedEvent.type);
454
+ const wildcardListener = this.eventListeners.get("*");
455
+ if (!listeners && !wildcardListener) return;
456
+ const allListeners = [...listeners ? listeners.values() : [], ...wildcardListener ? wildcardListener.values() : []];
457
+ for (const handler of allListeners) try {
458
+ handler(emittedEvent);
459
+ } catch (err) {
460
+ reportUnhandledError(err);
461
+ }
462
+ },
463
+ actionExecutor: (action) => {
464
+ const exec = () => {
465
+ this._actorScope.system._sendInspectionEvent({
466
+ type: "@xstate.action",
467
+ actorRef: this,
468
+ action: {
469
+ type: action.type,
470
+ params: action.params
471
+ }
472
+ });
473
+ if (!action.exec) return;
474
+ const saveExecutingCustomAction = executingCustomAction;
475
+ try {
476
+ executingCustomAction = true;
477
+ action.exec(action.info, action.params);
478
+ } finally {
479
+ executingCustomAction = saveExecutingCustomAction;
480
+ }
481
+ };
482
+ if (this._processingStatus === ProcessingStatus.Running) exec();
483
+ else this._deferred.push(exec);
484
+ }
485
+ };
486
+ this.send = this.send.bind(this);
487
+ this.system._sendInspectionEvent({
488
+ type: "@xstate.actor",
489
+ actorRef: this
490
+ });
491
+ if (systemId) {
492
+ this.systemId = systemId;
493
+ this.system._set(systemId, this);
494
+ }
495
+ this._initState(options?.snapshot ?? options?.state);
496
+ if (systemId && this._snapshot.status !== "active") this.system._unregister(this);
497
+ }
498
+ _initState(persistedState) {
499
+ try {
500
+ this._snapshot = persistedState ? this.logic.restoreSnapshot ? this.logic.restoreSnapshot(persistedState, this._actorScope) : persistedState : this.logic.getInitialSnapshot(this._actorScope, this.options?.input);
501
+ } catch (err) {
502
+ this._snapshot = {
503
+ status: "error",
504
+ output: void 0,
505
+ error: err
506
+ };
507
+ }
508
+ }
509
+ update(snapshot, event) {
510
+ this._snapshot = snapshot;
511
+ let deferredFn;
512
+ while (deferredFn = this._deferred.shift()) try {
513
+ deferredFn();
514
+ } catch (err) {
515
+ this._deferred.length = 0;
516
+ this._snapshot = {
517
+ ...snapshot,
518
+ status: "error",
519
+ error: err
520
+ };
521
+ }
522
+ switch (this._snapshot.status) {
523
+ case "active":
524
+ for (const observer of this.observers) try {
525
+ observer.next?.(snapshot);
526
+ } catch (err) {
527
+ reportUnhandledError(err);
528
+ }
529
+ break;
530
+ case "done":
531
+ for (const observer of this.observers) try {
532
+ observer.next?.(snapshot);
533
+ } catch (err) {
534
+ reportUnhandledError(err);
535
+ }
536
+ this._stopProcedure();
537
+ this._complete();
538
+ this._doneEvent = createDoneActorEvent(this.id, this._snapshot.output);
539
+ if (this._parent) this.system._relay(this, this._parent, this._doneEvent);
540
+ break;
541
+ case "error":
542
+ this._error(this._snapshot.error);
543
+ break;
544
+ }
545
+ this.system._sendInspectionEvent({
546
+ type: "@xstate.snapshot",
547
+ actorRef: this,
548
+ event,
549
+ snapshot
550
+ });
551
+ }
552
+ /**
553
+ * Subscribe an observer to an actor’s snapshot values.
554
+ *
555
+ * @remarks
556
+ * The observer will receive the actor’s snapshot value when it is emitted.
557
+ * The observer can be:
558
+ *
559
+ * - A plain function that receives the latest snapshot, or
560
+ * - An observer object whose `.next(snapshot)` method receives the latest
561
+ * snapshot
562
+ *
563
+ * @example
564
+ *
565
+ * ```ts
566
+ * // Observer as a plain function
567
+ * const subscription = actor.subscribe((snapshot) => {
568
+ * console.log(snapshot);
569
+ * });
570
+ * ```
571
+ *
572
+ * @example
573
+ *
574
+ * ```ts
575
+ * // Observer as an object
576
+ * const subscription = actor.subscribe({
577
+ * next(snapshot) {
578
+ * console.log(snapshot);
579
+ * },
580
+ * error(err) {
581
+ * // ...
582
+ * },
583
+ * complete() {
584
+ * // ...
585
+ * }
586
+ * });
587
+ * ```
588
+ *
589
+ * The return value of `actor.subscribe(observer)` is a subscription object
590
+ * that has an `.unsubscribe()` method. You can call
591
+ * `subscription.unsubscribe()` to unsubscribe the observer:
592
+ *
593
+ * @example
594
+ *
595
+ * ```ts
596
+ * const subscription = actor.subscribe((snapshot) => {
597
+ * // ...
598
+ * });
599
+ *
600
+ * // Unsubscribe the observer
601
+ * subscription.unsubscribe();
602
+ * ```
603
+ *
604
+ * When the actor is stopped, all of its observers will automatically be
605
+ * unsubscribed.
606
+ *
607
+ * @param observer - Either a plain function that receives the latest
608
+ * snapshot, or an observer object whose `.next(snapshot)` method receives
609
+ * the latest snapshot
610
+ */
611
+ subscribe(nextListenerOrObserver, errorListener, completeListener) {
612
+ const observer = toObserver(nextListenerOrObserver, errorListener, completeListener);
613
+ if (this._processingStatus !== ProcessingStatus.Stopped) this.observers.add(observer);
614
+ else switch (this._snapshot.status) {
615
+ case "done":
616
+ try {
617
+ observer.complete?.();
618
+ } catch (err) {
619
+ reportUnhandledError(err);
620
+ }
621
+ break;
622
+ case "error": {
623
+ const err = this._snapshot.error;
624
+ if (!observer.error) reportUnhandledError(err);
625
+ else try {
626
+ observer.error(err);
627
+ } catch (err$1) {
628
+ reportUnhandledError(err$1);
629
+ }
630
+ break;
631
+ }
632
+ }
633
+ return { unsubscribe: () => {
634
+ this.observers.delete(observer);
635
+ } };
636
+ }
637
+ on(type, handler) {
638
+ let listeners = this.eventListeners.get(type);
639
+ if (!listeners) {
640
+ listeners = /* @__PURE__ */ new Set();
641
+ this.eventListeners.set(type, listeners);
642
+ }
643
+ const wrappedHandler = handler.bind(void 0);
644
+ listeners.add(wrappedHandler);
645
+ return { unsubscribe: () => {
646
+ listeners.delete(wrappedHandler);
647
+ } };
648
+ }
649
+ /** Starts the Actor from the initial state */
650
+ start() {
651
+ if (this._processingStatus === ProcessingStatus.Running) return this;
652
+ if (this._syncSnapshot) this.subscribe({
653
+ next: (snapshot) => {
654
+ if (snapshot.status === "active") this.system._relay(this, this._parent, {
655
+ type: `xstate.snapshot.${this.id}`,
656
+ snapshot
657
+ });
658
+ },
659
+ error: () => {}
660
+ });
661
+ this.system._register(this.sessionId, this);
662
+ if (this.systemId) this.system._set(this.systemId, this);
663
+ this._processingStatus = ProcessingStatus.Running;
664
+ const initEvent = createInitEvent(this.options.input);
665
+ this.system._sendInspectionEvent({
666
+ type: "@xstate.event",
667
+ sourceRef: this._parent,
668
+ actorRef: this,
669
+ event: initEvent
670
+ });
671
+ switch (this._snapshot.status) {
672
+ case "done":
673
+ this.update(this._snapshot, initEvent);
674
+ return this;
675
+ case "error":
676
+ this._error(this._snapshot.error);
677
+ return this;
678
+ }
679
+ if (!this._parent) this.system.start();
680
+ if (this.logic.start) try {
681
+ this.logic.start(this._snapshot, this._actorScope);
682
+ } catch (err) {
683
+ this._snapshot = {
684
+ ...this._snapshot,
685
+ status: "error",
686
+ error: err
687
+ };
688
+ this._error(err);
689
+ return this;
690
+ }
691
+ this.update(this._snapshot, initEvent);
692
+ if (this.options.devTools) this.attachDevTools();
693
+ this.mailbox.start();
694
+ return this;
695
+ }
696
+ _process(event) {
697
+ let nextState;
698
+ let caughtError;
699
+ try {
700
+ nextState = this.logic.transition(this._snapshot, event, this._actorScope);
701
+ } catch (err) {
702
+ caughtError = { err };
703
+ }
704
+ if (caughtError) {
705
+ const { err } = caughtError;
706
+ this._snapshot = {
707
+ ...this._snapshot,
708
+ status: "error",
709
+ error: err
710
+ };
711
+ this._error(err);
712
+ return;
713
+ }
714
+ this.update(nextState, event);
715
+ if (event.type === XSTATE_STOP) {
716
+ this._stopProcedure();
717
+ this._complete();
718
+ }
719
+ }
720
+ _stop() {
721
+ if (this._processingStatus === ProcessingStatus.Stopped) return this;
722
+ this.mailbox.clear();
723
+ if (this._processingStatus === ProcessingStatus.NotStarted) {
724
+ this._processingStatus = ProcessingStatus.Stopped;
725
+ return this;
726
+ }
727
+ this.mailbox.enqueue({ type: XSTATE_STOP });
728
+ return this;
729
+ }
730
+ /** Stops the Actor and unsubscribe all listeners. */
731
+ stop() {
732
+ if (this._parent) throw new Error("A non-root actor cannot be stopped directly.");
733
+ return this._stop();
734
+ }
735
+ _complete() {
736
+ for (const observer of this.observers) try {
737
+ observer.complete?.();
738
+ } catch (err) {
739
+ reportUnhandledError(err);
740
+ }
741
+ this.observers.clear();
742
+ }
743
+ _reportError(err) {
744
+ if (!this.observers.size) {
745
+ if (!this._parent) reportUnhandledError(err);
746
+ return;
747
+ }
748
+ let reportError = false;
749
+ for (const observer of this.observers) {
750
+ const errorListener = observer.error;
751
+ reportError ||= !errorListener;
752
+ try {
753
+ errorListener?.(err);
754
+ } catch (err2) {
755
+ reportUnhandledError(err2);
756
+ }
757
+ }
758
+ this.observers.clear();
759
+ if (reportError) reportUnhandledError(err);
760
+ }
761
+ _error(err) {
762
+ this._stopProcedure();
763
+ this._reportError(err);
764
+ if (this._parent) this.system._relay(this, this._parent, createErrorActorEvent(this.id, err));
765
+ }
766
+ _stopProcedure() {
767
+ if (this._processingStatus !== ProcessingStatus.Running) return this;
768
+ this.system.scheduler.cancelAll(this);
769
+ this.mailbox.clear();
770
+ this.mailbox = new Mailbox(this._process.bind(this));
771
+ this._processingStatus = ProcessingStatus.Stopped;
772
+ this.system._unregister(this);
773
+ return this;
774
+ }
775
+ /** @internal */
776
+ _send(event) {
777
+ if (this._processingStatus === ProcessingStatus.Stopped) return;
778
+ this.mailbox.enqueue(event);
779
+ }
780
+ /**
781
+ * Sends an event to the running Actor to trigger a transition.
782
+ *
783
+ * @param event The event to send
784
+ */
785
+ send(event) {
786
+ this.system._relay(void 0, this, event);
787
+ }
788
+ attachDevTools() {
789
+ const { devTools } = this.options;
790
+ if (devTools) (typeof devTools === "function" ? devTools : devToolsAdapter)(this);
791
+ }
792
+ toJSON() {
793
+ return {
794
+ xstate$$type: $$ACTOR_TYPE,
795
+ id: this.id
796
+ };
797
+ }
798
+ /**
799
+ * Obtain the internal state of the actor, which can be persisted.
800
+ *
801
+ * @remarks
802
+ * The internal state can be persisted from any actor, not only machines.
803
+ *
804
+ * Note that the persisted state is not the same as the snapshot from
805
+ * {@link Actor.getSnapshot}. Persisted state represents the internal state of
806
+ * the actor, while snapshots represent the actor's last emitted value.
807
+ *
808
+ * Can be restored with {@link ActorOptions.state}
809
+ * @see https://stately.ai/docs/persistence
810
+ */
811
+ getPersistedSnapshot(options) {
812
+ return this.logic.getPersistedSnapshot(this._snapshot, options);
813
+ }
814
+ [symbolObservable]() {
815
+ return this;
816
+ }
817
+ /**
818
+ * Read an actor’s snapshot synchronously.
819
+ *
820
+ * @remarks
821
+ * The snapshot represent an actor's last emitted value.
822
+ *
823
+ * When an actor receives an event, its internal state may change. An actor
824
+ * may emit a snapshot when a state transition occurs.
825
+ *
826
+ * Note that some actors, such as callback actors generated with
827
+ * `fromCallback`, will not emit snapshots.
828
+ * @see {@link Actor.subscribe} to subscribe to an actor’s snapshot values.
829
+ * @see {@link Actor.getPersistedSnapshot} to persist the internal state of an actor (which is more than just a snapshot).
830
+ */
831
+ getSnapshot() {
832
+ return this._snapshot;
833
+ }
834
+ };
835
+ /**
836
+ * Creates a new actor instance for the given actor logic with the provided
837
+ * options, if any.
838
+ *
839
+ * @remarks
840
+ * When you create an actor from actor logic via `createActor(logic)`, you
841
+ * implicitly create an actor system where the created actor is the root actor.
842
+ * Any actors spawned from this root actor and its descendants are part of that
843
+ * actor system.
844
+ * @example
845
+ *
846
+ * ```ts
847
+ * import { createActor } from 'xstate';
848
+ * import { someActorLogic } from './someActorLogic.ts';
849
+ *
850
+ * // Creating the actor, which implicitly creates an actor system with itself as the root actor
851
+ * const actor = createActor(someActorLogic);
852
+ *
853
+ * actor.subscribe((snapshot) => {
854
+ * console.log(snapshot);
855
+ * });
856
+ *
857
+ * // Actors must be started by calling `actor.start()`, which will also start the actor system.
858
+ * actor.start();
859
+ *
860
+ * // Actors can receive events
861
+ * actor.send({ type: 'someEvent' });
862
+ *
863
+ * // You can stop root actors by calling `actor.stop()`, which will also stop the actor system and all actors in that system.
864
+ * actor.stop();
865
+ * ```
866
+ *
867
+ * @param logic - The actor logic to create an actor from. For a state machine
868
+ * actor logic creator, see {@link createMachine}. Other actor logic creators
869
+ * include {@link fromCallback}, {@link fromEventObservable},
870
+ * {@link fromObservable}, {@link fromPromise}, and {@link fromTransition}.
871
+ * @param options - Actor options
872
+ */
873
+ function createActor(logic, ...[options]) {
874
+ return new Actor(logic, options);
875
+ }
876
+ /**
877
+ * @deprecated Use `Actor` instead.
878
+ * @alias
879
+ */
880
+ function resolveCancel(_, snapshot, actionArgs, actionParams, { sendId }) {
881
+ return [
882
+ snapshot,
883
+ { sendId: typeof sendId === "function" ? sendId(actionArgs, actionParams) : sendId },
884
+ void 0
885
+ ];
886
+ }
887
+ function executeCancel(actorScope, params) {
888
+ actorScope.defer(() => {
889
+ actorScope.system.scheduler.cancel(actorScope.self, params.sendId);
890
+ });
891
+ }
892
+ /**
893
+ * Cancels a delayed `sendTo(...)` action that is waiting to be executed. The
894
+ * canceled `sendTo(...)` action will not send its event or execute, unless the
895
+ * `delay` has already elapsed before `cancel(...)` is called.
896
+ *
897
+ * @example
898
+ *
899
+ * ```ts
900
+ * import { createMachine, sendTo, cancel } from 'xstate';
901
+ *
902
+ * const machine = createMachine({
903
+ * // ...
904
+ * on: {
905
+ * sendEvent: {
906
+ * actions: sendTo(
907
+ * 'some-actor',
908
+ * { type: 'someEvent' },
909
+ * {
910
+ * id: 'some-id',
911
+ * delay: 1000
912
+ * }
913
+ * )
914
+ * },
915
+ * cancelEvent: {
916
+ * actions: cancel('some-id')
917
+ * }
918
+ * }
919
+ * });
920
+ * ```
921
+ *
922
+ * @param sendId The `id` of the `sendTo(...)` action to cancel.
923
+ */
924
+ function cancel(sendId) {
925
+ function cancel$1(_args, _params) {}
926
+ cancel$1.type = "xstate.cancel";
927
+ cancel$1.sendId = sendId;
928
+ cancel$1.resolve = resolveCancel;
929
+ cancel$1.execute = executeCancel;
930
+ return cancel$1;
931
+ }
932
+ function resolveSpawn(actorScope, snapshot, actionArgs, _actionParams, { id, systemId, src, input, syncSnapshot }) {
933
+ const logic = typeof src === "string" ? resolveReferencedActor(snapshot.machine, src) : src;
934
+ const resolvedId = typeof id === "function" ? id(actionArgs) : id;
935
+ let actorRef;
936
+ let resolvedInput = void 0;
937
+ if (logic) {
938
+ resolvedInput = typeof input === "function" ? input({
939
+ context: snapshot.context,
940
+ event: actionArgs.event,
941
+ self: actorScope.self
942
+ }) : input;
943
+ actorRef = createActor(logic, {
944
+ id: resolvedId,
945
+ src,
946
+ parent: actorScope.self,
947
+ syncSnapshot,
948
+ systemId,
949
+ input: resolvedInput
950
+ });
951
+ }
952
+ return [
953
+ cloneMachineSnapshot(snapshot, { children: {
954
+ ...snapshot.children,
955
+ [resolvedId]: actorRef
956
+ } }),
957
+ {
958
+ id,
959
+ systemId,
960
+ actorRef,
961
+ src,
962
+ input: resolvedInput
963
+ },
964
+ void 0
965
+ ];
966
+ }
967
+ function executeSpawn(actorScope, { actorRef }) {
968
+ if (!actorRef) return;
969
+ actorScope.defer(() => {
970
+ if (actorRef._processingStatus === ProcessingStatus.Stopped) return;
971
+ actorRef.start();
972
+ });
973
+ }
974
+ function spawnChild(...[src, { id, systemId, input, syncSnapshot = false } = {}]) {
975
+ function spawnChild$1(_args, _params) {}
976
+ spawnChild$1.type = "xstate.spawnChild";
977
+ spawnChild$1.id = id;
978
+ spawnChild$1.systemId = systemId;
979
+ spawnChild$1.src = src;
980
+ spawnChild$1.input = input;
981
+ spawnChild$1.syncSnapshot = syncSnapshot;
982
+ spawnChild$1.resolve = resolveSpawn;
983
+ spawnChild$1.execute = executeSpawn;
984
+ return spawnChild$1;
985
+ }
986
+ function resolveStop(_, snapshot, args, actionParams, { actorRef }) {
987
+ const actorRefOrString = typeof actorRef === "function" ? actorRef(args, actionParams) : actorRef;
988
+ const resolvedActorRef = typeof actorRefOrString === "string" ? snapshot.children[actorRefOrString] : actorRefOrString;
989
+ let children = snapshot.children;
990
+ if (resolvedActorRef) {
991
+ children = { ...children };
992
+ delete children[resolvedActorRef.id];
993
+ }
994
+ return [
995
+ cloneMachineSnapshot(snapshot, { children }),
996
+ resolvedActorRef,
997
+ void 0
998
+ ];
999
+ }
1000
+ function executeStop(actorScope, actorRef) {
1001
+ if (!actorRef) return;
1002
+ actorScope.system._unregister(actorRef);
1003
+ if (actorRef._processingStatus !== ProcessingStatus.Running) {
1004
+ actorScope.stopChild(actorRef);
1005
+ return;
1006
+ }
1007
+ actorScope.defer(() => {
1008
+ actorScope.stopChild(actorRef);
1009
+ });
1010
+ }
1011
+ /**
1012
+ * Stops a child actor.
1013
+ *
1014
+ * @param actorRef The actor to stop.
1015
+ */
1016
+ function stopChild(actorRef) {
1017
+ function stop$1(_args, _params) {}
1018
+ stop$1.type = "xstate.stopChild";
1019
+ stop$1.actorRef = actorRef;
1020
+ stop$1.resolve = resolveStop;
1021
+ stop$1.execute = executeStop;
1022
+ return stop$1;
1023
+ }
1024
+ function evaluateGuard(guard, context, event, snapshot) {
1025
+ const { machine } = snapshot;
1026
+ const isInline = typeof guard === "function";
1027
+ const resolved = isInline ? guard : machine.implementations.guards[typeof guard === "string" ? guard : guard.type];
1028
+ if (!isInline && !resolved) throw new Error(`Guard '${typeof guard === "string" ? guard : guard.type}' is not implemented.'.`);
1029
+ if (typeof resolved !== "function") return evaluateGuard(resolved, context, event, snapshot);
1030
+ const guardArgs = {
1031
+ context,
1032
+ event
1033
+ };
1034
+ const guardParams = isInline || typeof guard === "string" ? void 0 : "params" in guard ? typeof guard.params === "function" ? guard.params({
1035
+ context,
1036
+ event
1037
+ }) : guard.params : void 0;
1038
+ if (!("check" in resolved)) return resolved(guardArgs, guardParams);
1039
+ return resolved.check(snapshot, guardArgs, resolved);
1040
+ }
1041
+ const isAtomicStateNode = (stateNode) => stateNode.type === "atomic" || stateNode.type === "final";
1042
+ function getChildren(stateNode) {
1043
+ return Object.values(stateNode.states).filter((sn) => sn.type !== "history");
1044
+ }
1045
+ function getProperAncestors(stateNode, toStateNode) {
1046
+ const ancestors = [];
1047
+ if (toStateNode === stateNode) return ancestors;
1048
+ let m = stateNode.parent;
1049
+ while (m && m !== toStateNode) {
1050
+ ancestors.push(m);
1051
+ m = m.parent;
1052
+ }
1053
+ return ancestors;
1054
+ }
1055
+ function getAllStateNodes(stateNodes) {
1056
+ const nodeSet = new Set(stateNodes);
1057
+ const adjList = getAdjList(nodeSet);
1058
+ for (const s of nodeSet) if (s.type === "compound" && (!adjList.get(s) || !adjList.get(s).length)) getInitialStateNodesWithTheirAncestors(s).forEach((sn) => nodeSet.add(sn));
1059
+ else if (s.type === "parallel") for (const child of getChildren(s)) {
1060
+ if (child.type === "history") continue;
1061
+ if (!nodeSet.has(child)) {
1062
+ const initialStates = getInitialStateNodesWithTheirAncestors(child);
1063
+ for (const initialStateNode of initialStates) nodeSet.add(initialStateNode);
1064
+ }
1065
+ }
1066
+ for (const s of nodeSet) {
1067
+ let m = s.parent;
1068
+ while (m) {
1069
+ nodeSet.add(m);
1070
+ m = m.parent;
1071
+ }
1072
+ }
1073
+ return nodeSet;
1074
+ }
1075
+ function getValueFromAdj(baseNode, adjList) {
1076
+ const childStateNodes = adjList.get(baseNode);
1077
+ if (!childStateNodes) return {};
1078
+ if (baseNode.type === "compound") {
1079
+ const childStateNode = childStateNodes[0];
1080
+ if (childStateNode) {
1081
+ if (isAtomicStateNode(childStateNode)) return childStateNode.key;
1082
+ } else return {};
1083
+ }
1084
+ const stateValue = {};
1085
+ for (const childStateNode of childStateNodes) stateValue[childStateNode.key] = getValueFromAdj(childStateNode, adjList);
1086
+ return stateValue;
1087
+ }
1088
+ function getAdjList(stateNodes) {
1089
+ const adjList = /* @__PURE__ */ new Map();
1090
+ for (const s of stateNodes) {
1091
+ if (!adjList.has(s)) adjList.set(s, []);
1092
+ if (s.parent) {
1093
+ if (!adjList.has(s.parent)) adjList.set(s.parent, []);
1094
+ adjList.get(s.parent).push(s);
1095
+ }
1096
+ }
1097
+ return adjList;
1098
+ }
1099
+ function getStateValue(rootNode, stateNodes) {
1100
+ return getValueFromAdj(rootNode, getAdjList(getAllStateNodes(stateNodes)));
1101
+ }
1102
+ function isInFinalState(stateNodeSet, stateNode) {
1103
+ if (stateNode.type === "compound") return getChildren(stateNode).some((s) => s.type === "final" && stateNodeSet.has(s));
1104
+ if (stateNode.type === "parallel") return getChildren(stateNode).every((sn) => isInFinalState(stateNodeSet, sn));
1105
+ return stateNode.type === "final";
1106
+ }
1107
+ const isStateId = (str) => str[0] === STATE_IDENTIFIER;
1108
+ function getCandidates(stateNode, receivedEventType) {
1109
+ return stateNode.transitions.get(receivedEventType) || [...stateNode.transitions.keys()].filter((eventDescriptor) => {
1110
+ if (eventDescriptor === WILDCARD) return true;
1111
+ if (!eventDescriptor.endsWith(".*")) return false;
1112
+ const partialEventTokens = eventDescriptor.split(".");
1113
+ const eventTokens = receivedEventType.split(".");
1114
+ for (let tokenIndex = 0; tokenIndex < partialEventTokens.length; tokenIndex++) {
1115
+ const partialEventToken = partialEventTokens[tokenIndex];
1116
+ const eventToken = eventTokens[tokenIndex];
1117
+ if (partialEventToken === "*") return tokenIndex === partialEventTokens.length - 1;
1118
+ if (partialEventToken !== eventToken) return false;
1119
+ }
1120
+ return true;
1121
+ }).sort((a, b) => b.length - a.length).flatMap((key) => stateNode.transitions.get(key));
1122
+ }
1123
+ /** All delayed transitions from the config. */
1124
+ function getDelayedTransitions(stateNode) {
1125
+ const afterConfig = stateNode.config.after;
1126
+ if (!afterConfig) return [];
1127
+ const mutateEntryExit = (delay) => {
1128
+ const afterEvent = createAfterEvent(delay, stateNode.id);
1129
+ const eventType = afterEvent.type;
1130
+ stateNode.entry.push(raise(afterEvent, {
1131
+ id: eventType,
1132
+ delay
1133
+ }));
1134
+ stateNode.exit.push(cancel(eventType));
1135
+ return eventType;
1136
+ };
1137
+ return Object.keys(afterConfig).flatMap((delay) => {
1138
+ const configTransition = afterConfig[delay];
1139
+ const resolvedTransition = typeof configTransition === "string" ? { target: configTransition } : configTransition;
1140
+ const resolvedDelay = Number.isNaN(+delay) ? delay : +delay;
1141
+ const eventType = mutateEntryExit(resolvedDelay);
1142
+ return toArray(resolvedTransition).map((transition) => ({
1143
+ ...transition,
1144
+ event: eventType,
1145
+ delay: resolvedDelay
1146
+ }));
1147
+ }).map((delayedTransition) => {
1148
+ const { delay } = delayedTransition;
1149
+ return {
1150
+ ...formatTransition(stateNode, delayedTransition.event, delayedTransition),
1151
+ delay
1152
+ };
1153
+ });
1154
+ }
1155
+ function formatTransition(stateNode, descriptor, transitionConfig) {
1156
+ const normalizedTarget = normalizeTarget(transitionConfig.target);
1157
+ const reenter = transitionConfig.reenter ?? false;
1158
+ const target = resolveTarget(stateNode, normalizedTarget);
1159
+ const transition = {
1160
+ ...transitionConfig,
1161
+ actions: toArray(transitionConfig.actions),
1162
+ guard: transitionConfig.guard,
1163
+ target,
1164
+ source: stateNode,
1165
+ reenter,
1166
+ eventType: descriptor,
1167
+ toJSON: () => ({
1168
+ ...transition,
1169
+ source: `#${stateNode.id}`,
1170
+ target: target ? target.map((t) => `#${t.id}`) : void 0
1171
+ })
1172
+ };
1173
+ return transition;
1174
+ }
1175
+ function formatTransitions(stateNode) {
1176
+ const transitions = /* @__PURE__ */ new Map();
1177
+ if (stateNode.config.on) for (const descriptor of Object.keys(stateNode.config.on)) {
1178
+ if (descriptor === NULL_EVENT) throw new Error("Null events (\"\") cannot be specified as a transition key. Use `always: { ... }` instead.");
1179
+ const transitionsConfig = stateNode.config.on[descriptor];
1180
+ transitions.set(descriptor, toTransitionConfigArray(transitionsConfig).map((t) => formatTransition(stateNode, descriptor, t)));
1181
+ }
1182
+ if (stateNode.config.onDone) {
1183
+ const descriptor = `xstate.done.state.${stateNode.id}`;
1184
+ transitions.set(descriptor, toTransitionConfigArray(stateNode.config.onDone).map((t) => formatTransition(stateNode, descriptor, t)));
1185
+ }
1186
+ for (const invokeDef of stateNode.invoke) {
1187
+ if (invokeDef.onDone) {
1188
+ const descriptor = `xstate.done.actor.${invokeDef.id}`;
1189
+ transitions.set(descriptor, toTransitionConfigArray(invokeDef.onDone).map((t) => formatTransition(stateNode, descriptor, t)));
1190
+ }
1191
+ if (invokeDef.onError) {
1192
+ const descriptor = `xstate.error.actor.${invokeDef.id}`;
1193
+ transitions.set(descriptor, toTransitionConfigArray(invokeDef.onError).map((t) => formatTransition(stateNode, descriptor, t)));
1194
+ }
1195
+ if (invokeDef.onSnapshot) {
1196
+ const descriptor = `xstate.snapshot.${invokeDef.id}`;
1197
+ transitions.set(descriptor, toTransitionConfigArray(invokeDef.onSnapshot).map((t) => formatTransition(stateNode, descriptor, t)));
1198
+ }
1199
+ }
1200
+ for (const delayedTransition of stateNode.after) {
1201
+ let existing = transitions.get(delayedTransition.eventType);
1202
+ if (!existing) {
1203
+ existing = [];
1204
+ transitions.set(delayedTransition.eventType, existing);
1205
+ }
1206
+ existing.push(delayedTransition);
1207
+ }
1208
+ return transitions;
1209
+ }
1210
+ function formatInitialTransition(stateNode, _target) {
1211
+ const resolvedTarget = typeof _target === "string" ? stateNode.states[_target] : _target ? stateNode.states[_target.target] : void 0;
1212
+ if (!resolvedTarget && _target) throw new Error(`Initial state node "${_target}" not found on parent state node #${stateNode.id}`);
1213
+ const transition = {
1214
+ source: stateNode,
1215
+ actions: !_target || typeof _target === "string" ? [] : toArray(_target.actions),
1216
+ eventType: null,
1217
+ reenter: false,
1218
+ target: resolvedTarget ? [resolvedTarget] : [],
1219
+ toJSON: () => ({
1220
+ ...transition,
1221
+ source: `#${stateNode.id}`,
1222
+ target: resolvedTarget ? [`#${resolvedTarget.id}`] : []
1223
+ })
1224
+ };
1225
+ return transition;
1226
+ }
1227
+ function resolveTarget(stateNode, targets) {
1228
+ if (targets === void 0) return;
1229
+ return targets.map((target) => {
1230
+ if (typeof target !== "string") return target;
1231
+ if (isStateId(target)) return stateNode.machine.getStateNodeById(target);
1232
+ const isInternalTarget = target[0] === STATE_DELIMITER;
1233
+ if (isInternalTarget && !stateNode.parent) return getStateNodeByPath(stateNode, target.slice(1));
1234
+ const resolvedTarget = isInternalTarget ? stateNode.key + target : target;
1235
+ if (stateNode.parent) try {
1236
+ return getStateNodeByPath(stateNode.parent, resolvedTarget);
1237
+ } catch (err) {
1238
+ throw new Error(`Invalid transition definition for state node '${stateNode.id}':\n${err.message}`);
1239
+ }
1240
+ else throw new Error(`Invalid target: "${target}" is not a valid target from the root node. Did you mean ".${target}"?`);
1241
+ });
1242
+ }
1243
+ function resolveHistoryDefaultTransition(stateNode) {
1244
+ const normalizedTarget = normalizeTarget(stateNode.config.target);
1245
+ if (!normalizedTarget) return stateNode.parent.initial;
1246
+ return { target: normalizedTarget.map((t) => typeof t === "string" ? getStateNodeByPath(stateNode.parent, t) : t) };
1247
+ }
1248
+ function isHistoryNode(stateNode) {
1249
+ return stateNode.type === "history";
1250
+ }
1251
+ function getInitialStateNodesWithTheirAncestors(stateNode) {
1252
+ const states = getInitialStateNodes(stateNode);
1253
+ for (const initialState of states) for (const ancestor of getProperAncestors(initialState, stateNode)) states.add(ancestor);
1254
+ return states;
1255
+ }
1256
+ function getInitialStateNodes(stateNode) {
1257
+ const set = /* @__PURE__ */ new Set();
1258
+ function iter(descStateNode) {
1259
+ if (set.has(descStateNode)) return;
1260
+ set.add(descStateNode);
1261
+ if (descStateNode.type === "compound") iter(descStateNode.initial.target[0]);
1262
+ else if (descStateNode.type === "parallel") for (const child of getChildren(descStateNode)) iter(child);
1263
+ }
1264
+ iter(stateNode);
1265
+ return set;
1266
+ }
1267
+ /** Returns the child state node from its relative `stateKey`, or throws. */
1268
+ function getStateNode(stateNode, stateKey) {
1269
+ if (isStateId(stateKey)) return stateNode.machine.getStateNodeById(stateKey);
1270
+ if (!stateNode.states) throw new Error(`Unable to retrieve child state '${stateKey}' from '${stateNode.id}'; no child states exist.`);
1271
+ const result = stateNode.states[stateKey];
1272
+ if (!result) throw new Error(`Child state '${stateKey}' does not exist on '${stateNode.id}'`);
1273
+ return result;
1274
+ }
1275
+ /**
1276
+ * Returns the relative state node from the given `statePath`, or throws.
1277
+ *
1278
+ * @param statePath The string or string array relative path to the state node.
1279
+ */
1280
+ function getStateNodeByPath(stateNode, statePath) {
1281
+ if (typeof statePath === "string" && isStateId(statePath)) try {
1282
+ return stateNode.machine.getStateNodeById(statePath);
1283
+ } catch {}
1284
+ const arrayStatePath = toStatePath(statePath).slice();
1285
+ let currentStateNode = stateNode;
1286
+ while (arrayStatePath.length) {
1287
+ const key = arrayStatePath.shift();
1288
+ if (!key.length) break;
1289
+ currentStateNode = getStateNode(currentStateNode, key);
1290
+ }
1291
+ return currentStateNode;
1292
+ }
1293
+ /**
1294
+ * Returns the state nodes represented by the current state value.
1295
+ *
1296
+ * @param stateValue The state value or State instance
1297
+ */
1298
+ function getStateNodes(stateNode, stateValue) {
1299
+ if (typeof stateValue === "string") {
1300
+ const childStateNode = stateNode.states[stateValue];
1301
+ if (!childStateNode) throw new Error(`State '${stateValue}' does not exist on '${stateNode.id}'`);
1302
+ return [stateNode, childStateNode];
1303
+ }
1304
+ const childStateKeys = Object.keys(stateValue);
1305
+ const childStateNodes = childStateKeys.map((subStateKey) => getStateNode(stateNode, subStateKey)).filter(Boolean);
1306
+ return [stateNode.machine.root, stateNode].concat(childStateNodes, childStateKeys.reduce((allSubStateNodes, subStateKey) => {
1307
+ const subStateNode = getStateNode(stateNode, subStateKey);
1308
+ if (!subStateNode) return allSubStateNodes;
1309
+ const subStateNodes = getStateNodes(subStateNode, stateValue[subStateKey]);
1310
+ return allSubStateNodes.concat(subStateNodes);
1311
+ }, []));
1312
+ }
1313
+ function transitionAtomicNode(stateNode, stateValue, snapshot, event) {
1314
+ const next = getStateNode(stateNode, stateValue).next(snapshot, event);
1315
+ if (!next || !next.length) return stateNode.next(snapshot, event);
1316
+ return next;
1317
+ }
1318
+ function transitionCompoundNode(stateNode, stateValue, snapshot, event) {
1319
+ const subStateKeys = Object.keys(stateValue);
1320
+ const next = transitionNode(getStateNode(stateNode, subStateKeys[0]), stateValue[subStateKeys[0]], snapshot, event);
1321
+ if (!next || !next.length) return stateNode.next(snapshot, event);
1322
+ return next;
1323
+ }
1324
+ function transitionParallelNode(stateNode, stateValue, snapshot, event) {
1325
+ const allInnerTransitions = [];
1326
+ for (const subStateKey of Object.keys(stateValue)) {
1327
+ const subStateValue = stateValue[subStateKey];
1328
+ if (!subStateValue) continue;
1329
+ const innerTransitions = transitionNode(getStateNode(stateNode, subStateKey), subStateValue, snapshot, event);
1330
+ if (innerTransitions) allInnerTransitions.push(...innerTransitions);
1331
+ }
1332
+ if (!allInnerTransitions.length) return stateNode.next(snapshot, event);
1333
+ return allInnerTransitions;
1334
+ }
1335
+ function transitionNode(stateNode, stateValue, snapshot, event) {
1336
+ if (typeof stateValue === "string") return transitionAtomicNode(stateNode, stateValue, snapshot, event);
1337
+ if (Object.keys(stateValue).length === 1) return transitionCompoundNode(stateNode, stateValue, snapshot, event);
1338
+ return transitionParallelNode(stateNode, stateValue, snapshot, event);
1339
+ }
1340
+ function getHistoryNodes(stateNode) {
1341
+ return Object.keys(stateNode.states).map((key) => stateNode.states[key]).filter((sn) => sn.type === "history");
1342
+ }
1343
+ function isDescendant(childStateNode, parentStateNode) {
1344
+ let marker = childStateNode;
1345
+ while (marker.parent && marker.parent !== parentStateNode) marker = marker.parent;
1346
+ return marker.parent === parentStateNode;
1347
+ }
1348
+ function hasIntersection(s1, s2) {
1349
+ const set1 = new Set(s1);
1350
+ const set2 = new Set(s2);
1351
+ for (const item of set1) if (set2.has(item)) return true;
1352
+ for (const item of set2) if (set1.has(item)) return true;
1353
+ return false;
1354
+ }
1355
+ function removeConflictingTransitions(enabledTransitions, stateNodeSet, historyValue) {
1356
+ const filteredTransitions = /* @__PURE__ */ new Set();
1357
+ for (const t1 of enabledTransitions) {
1358
+ let t1Preempted = false;
1359
+ const transitionsToRemove = /* @__PURE__ */ new Set();
1360
+ for (const t2 of filteredTransitions) if (hasIntersection(computeExitSet([t1], stateNodeSet, historyValue), computeExitSet([t2], stateNodeSet, historyValue))) if (isDescendant(t1.source, t2.source)) transitionsToRemove.add(t2);
1361
+ else {
1362
+ t1Preempted = true;
1363
+ break;
1364
+ }
1365
+ if (!t1Preempted) {
1366
+ for (const t3 of transitionsToRemove) filteredTransitions.delete(t3);
1367
+ filteredTransitions.add(t1);
1368
+ }
1369
+ }
1370
+ return Array.from(filteredTransitions);
1371
+ }
1372
+ function findLeastCommonAncestor(stateNodes) {
1373
+ const [head, ...tail] = stateNodes;
1374
+ for (const ancestor of getProperAncestors(head, void 0)) if (tail.every((sn) => isDescendant(sn, ancestor))) return ancestor;
1375
+ }
1376
+ function getEffectiveTargetStates(transition, historyValue) {
1377
+ if (!transition.target) return [];
1378
+ const targets = /* @__PURE__ */ new Set();
1379
+ for (const targetNode of transition.target) if (isHistoryNode(targetNode)) if (historyValue[targetNode.id]) for (const node of historyValue[targetNode.id]) targets.add(node);
1380
+ else for (const node of getEffectiveTargetStates(resolveHistoryDefaultTransition(targetNode), historyValue)) targets.add(node);
1381
+ else targets.add(targetNode);
1382
+ return [...targets];
1383
+ }
1384
+ function getTransitionDomain(transition, historyValue) {
1385
+ const targetStates = getEffectiveTargetStates(transition, historyValue);
1386
+ if (!targetStates) return;
1387
+ if (!transition.reenter && targetStates.every((target) => target === transition.source || isDescendant(target, transition.source))) return transition.source;
1388
+ const lca = findLeastCommonAncestor(targetStates.concat(transition.source));
1389
+ if (lca) return lca;
1390
+ if (transition.reenter) return;
1391
+ return transition.source.machine.root;
1392
+ }
1393
+ function computeExitSet(transitions, stateNodeSet, historyValue) {
1394
+ const statesToExit = /* @__PURE__ */ new Set();
1395
+ for (const t of transitions) if (t.target?.length) {
1396
+ const domain = getTransitionDomain(t, historyValue);
1397
+ if (t.reenter && t.source === domain) statesToExit.add(domain);
1398
+ for (const stateNode of stateNodeSet) if (isDescendant(stateNode, domain)) statesToExit.add(stateNode);
1399
+ }
1400
+ return [...statesToExit];
1401
+ }
1402
+ function areStateNodeCollectionsEqual(prevStateNodes, nextStateNodeSet) {
1403
+ if (prevStateNodes.length !== nextStateNodeSet.size) return false;
1404
+ for (const node of prevStateNodes) if (!nextStateNodeSet.has(node)) return false;
1405
+ return true;
1406
+ }
1407
+ /** https://www.w3.org/TR/scxml/#microstepProcedure */
1408
+ function microstep(transitions, currentSnapshot, actorScope, event, isInitial, internalQueue) {
1409
+ if (!transitions.length) return currentSnapshot;
1410
+ const mutStateNodeSet = new Set(currentSnapshot._nodes);
1411
+ let historyValue = currentSnapshot.historyValue;
1412
+ const filteredTransitions = removeConflictingTransitions(transitions, mutStateNodeSet, historyValue);
1413
+ let nextState = currentSnapshot;
1414
+ if (!isInitial) [nextState, historyValue] = exitStates(nextState, event, actorScope, filteredTransitions, mutStateNodeSet, historyValue, internalQueue, actorScope.actionExecutor);
1415
+ nextState = resolveActionsAndContext(nextState, event, actorScope, filteredTransitions.flatMap((t) => t.actions), internalQueue, void 0);
1416
+ nextState = enterStates(nextState, event, actorScope, filteredTransitions, mutStateNodeSet, internalQueue, historyValue, isInitial);
1417
+ const nextStateNodes = [...mutStateNodeSet];
1418
+ if (nextState.status === "done") nextState = resolveActionsAndContext(nextState, event, actorScope, nextStateNodes.sort((a, b) => b.order - a.order).flatMap((state) => state.exit), internalQueue, void 0);
1419
+ try {
1420
+ if (historyValue === currentSnapshot.historyValue && areStateNodeCollectionsEqual(currentSnapshot._nodes, mutStateNodeSet)) return nextState;
1421
+ return cloneMachineSnapshot(nextState, {
1422
+ _nodes: nextStateNodes,
1423
+ historyValue
1424
+ });
1425
+ } catch (e) {
1426
+ throw e;
1427
+ }
1428
+ }
1429
+ function getMachineOutput(snapshot, event, actorScope, rootNode, rootCompletionNode) {
1430
+ if (rootNode.output === void 0) return;
1431
+ const doneStateEvent = createDoneStateEvent(rootCompletionNode.id, rootCompletionNode.output !== void 0 && rootCompletionNode.parent ? resolveOutput(rootCompletionNode.output, snapshot.context, event, actorScope.self) : void 0);
1432
+ return resolveOutput(rootNode.output, snapshot.context, doneStateEvent, actorScope.self);
1433
+ }
1434
+ function enterStates(currentSnapshot, event, actorScope, filteredTransitions, mutStateNodeSet, internalQueue, historyValue, isInitial) {
1435
+ let nextSnapshot = currentSnapshot;
1436
+ const statesToEnter = /* @__PURE__ */ new Set();
1437
+ const statesForDefaultEntry = /* @__PURE__ */ new Set();
1438
+ computeEntrySet(filteredTransitions, historyValue, statesForDefaultEntry, statesToEnter);
1439
+ if (isInitial) statesForDefaultEntry.add(currentSnapshot.machine.root);
1440
+ const completedNodes = /* @__PURE__ */ new Set();
1441
+ for (const stateNodeToEnter of [...statesToEnter].sort((a, b) => a.order - b.order)) {
1442
+ mutStateNodeSet.add(stateNodeToEnter);
1443
+ const actions = [];
1444
+ actions.push(...stateNodeToEnter.entry);
1445
+ for (const invokeDef of stateNodeToEnter.invoke) actions.push(spawnChild(invokeDef.src, {
1446
+ ...invokeDef,
1447
+ syncSnapshot: !!invokeDef.onSnapshot
1448
+ }));
1449
+ if (statesForDefaultEntry.has(stateNodeToEnter)) {
1450
+ const initialActions = stateNodeToEnter.initial.actions;
1451
+ actions.push(...initialActions);
1452
+ }
1453
+ nextSnapshot = resolveActionsAndContext(nextSnapshot, event, actorScope, actions, internalQueue, stateNodeToEnter.invoke.map((invokeDef) => invokeDef.id));
1454
+ if (stateNodeToEnter.type === "final") {
1455
+ const parent = stateNodeToEnter.parent;
1456
+ let ancestorMarker = parent?.type === "parallel" ? parent : parent?.parent;
1457
+ let rootCompletionNode = ancestorMarker || stateNodeToEnter;
1458
+ if (parent?.type === "compound") internalQueue.push(createDoneStateEvent(parent.id, stateNodeToEnter.output !== void 0 ? resolveOutput(stateNodeToEnter.output, nextSnapshot.context, event, actorScope.self) : void 0));
1459
+ while (ancestorMarker?.type === "parallel" && !completedNodes.has(ancestorMarker) && isInFinalState(mutStateNodeSet, ancestorMarker)) {
1460
+ completedNodes.add(ancestorMarker);
1461
+ internalQueue.push(createDoneStateEvent(ancestorMarker.id));
1462
+ rootCompletionNode = ancestorMarker;
1463
+ ancestorMarker = ancestorMarker.parent;
1464
+ }
1465
+ if (ancestorMarker) continue;
1466
+ nextSnapshot = cloneMachineSnapshot(nextSnapshot, {
1467
+ status: "done",
1468
+ output: getMachineOutput(nextSnapshot, event, actorScope, nextSnapshot.machine.root, rootCompletionNode)
1469
+ });
1470
+ }
1471
+ }
1472
+ return nextSnapshot;
1473
+ }
1474
+ function computeEntrySet(transitions, historyValue, statesForDefaultEntry, statesToEnter) {
1475
+ for (const t of transitions) {
1476
+ const domain = getTransitionDomain(t, historyValue);
1477
+ for (const s of t.target || []) {
1478
+ if (!isHistoryNode(s) && (t.source !== s || t.source !== domain || t.reenter)) {
1479
+ statesToEnter.add(s);
1480
+ statesForDefaultEntry.add(s);
1481
+ }
1482
+ addDescendantStatesToEnter(s, historyValue, statesForDefaultEntry, statesToEnter);
1483
+ }
1484
+ const targetStates = getEffectiveTargetStates(t, historyValue);
1485
+ for (const s of targetStates) {
1486
+ const ancestors = getProperAncestors(s, domain);
1487
+ if (domain?.type === "parallel") ancestors.push(domain);
1488
+ addAncestorStatesToEnter(statesToEnter, historyValue, statesForDefaultEntry, ancestors, !t.source.parent && t.reenter ? void 0 : domain);
1489
+ }
1490
+ }
1491
+ }
1492
+ function addDescendantStatesToEnter(stateNode, historyValue, statesForDefaultEntry, statesToEnter) {
1493
+ if (isHistoryNode(stateNode)) if (historyValue[stateNode.id]) {
1494
+ const historyStateNodes = historyValue[stateNode.id];
1495
+ for (const s of historyStateNodes) {
1496
+ statesToEnter.add(s);
1497
+ addDescendantStatesToEnter(s, historyValue, statesForDefaultEntry, statesToEnter);
1498
+ }
1499
+ for (const s of historyStateNodes) addProperAncestorStatesToEnter(s, stateNode.parent, statesToEnter, historyValue, statesForDefaultEntry);
1500
+ } else {
1501
+ const historyDefaultTransition = resolveHistoryDefaultTransition(stateNode);
1502
+ for (const s of historyDefaultTransition.target) {
1503
+ statesToEnter.add(s);
1504
+ if (historyDefaultTransition === stateNode.parent?.initial) statesForDefaultEntry.add(stateNode.parent);
1505
+ addDescendantStatesToEnter(s, historyValue, statesForDefaultEntry, statesToEnter);
1506
+ }
1507
+ for (const s of historyDefaultTransition.target) addProperAncestorStatesToEnter(s, stateNode.parent, statesToEnter, historyValue, statesForDefaultEntry);
1508
+ }
1509
+ else if (stateNode.type === "compound") {
1510
+ const [initialState] = stateNode.initial.target;
1511
+ if (!isHistoryNode(initialState)) {
1512
+ statesToEnter.add(initialState);
1513
+ statesForDefaultEntry.add(initialState);
1514
+ }
1515
+ addDescendantStatesToEnter(initialState, historyValue, statesForDefaultEntry, statesToEnter);
1516
+ addProperAncestorStatesToEnter(initialState, stateNode, statesToEnter, historyValue, statesForDefaultEntry);
1517
+ } else if (stateNode.type === "parallel") {
1518
+ for (const child of getChildren(stateNode).filter((sn) => !isHistoryNode(sn))) if (![...statesToEnter].some((s) => isDescendant(s, child))) {
1519
+ if (!isHistoryNode(child)) {
1520
+ statesToEnter.add(child);
1521
+ statesForDefaultEntry.add(child);
1522
+ }
1523
+ addDescendantStatesToEnter(child, historyValue, statesForDefaultEntry, statesToEnter);
1524
+ }
1525
+ }
1526
+ }
1527
+ function addAncestorStatesToEnter(statesToEnter, historyValue, statesForDefaultEntry, ancestors, reentrancyDomain) {
1528
+ for (const anc of ancestors) {
1529
+ if (!reentrancyDomain || isDescendant(anc, reentrancyDomain)) statesToEnter.add(anc);
1530
+ if (anc.type === "parallel") {
1531
+ for (const child of getChildren(anc).filter((sn) => !isHistoryNode(sn))) if (![...statesToEnter].some((s) => isDescendant(s, child))) {
1532
+ statesToEnter.add(child);
1533
+ addDescendantStatesToEnter(child, historyValue, statesForDefaultEntry, statesToEnter);
1534
+ }
1535
+ }
1536
+ }
1537
+ }
1538
+ function addProperAncestorStatesToEnter(stateNode, toStateNode, statesToEnter, historyValue, statesForDefaultEntry) {
1539
+ addAncestorStatesToEnter(statesToEnter, historyValue, statesForDefaultEntry, getProperAncestors(stateNode, toStateNode));
1540
+ }
1541
+ function exitStates(currentSnapshot, event, actorScope, transitions, mutStateNodeSet, historyValue, internalQueue, _actionExecutor) {
1542
+ let nextSnapshot = currentSnapshot;
1543
+ const statesToExit = computeExitSet(transitions, mutStateNodeSet, historyValue);
1544
+ statesToExit.sort((a, b) => b.order - a.order);
1545
+ let changedHistory;
1546
+ for (const exitStateNode of statesToExit) for (const historyNode of getHistoryNodes(exitStateNode)) {
1547
+ let predicate;
1548
+ if (historyNode.history === "deep") predicate = (sn) => isAtomicStateNode(sn) && isDescendant(sn, exitStateNode);
1549
+ else predicate = (sn) => {
1550
+ return sn.parent === exitStateNode;
1551
+ };
1552
+ changedHistory ??= { ...historyValue };
1553
+ changedHistory[historyNode.id] = Array.from(mutStateNodeSet).filter(predicate);
1554
+ }
1555
+ for (const s of statesToExit) {
1556
+ nextSnapshot = resolveActionsAndContext(nextSnapshot, event, actorScope, [...s.exit, ...s.invoke.map((def) => stopChild(def.id))], internalQueue, void 0);
1557
+ mutStateNodeSet.delete(s);
1558
+ }
1559
+ return [nextSnapshot, changedHistory || historyValue];
1560
+ }
1561
+ function getAction(machine, actionType) {
1562
+ return machine.implementations.actions[actionType];
1563
+ }
1564
+ function resolveAndExecuteActionsWithContext(currentSnapshot, event, actorScope, actions, extra, retries) {
1565
+ const { machine } = currentSnapshot;
1566
+ let intermediateSnapshot = currentSnapshot;
1567
+ for (const action of actions) {
1568
+ const isInline = typeof action === "function";
1569
+ const resolvedAction = isInline ? action : getAction(machine, typeof action === "string" ? action : action.type);
1570
+ const actionArgs = {
1571
+ context: intermediateSnapshot.context,
1572
+ event,
1573
+ self: actorScope.self,
1574
+ system: actorScope.system
1575
+ };
1576
+ const actionParams = isInline || typeof action === "string" ? void 0 : "params" in action ? typeof action.params === "function" ? action.params({
1577
+ context: intermediateSnapshot.context,
1578
+ event
1579
+ }) : action.params : void 0;
1580
+ if (!resolvedAction || !("resolve" in resolvedAction)) {
1581
+ actorScope.actionExecutor({
1582
+ type: typeof action === "string" ? action : typeof action === "object" ? action.type : action.name || "(anonymous)",
1583
+ info: actionArgs,
1584
+ params: actionParams,
1585
+ exec: resolvedAction
1586
+ });
1587
+ continue;
1588
+ }
1589
+ const builtinAction = resolvedAction;
1590
+ const [nextState, params, actions$1] = builtinAction.resolve(actorScope, intermediateSnapshot, actionArgs, actionParams, resolvedAction, extra);
1591
+ intermediateSnapshot = nextState;
1592
+ if ("retryResolve" in builtinAction) retries?.push([builtinAction, params]);
1593
+ if ("execute" in builtinAction) actorScope.actionExecutor({
1594
+ type: builtinAction.type,
1595
+ info: actionArgs,
1596
+ params,
1597
+ exec: builtinAction.execute.bind(null, actorScope, params)
1598
+ });
1599
+ if (actions$1) intermediateSnapshot = resolveAndExecuteActionsWithContext(intermediateSnapshot, event, actorScope, actions$1, extra, retries);
1600
+ }
1601
+ return intermediateSnapshot;
1602
+ }
1603
+ function resolveActionsAndContext(currentSnapshot, event, actorScope, actions, internalQueue, deferredActorIds) {
1604
+ const retries = deferredActorIds ? [] : void 0;
1605
+ const nextState = resolveAndExecuteActionsWithContext(currentSnapshot, event, actorScope, actions, {
1606
+ internalQueue,
1607
+ deferredActorIds
1608
+ }, retries);
1609
+ retries?.forEach(([builtinAction, params]) => {
1610
+ builtinAction.retryResolve(actorScope, nextState, params);
1611
+ });
1612
+ return nextState;
1613
+ }
1614
+ function macrostep(snapshot, event, actorScope, internalQueue) {
1615
+ let nextSnapshot = snapshot;
1616
+ const microstates = [];
1617
+ function addMicrostate(microstate, event$1, transitions) {
1618
+ actorScope.system._sendInspectionEvent({
1619
+ type: "@xstate.microstep",
1620
+ actorRef: actorScope.self,
1621
+ event: event$1,
1622
+ snapshot: microstate,
1623
+ _transitions: transitions
1624
+ });
1625
+ microstates.push(microstate);
1626
+ }
1627
+ if (event.type === XSTATE_STOP) {
1628
+ nextSnapshot = cloneMachineSnapshot(stopChildren(nextSnapshot, event, actorScope), { status: "stopped" });
1629
+ addMicrostate(nextSnapshot, event, []);
1630
+ return {
1631
+ snapshot: nextSnapshot,
1632
+ microstates
1633
+ };
1634
+ }
1635
+ let nextEvent = event;
1636
+ if (nextEvent.type !== XSTATE_INIT) {
1637
+ const currentEvent = nextEvent;
1638
+ const isErr = isErrorActorEvent(currentEvent);
1639
+ const transitions = selectTransitions(currentEvent, nextSnapshot);
1640
+ if (isErr && !transitions.length) {
1641
+ nextSnapshot = cloneMachineSnapshot(snapshot, {
1642
+ status: "error",
1643
+ error: currentEvent.error
1644
+ });
1645
+ addMicrostate(nextSnapshot, currentEvent, []);
1646
+ return {
1647
+ snapshot: nextSnapshot,
1648
+ microstates
1649
+ };
1650
+ }
1651
+ nextSnapshot = microstep(transitions, snapshot, actorScope, nextEvent, false, internalQueue);
1652
+ addMicrostate(nextSnapshot, currentEvent, transitions);
1653
+ }
1654
+ let shouldSelectEventlessTransitions = true;
1655
+ while (nextSnapshot.status === "active") {
1656
+ let enabledTransitions = shouldSelectEventlessTransitions ? selectEventlessTransitions(nextSnapshot, nextEvent) : [];
1657
+ const previousState = enabledTransitions.length ? nextSnapshot : void 0;
1658
+ if (!enabledTransitions.length) {
1659
+ if (!internalQueue.length) break;
1660
+ nextEvent = internalQueue.shift();
1661
+ enabledTransitions = selectTransitions(nextEvent, nextSnapshot);
1662
+ }
1663
+ nextSnapshot = microstep(enabledTransitions, nextSnapshot, actorScope, nextEvent, false, internalQueue);
1664
+ shouldSelectEventlessTransitions = nextSnapshot !== previousState;
1665
+ addMicrostate(nextSnapshot, nextEvent, enabledTransitions);
1666
+ }
1667
+ if (nextSnapshot.status !== "active") stopChildren(nextSnapshot, nextEvent, actorScope);
1668
+ return {
1669
+ snapshot: nextSnapshot,
1670
+ microstates
1671
+ };
1672
+ }
1673
+ function stopChildren(nextState, event, actorScope) {
1674
+ return resolveActionsAndContext(nextState, event, actorScope, Object.values(nextState.children).map((child) => stopChild(child)), [], void 0);
1675
+ }
1676
+ function selectTransitions(event, nextState) {
1677
+ return nextState.machine.getTransitionData(nextState, event);
1678
+ }
1679
+ function selectEventlessTransitions(nextState, event) {
1680
+ const enabledTransitionSet = /* @__PURE__ */ new Set();
1681
+ const atomicStates = nextState._nodes.filter(isAtomicStateNode);
1682
+ for (const stateNode of atomicStates) loop: for (const s of [stateNode].concat(getProperAncestors(stateNode, void 0))) {
1683
+ if (!s.always) continue;
1684
+ for (const transition of s.always) if (transition.guard === void 0 || evaluateGuard(transition.guard, nextState.context, event, nextState)) {
1685
+ enabledTransitionSet.add(transition);
1686
+ break loop;
1687
+ }
1688
+ }
1689
+ return removeConflictingTransitions(Array.from(enabledTransitionSet), new Set(nextState._nodes), nextState.historyValue);
1690
+ }
1691
+ /**
1692
+ * Resolves a partial state value with its full representation in the state
1693
+ * node's machine.
1694
+ *
1695
+ * @param stateValue The partial state value to resolve.
1696
+ */
1697
+ function resolveStateValue(rootNode, stateValue) {
1698
+ return getStateValue(rootNode, [...getAllStateNodes(getStateNodes(rootNode, stateValue))]);
1699
+ }
1700
+ function isMachineSnapshot(value) {
1701
+ return !!value && typeof value === "object" && "machine" in value && "value" in value;
1702
+ }
1703
+ const machineSnapshotMatches = function matches(testValue) {
1704
+ return matchesState(testValue, this.value);
1705
+ };
1706
+ const machineSnapshotHasTag = function hasTag(tag) {
1707
+ return this.tags.has(tag);
1708
+ };
1709
+ const machineSnapshotCan = function can(event) {
1710
+ const transitionData = this.machine.getTransitionData(this, event);
1711
+ return !!transitionData?.length && transitionData.some((t) => t.target !== void 0 || t.actions.length);
1712
+ };
1713
+ const machineSnapshotToJSON = function toJSON() {
1714
+ const { _nodes: nodes, tags, machine, getMeta, toJSON: toJSON$1, can, hasTag, matches, ...jsonValues } = this;
1715
+ return {
1716
+ ...jsonValues,
1717
+ tags: Array.from(tags)
1718
+ };
1719
+ };
1720
+ const machineSnapshotGetMeta = function getMeta() {
1721
+ return this._nodes.reduce((acc, stateNode) => {
1722
+ if (stateNode.meta !== void 0) acc[stateNode.id] = stateNode.meta;
1723
+ return acc;
1724
+ }, {});
1725
+ };
1726
+ function createMachineSnapshot(config, machine) {
1727
+ return {
1728
+ status: config.status,
1729
+ output: config.output,
1730
+ error: config.error,
1731
+ machine,
1732
+ context: config.context,
1733
+ _nodes: config._nodes,
1734
+ value: getStateValue(machine.root, config._nodes),
1735
+ tags: new Set(config._nodes.flatMap((sn) => sn.tags)),
1736
+ children: config.children,
1737
+ historyValue: config.historyValue || {},
1738
+ matches: machineSnapshotMatches,
1739
+ hasTag: machineSnapshotHasTag,
1740
+ can: machineSnapshotCan,
1741
+ getMeta: machineSnapshotGetMeta,
1742
+ toJSON: machineSnapshotToJSON
1743
+ };
1744
+ }
1745
+ function cloneMachineSnapshot(snapshot, config = {}) {
1746
+ return createMachineSnapshot({
1747
+ ...snapshot,
1748
+ ...config
1749
+ }, snapshot.machine);
1750
+ }
1751
+ function serializeHistoryValue(historyValue) {
1752
+ if (typeof historyValue !== "object" || historyValue === null) return {};
1753
+ const result = {};
1754
+ for (const key in historyValue) {
1755
+ const value = historyValue[key];
1756
+ if (Array.isArray(value)) result[key] = value.map((item) => ({ id: item.id }));
1757
+ }
1758
+ return result;
1759
+ }
1760
+ function getPersistedSnapshot(snapshot, options) {
1761
+ const { _nodes: nodes, tags, machine, children, context, can, hasTag, matches, getMeta, toJSON, ...jsonValues } = snapshot;
1762
+ const childrenJson = {};
1763
+ for (const id in children) {
1764
+ const child = children[id];
1765
+ childrenJson[id] = {
1766
+ snapshot: child.getPersistedSnapshot(options),
1767
+ src: child.src,
1768
+ systemId: child.systemId,
1769
+ syncSnapshot: child._syncSnapshot
1770
+ };
1771
+ }
1772
+ return {
1773
+ ...jsonValues,
1774
+ context: persistContext(context),
1775
+ children: childrenJson,
1776
+ historyValue: serializeHistoryValue(jsonValues.historyValue)
1777
+ };
1778
+ }
1779
+ function persistContext(contextPart) {
1780
+ let copy;
1781
+ for (const key in contextPart) {
1782
+ const value = contextPart[key];
1783
+ if (value && typeof value === "object") if ("sessionId" in value && "send" in value && "ref" in value) {
1784
+ copy ??= Array.isArray(contextPart) ? contextPart.slice() : { ...contextPart };
1785
+ copy[key] = {
1786
+ xstate$$type: $$ACTOR_TYPE,
1787
+ id: value.id
1788
+ };
1789
+ } else {
1790
+ const result = persistContext(value);
1791
+ if (result !== value) {
1792
+ copy ??= Array.isArray(contextPart) ? contextPart.slice() : { ...contextPart };
1793
+ copy[key] = result;
1794
+ }
1795
+ }
1796
+ }
1797
+ return copy ?? contextPart;
1798
+ }
1799
+ function resolveRaise(_, snapshot, args, actionParams, { event: eventOrExpr, id, delay }, { internalQueue }) {
1800
+ const delaysMap = snapshot.machine.implementations.delays;
1801
+ if (typeof eventOrExpr === "string") throw new Error(`Only event objects may be used with raise; use raise({ type: "${eventOrExpr}" }) instead`);
1802
+ const resolvedEvent = typeof eventOrExpr === "function" ? eventOrExpr(args, actionParams) : eventOrExpr;
1803
+ let resolvedDelay;
1804
+ if (typeof delay === "string") {
1805
+ const configDelay = delaysMap && delaysMap[delay];
1806
+ resolvedDelay = typeof configDelay === "function" ? configDelay(args, actionParams) : configDelay;
1807
+ } else resolvedDelay = typeof delay === "function" ? delay(args, actionParams) : delay;
1808
+ if (typeof resolvedDelay !== "number") internalQueue.push(resolvedEvent);
1809
+ return [
1810
+ snapshot,
1811
+ {
1812
+ event: resolvedEvent,
1813
+ id,
1814
+ delay: resolvedDelay
1815
+ },
1816
+ void 0
1817
+ ];
1818
+ }
1819
+ function executeRaise(actorScope, params) {
1820
+ const { event, delay, id } = params;
1821
+ if (typeof delay === "number") {
1822
+ actorScope.defer(() => {
1823
+ const self$1 = actorScope.self;
1824
+ actorScope.system.scheduler.schedule(self$1, self$1, event, delay, id);
1825
+ });
1826
+ return;
1827
+ }
1828
+ }
1829
+ /**
1830
+ * Raises an event. This places the event in the internal event queue, so that
1831
+ * the event is immediately consumed by the machine in the current step.
1832
+ *
1833
+ * @param eventType The event to raise.
1834
+ */
1835
+ function raise(eventOrExpr, options) {
1836
+ function raise$1(_args, _params) {}
1837
+ raise$1.type = "xstate.raise";
1838
+ raise$1.event = eventOrExpr;
1839
+ raise$1.id = options?.id;
1840
+ raise$1.delay = options?.delay;
1841
+ raise$1.resolve = resolveRaise;
1842
+ raise$1.execute = executeRaise;
1843
+ return raise$1;
1844
+ }
1845
+
1846
+ //#endregion
1847
+ //#region ../../node_modules/.pnpm/xstate@5.24.0/node_modules/xstate/actors/dist/xstate-actors.esm.js
1848
+ /**
1849
+ * Represents an actor created by `fromTransition`.
1850
+ *
1851
+ * The type of `self` within the actor's logic.
1852
+ *
1853
+ * @example
1854
+ *
1855
+ * ```ts
1856
+ * import {
1857
+ * fromTransition,
1858
+ * createActor,
1859
+ * type AnyActorSystem
1860
+ * } from 'xstate';
1861
+ *
1862
+ * //* The actor's stored context.
1863
+ * type Context = {
1864
+ * // The current count.
1865
+ * count: number;
1866
+ * // The amount to increase `count` by.
1867
+ * step: number;
1868
+ * };
1869
+ * // The events the actor receives.
1870
+ * type Event = { type: 'increment' };
1871
+ * // The actor's input.
1872
+ * type Input = { step?: number };
1873
+ *
1874
+ * // Actor logic that increments `count` by `step` when it receives an event of
1875
+ * // type `increment`.
1876
+ * const logic = fromTransition<Context, Event, AnyActorSystem, Input>(
1877
+ * (state, event, actorScope) => {
1878
+ * actorScope.self;
1879
+ * // ^? TransitionActorRef<Context, Event>
1880
+ *
1881
+ * if (event.type === 'increment') {
1882
+ * return {
1883
+ * ...state,
1884
+ * count: state.count + state.step
1885
+ * };
1886
+ * }
1887
+ * return state;
1888
+ * },
1889
+ * ({ input, self }) => {
1890
+ * self;
1891
+ * // ^? TransitionActorRef<Context, Event>
1892
+ *
1893
+ * return {
1894
+ * count: 0,
1895
+ * step: input.step ?? 1
1896
+ * };
1897
+ * }
1898
+ * );
1899
+ *
1900
+ * const actor = createActor(logic, { input: { step: 10 } });
1901
+ * // ^? TransitionActorRef<Context, Event>
1902
+ * ```
1903
+ *
1904
+ * @see {@link fromTransition}
1905
+ */
1906
+ /**
1907
+ * Returns actor logic given a transition function and its initial state.
1908
+ *
1909
+ * A “transition function” is a function that takes the current `state` and
1910
+ * received `event` object as arguments, and returns the next state, similar to
1911
+ * a reducer.
1912
+ *
1913
+ * Actors created from transition logic (“transition actors”) can:
1914
+ *
1915
+ * - Receive events
1916
+ * - Emit snapshots of its state
1917
+ *
1918
+ * The transition function’s `state` is used as its transition actor’s
1919
+ * `context`.
1920
+ *
1921
+ * Note that the "state" for a transition function is provided by the initial
1922
+ * state argument, and is not the same as the State object of an actor or a
1923
+ * state within a machine configuration.
1924
+ *
1925
+ * @example
1926
+ *
1927
+ * ```ts
1928
+ * const transitionLogic = fromTransition(
1929
+ * (state, event) => {
1930
+ * if (event.type === 'increment') {
1931
+ * return {
1932
+ * ...state,
1933
+ * count: state.count + 1
1934
+ * };
1935
+ * }
1936
+ * return state;
1937
+ * },
1938
+ * { count: 0 }
1939
+ * );
1940
+ *
1941
+ * const transitionActor = createActor(transitionLogic);
1942
+ * transitionActor.subscribe((snapshot) => {
1943
+ * console.log(snapshot);
1944
+ * });
1945
+ * transitionActor.start();
1946
+ * // => {
1947
+ * // status: 'active',
1948
+ * // context: { count: 0 },
1949
+ * // ...
1950
+ * // }
1951
+ *
1952
+ * transitionActor.send({ type: 'increment' });
1953
+ * // => {
1954
+ * // status: 'active',
1955
+ * // context: { count: 1 },
1956
+ * // ...
1957
+ * // }
1958
+ * ```
1959
+ *
1960
+ * @param transition The transition function used to describe the transition
1961
+ * logic. It should return the next state given the current state and event.
1962
+ * It receives the following arguments:
1963
+ *
1964
+ * - `state` - the current state.
1965
+ * - `event` - the received event.
1966
+ * - `actorScope` - the actor scope object, with properties like `self` and
1967
+ * `system`.
1968
+ *
1969
+ * @param initialContext The initial state of the transition function, either an
1970
+ * object representing the state, or a function which returns a state object.
1971
+ * If a function, it will receive as its only argument an object with the
1972
+ * following properties:
1973
+ *
1974
+ * - `input` - the `input` provided to its parent transition actor.
1975
+ * - `self` - a reference to its parent transition actor.
1976
+ *
1977
+ * @returns Actor logic
1978
+ * @see {@link https://stately.ai/docs/input | Input docs} for more information about how input is passed
1979
+ */
1980
+ function fromTransition(transition, initialContext) {
1981
+ return {
1982
+ config: transition,
1983
+ transition: (snapshot, event, actorScope) => {
1984
+ return {
1985
+ ...snapshot,
1986
+ context: transition(snapshot.context, event, actorScope)
1987
+ };
1988
+ },
1989
+ getInitialSnapshot: (_, input) => {
1990
+ return {
1991
+ status: "active",
1992
+ output: void 0,
1993
+ error: void 0,
1994
+ context: typeof initialContext === "function" ? initialContext({ input }) : initialContext
1995
+ };
1996
+ },
1997
+ getPersistedSnapshot: (snapshot) => snapshot,
1998
+ restoreSnapshot: (snapshot) => snapshot
1999
+ };
2000
+ }
2001
+ const instanceStates = /* @__PURE__ */ new WeakMap();
2002
+ /**
2003
+ * Represents an actor created by `fromCallback`.
2004
+ *
2005
+ * The type of `self` within the actor's logic.
2006
+ *
2007
+ * @example
2008
+ *
2009
+ * ```ts
2010
+ * import { fromCallback, createActor } from 'xstate';
2011
+ *
2012
+ * // The events the actor receives.
2013
+ * type Event = { type: 'someEvent' };
2014
+ * // The actor's input.
2015
+ * type Input = { name: string };
2016
+ *
2017
+ * // Actor logic that logs whenever it receives an event of type `someEvent`.
2018
+ * const logic = fromCallback<Event, Input>(({ self, input, receive }) => {
2019
+ * self;
2020
+ * // ^? CallbackActorRef<Event, Input>
2021
+ *
2022
+ * receive((event) => {
2023
+ * if (event.type === 'someEvent') {
2024
+ * console.log(`${input.name}: received "someEvent" event`);
2025
+ * // logs 'myActor: received "someEvent" event'
2026
+ * }
2027
+ * });
2028
+ * });
2029
+ *
2030
+ * const actor = createActor(logic, { input: { name: 'myActor' } });
2031
+ * // ^? CallbackActorRef<Event, Input>
2032
+ * ```
2033
+ *
2034
+ * @see {@link fromCallback}
2035
+ */
2036
+ /**
2037
+ * An actor logic creator which returns callback logic as defined by a callback
2038
+ * function.
2039
+ *
2040
+ * @remarks
2041
+ * Useful for subscription-based or other free-form logic that can send events
2042
+ * back to the parent actor.
2043
+ *
2044
+ * Actors created from callback logic (“callback actors”) can:
2045
+ *
2046
+ * - Receive events via the `receive` function
2047
+ * - Send events to the parent actor via the `sendBack` function
2048
+ *
2049
+ * Callback actors are a bit different from other actors in that they:
2050
+ *
2051
+ * - Do not work with `onDone`
2052
+ * - Do not produce a snapshot using `.getSnapshot()`
2053
+ * - Do not emit values when used with `.subscribe()`
2054
+ * - Can not be stopped with `.stop()`
2055
+ *
2056
+ * @example
2057
+ *
2058
+ * ```typescript
2059
+ * const callbackLogic = fromCallback(({ sendBack, receive }) => {
2060
+ * let lockStatus = 'unlocked';
2061
+ *
2062
+ * const handler = (event) => {
2063
+ * if (lockStatus === 'locked') {
2064
+ * return;
2065
+ * }
2066
+ * sendBack(event);
2067
+ * };
2068
+ *
2069
+ * receive((event) => {
2070
+ * if (event.type === 'lock') {
2071
+ * lockStatus = 'locked';
2072
+ * } else if (event.type === 'unlock') {
2073
+ * lockStatus = 'unlocked';
2074
+ * }
2075
+ * });
2076
+ *
2077
+ * document.body.addEventListener('click', handler);
2078
+ *
2079
+ * return () => {
2080
+ * document.body.removeEventListener('click', handler);
2081
+ * };
2082
+ * });
2083
+ * ```
2084
+ *
2085
+ * @param callback - The callback function used to describe the callback logic
2086
+ * The callback function is passed an object with the following properties:
2087
+ *
2088
+ * - `receive` - A function that can send events back to the parent actor; the
2089
+ * listener is then called whenever events are received by the callback
2090
+ * actor
2091
+ * - `sendBack` - A function that can send events back to the parent actor
2092
+ * - `input` - Data that was provided to the callback actor
2093
+ * - `self` - The parent actor of the callback actor
2094
+ * - `system` - The actor system to which the callback actor belongs The callback
2095
+ * function can (optionally) return a cleanup function, which is called
2096
+ * when the actor is stopped.
2097
+ *
2098
+ * @returns Callback logic
2099
+ * @see {@link CallbackLogicFunction} for more information about the callback function and its object argument
2100
+ * @see {@link https://stately.ai/docs/input | Input docs} for more information about how input is passed
2101
+ */
2102
+ function fromCallback(callback) {
2103
+ return {
2104
+ config: callback,
2105
+ start: (state, actorScope) => {
2106
+ const { self: self$1, system, emit: emit$1 } = actorScope;
2107
+ const callbackState = {
2108
+ receivers: void 0,
2109
+ dispose: void 0
2110
+ };
2111
+ instanceStates.set(self$1, callbackState);
2112
+ callbackState.dispose = callback({
2113
+ input: state.input,
2114
+ system,
2115
+ self: self$1,
2116
+ sendBack: (event) => {
2117
+ if (self$1.getSnapshot().status === "stopped") return;
2118
+ if (self$1._parent) system._relay(self$1, self$1._parent, event);
2119
+ },
2120
+ receive: (listener) => {
2121
+ callbackState.receivers ??= /* @__PURE__ */ new Set();
2122
+ callbackState.receivers.add(listener);
2123
+ },
2124
+ emit: emit$1
2125
+ });
2126
+ },
2127
+ transition: (state, event, actorScope) => {
2128
+ const callbackState = instanceStates.get(actorScope.self);
2129
+ if (event.type === XSTATE_STOP) {
2130
+ state = {
2131
+ ...state,
2132
+ status: "stopped",
2133
+ error: void 0
2134
+ };
2135
+ callbackState.dispose?.();
2136
+ return state;
2137
+ }
2138
+ callbackState.receivers?.forEach((receiver) => receiver(event));
2139
+ return state;
2140
+ },
2141
+ getInitialSnapshot: (_, input) => {
2142
+ return {
2143
+ status: "active",
2144
+ output: void 0,
2145
+ error: void 0,
2146
+ input
2147
+ };
2148
+ },
2149
+ getPersistedSnapshot: (snapshot) => snapshot,
2150
+ restoreSnapshot: (snapshot) => snapshot
2151
+ };
2152
+ }
2153
+ const XSTATE_PROMISE_RESOLVE = "xstate.promise.resolve";
2154
+ const XSTATE_PROMISE_REJECT = "xstate.promise.reject";
2155
+ /**
2156
+ * Represents an actor created by `fromPromise`.
2157
+ *
2158
+ * The type of `self` within the actor's logic.
2159
+ *
2160
+ * @example
2161
+ *
2162
+ * ```ts
2163
+ * import { fromPromise, createActor } from 'xstate';
2164
+ *
2165
+ * // The actor's resolved output
2166
+ * type Output = string;
2167
+ * // The actor's input.
2168
+ * type Input = { message: string };
2169
+ *
2170
+ * // Actor logic that fetches the url of an image of a cat saying `input.message`.
2171
+ * const logic = fromPromise<Output, Input>(async ({ input, self }) => {
2172
+ * self;
2173
+ * // ^? PromiseActorRef<Output, Input>
2174
+ *
2175
+ * const data = await fetch(
2176
+ * `https://cataas.com/cat/says/${input.message}`
2177
+ * );
2178
+ * const url = await data.json();
2179
+ * return url;
2180
+ * });
2181
+ *
2182
+ * const actor = createActor(logic, { input: { message: 'hello world' } });
2183
+ * // ^? PromiseActorRef<Output, Input>
2184
+ * ```
2185
+ *
2186
+ * @see {@link fromPromise}
2187
+ */
2188
+ const controllerMap = /* @__PURE__ */ new WeakMap();
2189
+ /**
2190
+ * An actor logic creator which returns promise logic as defined by an async
2191
+ * process that resolves or rejects after some time.
2192
+ *
2193
+ * Actors created from promise actor logic (“promise actors”) can:
2194
+ *
2195
+ * - Emit the resolved value of the promise
2196
+ * - Output the resolved value of the promise
2197
+ *
2198
+ * Sending events to promise actors will have no effect.
2199
+ *
2200
+ * @example
2201
+ *
2202
+ * ```ts
2203
+ * const promiseLogic = fromPromise(async () => {
2204
+ * const result = await fetch('https://example.com/...').then((data) =>
2205
+ * data.json()
2206
+ * );
2207
+ *
2208
+ * return result;
2209
+ * });
2210
+ *
2211
+ * const promiseActor = createActor(promiseLogic);
2212
+ * promiseActor.subscribe((snapshot) => {
2213
+ * console.log(snapshot);
2214
+ * });
2215
+ * promiseActor.start();
2216
+ * // => {
2217
+ * // output: undefined,
2218
+ * // status: 'active'
2219
+ * // ...
2220
+ * // }
2221
+ *
2222
+ * // After promise resolves
2223
+ * // => {
2224
+ * // output: { ... },
2225
+ * // status: 'done',
2226
+ * // ...
2227
+ * // }
2228
+ * ```
2229
+ *
2230
+ * @param promiseCreator A function which returns a Promise, and accepts an
2231
+ * object with the following properties:
2232
+ *
2233
+ * - `input` - Data that was provided to the promise actor
2234
+ * - `self` - The parent actor of the promise actor
2235
+ * - `system` - The actor system to which the promise actor belongs
2236
+ *
2237
+ * @see {@link https://stately.ai/docs/input | Input docs} for more information about how input is passed
2238
+ */
2239
+ function fromPromise(promiseCreator) {
2240
+ return {
2241
+ config: promiseCreator,
2242
+ transition: (state, event, scope) => {
2243
+ if (state.status !== "active") return state;
2244
+ switch (event.type) {
2245
+ case XSTATE_PROMISE_RESOLVE: {
2246
+ const resolvedValue = event.data;
2247
+ return {
2248
+ ...state,
2249
+ status: "done",
2250
+ output: resolvedValue,
2251
+ input: void 0
2252
+ };
2253
+ }
2254
+ case XSTATE_PROMISE_REJECT: return {
2255
+ ...state,
2256
+ status: "error",
2257
+ error: event.data,
2258
+ input: void 0
2259
+ };
2260
+ case XSTATE_STOP:
2261
+ controllerMap.get(scope.self)?.abort();
2262
+ return {
2263
+ ...state,
2264
+ status: "stopped",
2265
+ input: void 0
2266
+ };
2267
+ default: return state;
2268
+ }
2269
+ },
2270
+ start: (state, { self: self$1, system, emit: emit$1 }) => {
2271
+ if (state.status !== "active") return;
2272
+ const controller = new AbortController();
2273
+ controllerMap.set(self$1, controller);
2274
+ Promise.resolve(promiseCreator({
2275
+ input: state.input,
2276
+ system,
2277
+ self: self$1,
2278
+ signal: controller.signal,
2279
+ emit: emit$1
2280
+ })).then((response) => {
2281
+ if (self$1.getSnapshot().status !== "active") return;
2282
+ controllerMap.delete(self$1);
2283
+ system._relay(self$1, self$1, {
2284
+ type: XSTATE_PROMISE_RESOLVE,
2285
+ data: response
2286
+ });
2287
+ }, (errorData) => {
2288
+ if (self$1.getSnapshot().status !== "active") return;
2289
+ controllerMap.delete(self$1);
2290
+ system._relay(self$1, self$1, {
2291
+ type: XSTATE_PROMISE_REJECT,
2292
+ data: errorData
2293
+ });
2294
+ });
2295
+ },
2296
+ getInitialSnapshot: (_, input) => {
2297
+ return {
2298
+ status: "active",
2299
+ output: void 0,
2300
+ error: void 0,
2301
+ input
2302
+ };
2303
+ },
2304
+ getPersistedSnapshot: (snapshot) => snapshot,
2305
+ restoreSnapshot: (snapshot) => snapshot
2306
+ };
2307
+ }
2308
+ const emptyLogic = fromTransition((_) => void 0, void 0);
2309
+
2310
+ //#endregion
2311
+ //#region ../../node_modules/.pnpm/xstate@5.24.0/node_modules/xstate/dist/assign-ab9cc19e.esm.js
2312
+ function createSpawner(actorScope, { machine, context }, event, spawnedChildren) {
2313
+ const spawn = (src, options) => {
2314
+ if (typeof src === "string") {
2315
+ const logic = resolveReferencedActor(machine, src);
2316
+ if (!logic) throw new Error(`Actor logic '${src}' not implemented in machine '${machine.id}'`);
2317
+ const actorRef = createActor(logic, {
2318
+ id: options?.id,
2319
+ parent: actorScope.self,
2320
+ syncSnapshot: options?.syncSnapshot,
2321
+ input: typeof options?.input === "function" ? options.input({
2322
+ context,
2323
+ event,
2324
+ self: actorScope.self
2325
+ }) : options?.input,
2326
+ src,
2327
+ systemId: options?.systemId
2328
+ });
2329
+ spawnedChildren[actorRef.id] = actorRef;
2330
+ return actorRef;
2331
+ } else return createActor(src, {
2332
+ id: options?.id,
2333
+ parent: actorScope.self,
2334
+ syncSnapshot: options?.syncSnapshot,
2335
+ input: options?.input,
2336
+ src,
2337
+ systemId: options?.systemId
2338
+ });
2339
+ };
2340
+ return (src, options) => {
2341
+ const actorRef = spawn(src, options);
2342
+ spawnedChildren[actorRef.id] = actorRef;
2343
+ actorScope.defer(() => {
2344
+ if (actorRef._processingStatus === ProcessingStatus.Stopped) return;
2345
+ actorRef.start();
2346
+ });
2347
+ return actorRef;
2348
+ };
2349
+ }
2350
+ function resolveAssign(actorScope, snapshot, actionArgs, actionParams, { assignment }) {
2351
+ if (!snapshot.context) throw new Error("Cannot assign to undefined `context`. Ensure that `context` is defined in the machine config.");
2352
+ const spawnedChildren = {};
2353
+ const assignArgs = {
2354
+ context: snapshot.context,
2355
+ event: actionArgs.event,
2356
+ spawn: createSpawner(actorScope, snapshot, actionArgs.event, spawnedChildren),
2357
+ self: actorScope.self,
2358
+ system: actorScope.system
2359
+ };
2360
+ let partialUpdate = {};
2361
+ if (typeof assignment === "function") partialUpdate = assignment(assignArgs, actionParams);
2362
+ else for (const key of Object.keys(assignment)) {
2363
+ const propAssignment = assignment[key];
2364
+ partialUpdate[key] = typeof propAssignment === "function" ? propAssignment(assignArgs, actionParams) : propAssignment;
2365
+ }
2366
+ return [
2367
+ cloneMachineSnapshot(snapshot, {
2368
+ context: Object.assign({}, snapshot.context, partialUpdate),
2369
+ children: Object.keys(spawnedChildren).length ? {
2370
+ ...snapshot.children,
2371
+ ...spawnedChildren
2372
+ } : snapshot.children
2373
+ }),
2374
+ void 0,
2375
+ void 0
2376
+ ];
2377
+ }
2378
+ /**
2379
+ * Updates the current context of the machine.
2380
+ *
2381
+ * @example
2382
+ *
2383
+ * ```ts
2384
+ * import { createMachine, assign } from 'xstate';
2385
+ *
2386
+ * const countMachine = createMachine({
2387
+ * context: {
2388
+ * count: 0,
2389
+ * message: ''
2390
+ * },
2391
+ * on: {
2392
+ * inc: {
2393
+ * actions: assign({
2394
+ * count: ({ context }) => context.count + 1
2395
+ * })
2396
+ * },
2397
+ * updateMessage: {
2398
+ * actions: assign(({ context, event }) => {
2399
+ * return {
2400
+ * message: event.message.trim()
2401
+ * };
2402
+ * })
2403
+ * }
2404
+ * }
2405
+ * });
2406
+ * ```
2407
+ *
2408
+ * @param assignment An object that represents the partial context to update, or
2409
+ * a function that returns an object that represents the partial context to
2410
+ * update.
2411
+ */
2412
+ function assign(assignment) {
2413
+ function assign$1(_args, _params) {}
2414
+ assign$1.type = "xstate.assign";
2415
+ assign$1.assignment = assignment;
2416
+ assign$1.resolve = resolveAssign;
2417
+ return assign$1;
2418
+ }
2419
+
2420
+ //#endregion
2421
+ //#region ../../node_modules/.pnpm/xstate@5.24.0/node_modules/xstate/dist/StateMachine-37bc3882.esm.js
2422
+ const cache = /* @__PURE__ */ new WeakMap();
2423
+ function memo(object, key, fn) {
2424
+ let memoizedData = cache.get(object);
2425
+ if (!memoizedData) {
2426
+ memoizedData = { [key]: fn() };
2427
+ cache.set(object, memoizedData);
2428
+ } else if (!(key in memoizedData)) memoizedData[key] = fn();
2429
+ return memoizedData[key];
2430
+ }
2431
+ const EMPTY_OBJECT = {};
2432
+ const toSerializableAction = (action) => {
2433
+ if (typeof action === "string") return { type: action };
2434
+ if (typeof action === "function") {
2435
+ if ("resolve" in action) return { type: action.type };
2436
+ return { type: action.name };
2437
+ }
2438
+ return action;
2439
+ };
2440
+ var StateNode = class StateNode {
2441
+ constructor(config, options) {
2442
+ this.config = config;
2443
+ /**
2444
+ * The relative key of the state node, which represents its location in the
2445
+ * overall state value.
2446
+ */
2447
+ this.key = void 0;
2448
+ /** The unique ID of the state node. */
2449
+ this.id = void 0;
2450
+ /**
2451
+ * The type of this state node:
2452
+ *
2453
+ * - `'atomic'` - no child state nodes
2454
+ * - `'compound'` - nested child state nodes (XOR)
2455
+ * - `'parallel'` - orthogonal nested child state nodes (AND)
2456
+ * - `'history'` - history state node
2457
+ * - `'final'` - final state node
2458
+ */
2459
+ this.type = void 0;
2460
+ /** The string path from the root machine node to this node. */
2461
+ this.path = void 0;
2462
+ /** The child state nodes. */
2463
+ this.states = void 0;
2464
+ /**
2465
+ * The type of history on this state node. Can be:
2466
+ *
2467
+ * - `'shallow'` - recalls only top-level historical state value
2468
+ * - `'deep'` - recalls historical state value at all levels
2469
+ */
2470
+ this.history = void 0;
2471
+ /** The action(s) to be executed upon entering the state node. */
2472
+ this.entry = void 0;
2473
+ /** The action(s) to be executed upon exiting the state node. */
2474
+ this.exit = void 0;
2475
+ /** The parent state node. */
2476
+ this.parent = void 0;
2477
+ /** The root machine node. */
2478
+ this.machine = void 0;
2479
+ /**
2480
+ * The meta data associated with this state node, which will be returned in
2481
+ * State instances.
2482
+ */
2483
+ this.meta = void 0;
2484
+ /**
2485
+ * The output data sent with the "xstate.done.state._id_" event if this is a
2486
+ * final state node.
2487
+ */
2488
+ this.output = void 0;
2489
+ /**
2490
+ * The order this state node appears. Corresponds to the implicit document
2491
+ * order.
2492
+ */
2493
+ this.order = -1;
2494
+ this.description = void 0;
2495
+ this.tags = [];
2496
+ this.transitions = void 0;
2497
+ this.always = void 0;
2498
+ this.parent = options._parent;
2499
+ this.key = options._key;
2500
+ this.machine = options._machine;
2501
+ this.path = this.parent ? this.parent.path.concat(this.key) : [];
2502
+ this.id = this.config.id || [this.machine.id, ...this.path].join(STATE_DELIMITER);
2503
+ this.type = this.config.type || (this.config.states && Object.keys(this.config.states).length ? "compound" : this.config.history ? "history" : "atomic");
2504
+ this.description = this.config.description;
2505
+ this.order = this.machine.idMap.size;
2506
+ this.machine.idMap.set(this.id, this);
2507
+ this.states = this.config.states ? mapValues(this.config.states, (stateConfig, key) => {
2508
+ return new StateNode(stateConfig, {
2509
+ _parent: this,
2510
+ _key: key,
2511
+ _machine: this.machine
2512
+ });
2513
+ }) : EMPTY_OBJECT;
2514
+ if (this.type === "compound" && !this.config.initial) throw new Error(`No initial state specified for compound state node "#${this.id}". Try adding { initial: "${Object.keys(this.states)[0]}" } to the state config.`);
2515
+ this.history = this.config.history === true ? "shallow" : this.config.history || false;
2516
+ this.entry = toArray(this.config.entry).slice();
2517
+ this.exit = toArray(this.config.exit).slice();
2518
+ this.meta = this.config.meta;
2519
+ this.output = this.type === "final" || !this.parent ? this.config.output : void 0;
2520
+ this.tags = toArray(config.tags).slice();
2521
+ }
2522
+ /** @internal */
2523
+ _initialize() {
2524
+ this.transitions = formatTransitions(this);
2525
+ if (this.config.always) this.always = toTransitionConfigArray(this.config.always).map((t) => formatTransition(this, NULL_EVENT, t));
2526
+ Object.keys(this.states).forEach((key) => {
2527
+ this.states[key]._initialize();
2528
+ });
2529
+ }
2530
+ /** The well-structured state node definition. */
2531
+ get definition() {
2532
+ return {
2533
+ id: this.id,
2534
+ key: this.key,
2535
+ version: this.machine.version,
2536
+ type: this.type,
2537
+ initial: this.initial ? {
2538
+ target: this.initial.target,
2539
+ source: this,
2540
+ actions: this.initial.actions.map(toSerializableAction),
2541
+ eventType: null,
2542
+ reenter: false,
2543
+ toJSON: () => ({
2544
+ target: this.initial.target.map((t) => `#${t.id}`),
2545
+ source: `#${this.id}`,
2546
+ actions: this.initial.actions.map(toSerializableAction),
2547
+ eventType: null
2548
+ })
2549
+ } : void 0,
2550
+ history: this.history,
2551
+ states: mapValues(this.states, (state) => {
2552
+ return state.definition;
2553
+ }),
2554
+ on: this.on,
2555
+ transitions: [...this.transitions.values()].flat().map((t) => ({
2556
+ ...t,
2557
+ actions: t.actions.map(toSerializableAction)
2558
+ })),
2559
+ entry: this.entry.map(toSerializableAction),
2560
+ exit: this.exit.map(toSerializableAction),
2561
+ meta: this.meta,
2562
+ order: this.order || -1,
2563
+ output: this.output,
2564
+ invoke: this.invoke,
2565
+ description: this.description,
2566
+ tags: this.tags
2567
+ };
2568
+ }
2569
+ /** @internal */
2570
+ toJSON() {
2571
+ return this.definition;
2572
+ }
2573
+ /** The logic invoked as actors by this state node. */
2574
+ get invoke() {
2575
+ return memo(this, "invoke", () => toArray(this.config.invoke).map((invokeConfig, i) => {
2576
+ const { src, systemId } = invokeConfig;
2577
+ const resolvedId = invokeConfig.id ?? createInvokeId(this.id, i);
2578
+ const sourceName = typeof src === "string" ? src : `xstate.invoke.${createInvokeId(this.id, i)}`;
2579
+ return {
2580
+ ...invokeConfig,
2581
+ src: sourceName,
2582
+ id: resolvedId,
2583
+ systemId,
2584
+ toJSON() {
2585
+ const { onDone, onError, ...invokeDefValues } = invokeConfig;
2586
+ return {
2587
+ ...invokeDefValues,
2588
+ type: "xstate.invoke",
2589
+ src: sourceName,
2590
+ id: resolvedId
2591
+ };
2592
+ }
2593
+ };
2594
+ }));
2595
+ }
2596
+ /** The mapping of events to transitions. */
2597
+ get on() {
2598
+ return memo(this, "on", () => {
2599
+ return [...this.transitions].flatMap(([descriptor, t]) => t.map((t$1) => [descriptor, t$1])).reduce((map, [descriptor, transition]) => {
2600
+ map[descriptor] = map[descriptor] || [];
2601
+ map[descriptor].push(transition);
2602
+ return map;
2603
+ }, {});
2604
+ });
2605
+ }
2606
+ get after() {
2607
+ return memo(this, "delayedTransitions", () => getDelayedTransitions(this));
2608
+ }
2609
+ get initial() {
2610
+ return memo(this, "initial", () => formatInitialTransition(this, this.config.initial));
2611
+ }
2612
+ /** @internal */
2613
+ next(snapshot, event) {
2614
+ const eventType = event.type;
2615
+ const actions = [];
2616
+ let selectedTransition;
2617
+ const candidates = memo(this, `candidates-${eventType}`, () => getCandidates(this, eventType));
2618
+ for (const candidate of candidates) {
2619
+ const { guard } = candidate;
2620
+ const resolvedContext = snapshot.context;
2621
+ let guardPassed = false;
2622
+ try {
2623
+ guardPassed = !guard || evaluateGuard(guard, resolvedContext, event, snapshot);
2624
+ } catch (err) {
2625
+ const guardType = typeof guard === "string" ? guard : typeof guard === "object" ? guard.type : void 0;
2626
+ throw new Error(`Unable to evaluate guard ${guardType ? `'${guardType}' ` : ""}in transition for event '${eventType}' in state node '${this.id}':\n${err.message}`);
2627
+ }
2628
+ if (guardPassed) {
2629
+ actions.push(...candidate.actions);
2630
+ selectedTransition = candidate;
2631
+ break;
2632
+ }
2633
+ }
2634
+ return selectedTransition ? [selectedTransition] : void 0;
2635
+ }
2636
+ /** All the event types accepted by this state node and its descendants. */
2637
+ get events() {
2638
+ return memo(this, "events", () => {
2639
+ const { states } = this;
2640
+ const events = new Set(this.ownEvents);
2641
+ if (states) for (const stateId of Object.keys(states)) {
2642
+ const state = states[stateId];
2643
+ if (state.states) for (const event of state.events) events.add(`${event}`);
2644
+ }
2645
+ return Array.from(events);
2646
+ });
2647
+ }
2648
+ /**
2649
+ * All the events that have transitions directly from this state node.
2650
+ *
2651
+ * Excludes any inert events.
2652
+ */
2653
+ get ownEvents() {
2654
+ const events = new Set([...this.transitions.keys()].filter((descriptor) => {
2655
+ return this.transitions.get(descriptor).some((transition) => !(!transition.target && !transition.actions.length && !transition.reenter));
2656
+ }));
2657
+ return Array.from(events);
2658
+ }
2659
+ };
2660
+ var StateMachine = class StateMachine {
2661
+ constructor(config, implementations) {
2662
+ this.config = config;
2663
+ /** The machine's own version. */
2664
+ this.version = void 0;
2665
+ this.schemas = void 0;
2666
+ this.implementations = void 0;
2667
+ /** @internal */
2668
+ this.__xstatenode = true;
2669
+ /** @internal */
2670
+ this.idMap = /* @__PURE__ */ new Map();
2671
+ this.root = void 0;
2672
+ this.id = void 0;
2673
+ this.states = void 0;
2674
+ this.events = void 0;
2675
+ this.id = config.id || "(machine)";
2676
+ this.implementations = {
2677
+ actors: implementations?.actors ?? {},
2678
+ actions: implementations?.actions ?? {},
2679
+ delays: implementations?.delays ?? {},
2680
+ guards: implementations?.guards ?? {}
2681
+ };
2682
+ this.version = this.config.version;
2683
+ this.schemas = this.config.schemas;
2684
+ this.transition = this.transition.bind(this);
2685
+ this.getInitialSnapshot = this.getInitialSnapshot.bind(this);
2686
+ this.getPersistedSnapshot = this.getPersistedSnapshot.bind(this);
2687
+ this.restoreSnapshot = this.restoreSnapshot.bind(this);
2688
+ this.start = this.start.bind(this);
2689
+ this.root = new StateNode(config, {
2690
+ _key: this.id,
2691
+ _machine: this
2692
+ });
2693
+ this.root._initialize();
2694
+ this.states = this.root.states;
2695
+ this.events = this.root.events;
2696
+ }
2697
+ /**
2698
+ * Clones this state machine with the provided implementations.
2699
+ *
2700
+ * @param implementations Options (`actions`, `guards`, `actors`, `delays`) to
2701
+ * recursively merge with the existing options.
2702
+ * @returns A new `StateMachine` instance with the provided implementations.
2703
+ */
2704
+ provide(implementations) {
2705
+ const { actions, guards, actors, delays } = this.implementations;
2706
+ return new StateMachine(this.config, {
2707
+ actions: {
2708
+ ...actions,
2709
+ ...implementations.actions
2710
+ },
2711
+ guards: {
2712
+ ...guards,
2713
+ ...implementations.guards
2714
+ },
2715
+ actors: {
2716
+ ...actors,
2717
+ ...implementations.actors
2718
+ },
2719
+ delays: {
2720
+ ...delays,
2721
+ ...implementations.delays
2722
+ }
2723
+ });
2724
+ }
2725
+ resolveState(config) {
2726
+ const resolvedStateValue = resolveStateValue(this.root, config.value);
2727
+ const nodeSet = getAllStateNodes(getStateNodes(this.root, resolvedStateValue));
2728
+ return createMachineSnapshot({
2729
+ _nodes: [...nodeSet],
2730
+ context: config.context || {},
2731
+ children: {},
2732
+ status: isInFinalState(nodeSet, this.root) ? "done" : config.status || "active",
2733
+ output: config.output,
2734
+ error: config.error,
2735
+ historyValue: config.historyValue
2736
+ }, this);
2737
+ }
2738
+ /**
2739
+ * Determines the next snapshot given the current `snapshot` and received
2740
+ * `event`. Calculates a full macrostep from all microsteps.
2741
+ *
2742
+ * @param snapshot The current snapshot
2743
+ * @param event The received event
2744
+ */
2745
+ transition(snapshot, event, actorScope) {
2746
+ return macrostep(snapshot, event, actorScope, []).snapshot;
2747
+ }
2748
+ /**
2749
+ * Determines the next state given the current `state` and `event`. Calculates
2750
+ * a microstep.
2751
+ *
2752
+ * @param state The current state
2753
+ * @param event The received event
2754
+ */
2755
+ microstep(snapshot, event, actorScope) {
2756
+ return macrostep(snapshot, event, actorScope, []).microstates;
2757
+ }
2758
+ getTransitionData(snapshot, event) {
2759
+ return transitionNode(this.root, snapshot.value, snapshot, event) || [];
2760
+ }
2761
+ /**
2762
+ * The initial state _before_ evaluating any microsteps. This "pre-initial"
2763
+ * state is provided to initial actions executed in the initial state.
2764
+ */
2765
+ getPreInitialState(actorScope, initEvent, internalQueue) {
2766
+ const { context } = this.config;
2767
+ const preInitial = createMachineSnapshot({
2768
+ context: typeof context !== "function" && context ? context : {},
2769
+ _nodes: [this.root],
2770
+ children: {},
2771
+ status: "active"
2772
+ }, this);
2773
+ if (typeof context === "function") {
2774
+ const assignment = ({ spawn, event, self: self$1 }) => context({
2775
+ spawn,
2776
+ input: event.input,
2777
+ self: self$1
2778
+ });
2779
+ return resolveActionsAndContext(preInitial, initEvent, actorScope, [assign(assignment)], internalQueue, void 0);
2780
+ }
2781
+ return preInitial;
2782
+ }
2783
+ /**
2784
+ * Returns the initial `State` instance, with reference to `self` as an
2785
+ * `ActorRef`.
2786
+ */
2787
+ getInitialSnapshot(actorScope, input) {
2788
+ const initEvent = createInitEvent(input);
2789
+ const internalQueue = [];
2790
+ const preInitialState = this.getPreInitialState(actorScope, initEvent, internalQueue);
2791
+ const { snapshot: macroState } = macrostep(microstep([{
2792
+ target: [...getInitialStateNodes(this.root)],
2793
+ source: this.root,
2794
+ reenter: true,
2795
+ actions: [],
2796
+ eventType: null,
2797
+ toJSON: null
2798
+ }], preInitialState, actorScope, initEvent, true, internalQueue), initEvent, actorScope, internalQueue);
2799
+ return macroState;
2800
+ }
2801
+ start(snapshot) {
2802
+ Object.values(snapshot.children).forEach((child) => {
2803
+ if (child.getSnapshot().status === "active") child.start();
2804
+ });
2805
+ }
2806
+ getStateNodeById(stateId) {
2807
+ const fullPath = toStatePath(stateId);
2808
+ const relativePath = fullPath.slice(1);
2809
+ const resolvedStateId = isStateId(fullPath[0]) ? fullPath[0].slice(1) : fullPath[0];
2810
+ const stateNode = this.idMap.get(resolvedStateId);
2811
+ if (!stateNode) throw new Error(`Child state node '#${resolvedStateId}' does not exist on machine '${this.id}'`);
2812
+ return getStateNodeByPath(stateNode, relativePath);
2813
+ }
2814
+ get definition() {
2815
+ return this.root.definition;
2816
+ }
2817
+ toJSON() {
2818
+ return this.definition;
2819
+ }
2820
+ getPersistedSnapshot(snapshot, options) {
2821
+ return getPersistedSnapshot(snapshot, options);
2822
+ }
2823
+ restoreSnapshot(snapshot, _actorScope) {
2824
+ const children = {};
2825
+ const snapshotChildren = snapshot.children;
2826
+ Object.keys(snapshotChildren).forEach((actorId) => {
2827
+ const actorData = snapshotChildren[actorId];
2828
+ const childState = actorData.snapshot;
2829
+ const src = actorData.src;
2830
+ const logic = typeof src === "string" ? resolveReferencedActor(this, src) : src;
2831
+ if (!logic) return;
2832
+ children[actorId] = createActor(logic, {
2833
+ id: actorId,
2834
+ parent: _actorScope.self,
2835
+ syncSnapshot: actorData.syncSnapshot,
2836
+ snapshot: childState,
2837
+ src,
2838
+ systemId: actorData.systemId
2839
+ });
2840
+ });
2841
+ function resolveHistoryReferencedState(root, referenced) {
2842
+ if (referenced instanceof StateNode) return referenced;
2843
+ try {
2844
+ return root.machine.getStateNodeById(referenced.id);
2845
+ } catch {}
2846
+ }
2847
+ function reviveHistoryValue(root, historyValue) {
2848
+ if (!historyValue || typeof historyValue !== "object") return {};
2849
+ const revived = {};
2850
+ for (const key in historyValue) {
2851
+ const arr = historyValue[key];
2852
+ for (const item of arr) {
2853
+ const resolved = resolveHistoryReferencedState(root, item);
2854
+ if (!resolved) continue;
2855
+ revived[key] ??= [];
2856
+ revived[key].push(resolved);
2857
+ }
2858
+ }
2859
+ return revived;
2860
+ }
2861
+ const revivedHistoryValue = reviveHistoryValue(this.root, snapshot.historyValue);
2862
+ const restoredSnapshot = createMachineSnapshot({
2863
+ ...snapshot,
2864
+ children,
2865
+ _nodes: Array.from(getAllStateNodes(getStateNodes(this.root, snapshot.value))),
2866
+ historyValue: revivedHistoryValue
2867
+ }, this);
2868
+ const seen = /* @__PURE__ */ new Set();
2869
+ function reviveContext(contextPart, children$1) {
2870
+ if (seen.has(contextPart)) return;
2871
+ seen.add(contextPart);
2872
+ for (const key in contextPart) {
2873
+ const value = contextPart[key];
2874
+ if (value && typeof value === "object") {
2875
+ if ("xstate$$type" in value && value.xstate$$type === $$ACTOR_TYPE) {
2876
+ contextPart[key] = children$1[value.id];
2877
+ continue;
2878
+ }
2879
+ reviveContext(value, children$1);
2880
+ }
2881
+ }
2882
+ }
2883
+ reviveContext(restoredSnapshot.context, children);
2884
+ return restoredSnapshot;
2885
+ }
2886
+ };
2887
+
2888
+ //#endregion
2889
+ //#region ../../node_modules/.pnpm/xstate@5.24.0/node_modules/xstate/dist/log-7cbae384.esm.js
2890
+ function resolveEmit(_, snapshot, args, actionParams, { event: eventOrExpr }) {
2891
+ return [
2892
+ snapshot,
2893
+ { event: typeof eventOrExpr === "function" ? eventOrExpr(args, actionParams) : eventOrExpr },
2894
+ void 0
2895
+ ];
2896
+ }
2897
+ function executeEmit(actorScope, { event }) {
2898
+ actorScope.defer(() => actorScope.emit(event));
2899
+ }
2900
+ /**
2901
+ * Emits an event to event handlers registered on the actor via `actor.on(event,
2902
+ * handler)`.
2903
+ *
2904
+ * @example
2905
+ *
2906
+ * ```ts
2907
+ * import { emit } from 'xstate';
2908
+ *
2909
+ * const machine = createMachine({
2910
+ * // ...
2911
+ * on: {
2912
+ * something: {
2913
+ * actions: emit({
2914
+ * type: 'emitted',
2915
+ * some: 'data'
2916
+ * })
2917
+ * }
2918
+ * }
2919
+ * // ...
2920
+ * });
2921
+ *
2922
+ * const actor = createActor(machine).start();
2923
+ *
2924
+ * actor.on('emitted', (event) => {
2925
+ * console.log(event);
2926
+ * });
2927
+ *
2928
+ * actor.send({ type: 'something' });
2929
+ * // logs:
2930
+ * // {
2931
+ * // type: 'emitted',
2932
+ * // some: 'data'
2933
+ * // }
2934
+ * ```
2935
+ */
2936
+ function emit(eventOrExpr) {
2937
+ function emit$1(_args, _params) {}
2938
+ emit$1.type = "xstate.emit";
2939
+ emit$1.event = eventOrExpr;
2940
+ emit$1.resolve = resolveEmit;
2941
+ emit$1.execute = executeEmit;
2942
+ return emit$1;
2943
+ }
2944
+ /**
2945
+ * @remarks
2946
+ * `T | unknown` reduces to `unknown` and that can be problematic when it comes
2947
+ * to contextual typing. It especially is a problem when the union has a
2948
+ * function member, like here:
2949
+ *
2950
+ * ```ts
2951
+ * declare function test(
2952
+ * cbOrVal: ((arg: number) => unknown) | unknown
2953
+ * ): void;
2954
+ * test((arg) => {}); // oops, implicit any
2955
+ * ```
2956
+ *
2957
+ * This type can be used to avoid this problem. This union represents the same
2958
+ * value space as `unknown`.
2959
+ */
2960
+ /** @deprecated Use the built-in `NoInfer` type instead */
2961
+ /** The full definition of an event, with a string `type`. */
2962
+ /**
2963
+ * The string or object representing the state value relative to the parent
2964
+ * state node.
2965
+ *
2966
+ * @remarks
2967
+ * - For a child atomic state node, this is a string, e.g., `"pending"`.
2968
+ * - For complex state nodes, this is an object, e.g., `{ success:
2969
+ * "someChildState" }`.
2970
+ */
2971
+ /** @deprecated Use `AnyMachineSnapshot` instead */
2972
+ /** @ignore */
2973
+ let SpecialTargets = /* @__PURE__ */ function(SpecialTargets$1) {
2974
+ SpecialTargets$1["Parent"] = "#_parent";
2975
+ SpecialTargets$1["Internal"] = "#_internal";
2976
+ return SpecialTargets$1;
2977
+ }({});
2978
+ /** @deprecated Use `AnyActor` instead. */
2979
+ /** @deprecated Use `Actor<T>` instead. */
2980
+ /**
2981
+ * Represents logic which can be used by an actor.
2982
+ *
2983
+ * @template TSnapshot - The type of the snapshot.
2984
+ * @template TEvent - The type of the event object.
2985
+ * @template TInput - The type of the input.
2986
+ * @template TSystem - The type of the actor system.
2987
+ */
2988
+ /** @deprecated */
2989
+ function resolveSendTo(actorScope, snapshot, args, actionParams, { to, event: eventOrExpr, id, delay }, extra) {
2990
+ const delaysMap = snapshot.machine.implementations.delays;
2991
+ if (typeof eventOrExpr === "string") throw new Error(`Only event objects may be used with sendTo; use sendTo({ type: "${eventOrExpr}" }) instead`);
2992
+ const resolvedEvent = typeof eventOrExpr === "function" ? eventOrExpr(args, actionParams) : eventOrExpr;
2993
+ let resolvedDelay;
2994
+ if (typeof delay === "string") {
2995
+ const configDelay = delaysMap && delaysMap[delay];
2996
+ resolvedDelay = typeof configDelay === "function" ? configDelay(args, actionParams) : configDelay;
2997
+ } else resolvedDelay = typeof delay === "function" ? delay(args, actionParams) : delay;
2998
+ const resolvedTarget = typeof to === "function" ? to(args, actionParams) : to;
2999
+ let targetActorRef;
3000
+ if (typeof resolvedTarget === "string") {
3001
+ if (resolvedTarget === SpecialTargets.Parent) targetActorRef = actorScope.self._parent;
3002
+ else if (resolvedTarget === SpecialTargets.Internal) targetActorRef = actorScope.self;
3003
+ else if (resolvedTarget.startsWith("#_")) targetActorRef = snapshot.children[resolvedTarget.slice(2)];
3004
+ else targetActorRef = extra.deferredActorIds?.includes(resolvedTarget) ? resolvedTarget : snapshot.children[resolvedTarget];
3005
+ if (!targetActorRef) throw new Error(`Unable to send event to actor '${resolvedTarget}' from machine '${snapshot.machine.id}'.`);
3006
+ } else targetActorRef = resolvedTarget || actorScope.self;
3007
+ return [
3008
+ snapshot,
3009
+ {
3010
+ to: targetActorRef,
3011
+ targetId: typeof resolvedTarget === "string" ? resolvedTarget : void 0,
3012
+ event: resolvedEvent,
3013
+ id,
3014
+ delay: resolvedDelay
3015
+ },
3016
+ void 0
3017
+ ];
3018
+ }
3019
+ function retryResolveSendTo(_, snapshot, params) {
3020
+ if (typeof params.to === "string") params.to = snapshot.children[params.to];
3021
+ }
3022
+ function executeSendTo(actorScope, params) {
3023
+ actorScope.defer(() => {
3024
+ const { to, event, delay, id } = params;
3025
+ if (typeof delay === "number") {
3026
+ actorScope.system.scheduler.schedule(actorScope.self, to, event, delay, id);
3027
+ return;
3028
+ }
3029
+ actorScope.system._relay(actorScope.self, to, event.type === XSTATE_ERROR ? createErrorActorEvent(actorScope.self.id, event.data) : event);
3030
+ });
3031
+ }
3032
+ /**
3033
+ * Sends an event to an actor.
3034
+ *
3035
+ * @param actor The `ActorRef` to send the event to.
3036
+ * @param event The event to send, or an expression that evaluates to the event
3037
+ * to send
3038
+ * @param options Send action options
3039
+ *
3040
+ * - `id` - The unique send event identifier (used with `cancel()`).
3041
+ * - `delay` - The number of milliseconds to delay the sending of the event.
3042
+ */
3043
+ function sendTo(to, eventOrExpr, options) {
3044
+ function sendTo$1(_args, _params) {}
3045
+ sendTo$1.type = "xstate.sendTo";
3046
+ sendTo$1.to = to;
3047
+ sendTo$1.event = eventOrExpr;
3048
+ sendTo$1.id = options?.id;
3049
+ sendTo$1.delay = options?.delay;
3050
+ sendTo$1.resolve = resolveSendTo;
3051
+ sendTo$1.retryResolve = retryResolveSendTo;
3052
+ sendTo$1.execute = executeSendTo;
3053
+ return sendTo$1;
3054
+ }
3055
+ /**
3056
+ * Sends an event to this machine's parent.
3057
+ *
3058
+ * @param event The event to send to the parent machine.
3059
+ * @param options Options to pass into the send event.
3060
+ */
3061
+ function sendParent(event, options) {
3062
+ return sendTo(SpecialTargets.Parent, event, options);
3063
+ }
3064
+ function resolveEnqueueActions(actorScope, snapshot, args, actionParams, { collect }) {
3065
+ const actions = [];
3066
+ const enqueue = function enqueue$1(action) {
3067
+ actions.push(action);
3068
+ };
3069
+ enqueue.assign = (...args$1) => {
3070
+ actions.push(assign(...args$1));
3071
+ };
3072
+ enqueue.cancel = (...args$1) => {
3073
+ actions.push(cancel(...args$1));
3074
+ };
3075
+ enqueue.raise = (...args$1) => {
3076
+ actions.push(raise(...args$1));
3077
+ };
3078
+ enqueue.sendTo = (...args$1) => {
3079
+ actions.push(sendTo(...args$1));
3080
+ };
3081
+ enqueue.sendParent = (...args$1) => {
3082
+ actions.push(sendParent(...args$1));
3083
+ };
3084
+ enqueue.spawnChild = (...args$1) => {
3085
+ actions.push(spawnChild(...args$1));
3086
+ };
3087
+ enqueue.stopChild = (...args$1) => {
3088
+ actions.push(stopChild(...args$1));
3089
+ };
3090
+ enqueue.emit = (...args$1) => {
3091
+ actions.push(emit(...args$1));
3092
+ };
3093
+ collect({
3094
+ context: args.context,
3095
+ event: args.event,
3096
+ enqueue,
3097
+ check: (guard) => evaluateGuard(guard, snapshot.context, args.event, snapshot),
3098
+ self: actorScope.self,
3099
+ system: actorScope.system
3100
+ }, actionParams);
3101
+ return [
3102
+ snapshot,
3103
+ void 0,
3104
+ actions
3105
+ ];
3106
+ }
3107
+ /**
3108
+ * Creates an action object that will execute actions that are queued by the
3109
+ * `enqueue(action)` function.
3110
+ *
3111
+ * @example
3112
+ *
3113
+ * ```ts
3114
+ * import { createMachine, enqueueActions } from 'xstate';
3115
+ *
3116
+ * const machine = createMachine({
3117
+ * entry: enqueueActions(({ enqueue, check }) => {
3118
+ * enqueue.assign({ count: 0 });
3119
+ *
3120
+ * if (check('someGuard')) {
3121
+ * enqueue.assign({ count: 1 });
3122
+ * }
3123
+ *
3124
+ * enqueue('someAction');
3125
+ * })
3126
+ * });
3127
+ * ```
3128
+ */
3129
+ function enqueueActions(collect) {
3130
+ function enqueueActions$1(_args, _params) {}
3131
+ enqueueActions$1.type = "xstate.enqueueActions";
3132
+ enqueueActions$1.collect = collect;
3133
+ enqueueActions$1.resolve = resolveEnqueueActions;
3134
+ return enqueueActions$1;
3135
+ }
3136
+ function resolveLog(_, snapshot, actionArgs, actionParams, { value, label }) {
3137
+ return [
3138
+ snapshot,
3139
+ {
3140
+ value: typeof value === "function" ? value(actionArgs, actionParams) : value,
3141
+ label
3142
+ },
3143
+ void 0
3144
+ ];
3145
+ }
3146
+ function executeLog({ logger }, { value, label }) {
3147
+ if (label) logger(label, value);
3148
+ else logger(value);
3149
+ }
3150
+ /**
3151
+ * @param expr The expression function to evaluate which will be logged. Takes
3152
+ * in 2 arguments:
3153
+ *
3154
+ * - `ctx` - the current state context
3155
+ * - `event` - the event that caused this action to be executed.
3156
+ *
3157
+ * @param label The label to give to the logged expression.
3158
+ */
3159
+ function log(value = ({ context, event }) => ({
3160
+ context,
3161
+ event
3162
+ }), label) {
3163
+ function log$1(_args, _params) {}
3164
+ log$1.type = "xstate.log";
3165
+ log$1.value = value;
3166
+ log$1.label = label;
3167
+ log$1.resolve = resolveLog;
3168
+ log$1.execute = executeLog;
3169
+ return log$1;
3170
+ }
3171
+
3172
+ //#endregion
3173
+ //#region ../../node_modules/.pnpm/xstate@5.24.0/node_modules/xstate/dist/xstate.esm.js
3174
+ /**
3175
+ * Creates a state machine (statechart) with the given configuration.
3176
+ *
3177
+ * The state machine represents the pure logic of a state machine actor.
3178
+ *
3179
+ * @example
3180
+ *
3181
+ * ```ts
3182
+ * import { createMachine } from 'xstate';
3183
+ *
3184
+ * const lightMachine = createMachine({
3185
+ * id: 'light',
3186
+ * initial: 'green',
3187
+ * states: {
3188
+ * green: {
3189
+ * on: {
3190
+ * TIMER: { target: 'yellow' }
3191
+ * }
3192
+ * },
3193
+ * yellow: {
3194
+ * on: {
3195
+ * TIMER: { target: 'red' }
3196
+ * }
3197
+ * },
3198
+ * red: {
3199
+ * on: {
3200
+ * TIMER: { target: 'green' }
3201
+ * }
3202
+ * }
3203
+ * }
3204
+ * });
3205
+ *
3206
+ * const lightActor = createActor(lightMachine);
3207
+ * lightActor.start();
3208
+ *
3209
+ * lightActor.send({ type: 'TIMER' });
3210
+ * ```
3211
+ *
3212
+ * @param config The state machine configuration.
3213
+ * @param options DEPRECATED: use `setup({ ... })` or `machine.provide({ ... })`
3214
+ * to provide machine implementations instead.
3215
+ */
3216
+ function createMachine(config, implementations) {
3217
+ return new StateMachine(config, implementations);
3218
+ }
3219
+ function setup({ schemas, actors, actions, guards, delays }) {
3220
+ return {
3221
+ assign,
3222
+ sendTo,
3223
+ raise,
3224
+ log,
3225
+ cancel,
3226
+ stopChild,
3227
+ enqueueActions,
3228
+ emit,
3229
+ spawnChild,
3230
+ createStateConfig: (config) => config,
3231
+ createAction: (fn) => fn,
3232
+ createMachine: (config) => createMachine({
3233
+ ...config,
3234
+ schemas
3235
+ }, {
3236
+ actors,
3237
+ actions,
3238
+ guards,
3239
+ delays
3240
+ }),
3241
+ extend: (extended) => setup({
3242
+ schemas,
3243
+ actors,
3244
+ actions: {
3245
+ ...actions,
3246
+ ...extended.actions
3247
+ },
3248
+ guards: {
3249
+ ...guards,
3250
+ ...extended.guards
3251
+ },
3252
+ delays: {
3253
+ ...delays,
3254
+ ...extended.delays
3255
+ }
3256
+ })
3257
+ };
3258
+ }
3259
+
3260
+ //#endregion
3261
+ export { createActor as a, fromPromise as i, assign as n, fromCallback as r, setup as t };