xstate 5.0.0-beta.27 → 5.0.0-beta.29

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 (67) hide show
  1. package/README.md +9 -7
  2. package/actions/dist/xstate-actions.cjs.js +11 -17
  3. package/actions/dist/xstate-actions.cjs.mjs +0 -8
  4. package/actions/dist/xstate-actions.development.cjs.js +11 -17
  5. package/actions/dist/xstate-actions.development.cjs.mjs +0 -8
  6. package/actions/dist/xstate-actions.development.esm.js +3 -1
  7. package/actions/dist/xstate-actions.esm.js +3 -1
  8. package/actions/dist/xstate-actions.umd.min.js +1 -1
  9. package/actions/dist/xstate-actions.umd.min.js.map +1 -1
  10. package/actors/dist/xstate-actors.cjs.js +395 -28
  11. package/actors/dist/xstate-actors.cjs.mjs +1 -3
  12. package/actors/dist/xstate-actors.development.cjs.js +395 -28
  13. package/actors/dist/xstate-actors.development.cjs.mjs +1 -3
  14. package/actors/dist/xstate-actors.development.esm.js +389 -21
  15. package/actors/dist/xstate-actors.esm.js +389 -21
  16. package/actors/dist/xstate-actors.umd.min.js +1 -1
  17. package/actors/dist/xstate-actors.umd.min.js.map +1 -1
  18. package/dist/declarations/src/StateNode.d.ts +3 -3
  19. package/dist/declarations/src/actions/assign.d.ts +9 -4
  20. package/dist/declarations/src/actions/cancel.d.ts +4 -4
  21. package/dist/declarations/src/actions/choose.d.ts +5 -4
  22. package/dist/declarations/src/actions/log.d.ts +4 -4
  23. package/dist/declarations/src/actions/pure.d.ts +6 -5
  24. package/dist/declarations/src/actions/raise.d.ts +2 -2
  25. package/dist/declarations/src/actions/send.d.ts +7 -7
  26. package/dist/declarations/src/actions/stop.d.ts +4 -4
  27. package/dist/declarations/src/actions.d.ts +8 -44
  28. package/dist/declarations/src/actors/callback.d.ts +2 -2
  29. package/dist/declarations/src/actors/index.d.ts +3 -5
  30. package/dist/declarations/src/constants.d.ts +1 -0
  31. package/dist/declarations/src/index.d.ts +9 -16
  32. package/dist/declarations/src/spawn.d.ts +25 -0
  33. package/dist/declarations/src/stateUtils.d.ts +1 -1
  34. package/dist/declarations/src/typegenTypes.d.ts +4 -4
  35. package/dist/declarations/src/types.d.ts +92 -122
  36. package/dist/declarations/src/utils.d.ts +2 -2
  37. package/dist/interpreter-498891b2.esm.js +741 -0
  38. package/dist/interpreter-6e7909c8.development.esm.js +749 -0
  39. package/dist/interpreter-c357bc50.cjs.js +773 -0
  40. package/dist/interpreter-e2c6a579.development.cjs.js +781 -0
  41. package/dist/{actions-9754d2ca.development.esm.js → raise-03e57569.cjs.js} +130 -1307
  42. package/dist/{actions-d1dba4ac.cjs.js → raise-59f2c242.esm.js} +65 -1267
  43. package/dist/{actions-020463e9.esm.js → raise-e778a828.development.esm.js} +109 -1203
  44. package/dist/{actions-ca622922.development.cjs.js → raise-f751dfac.development.cjs.js} +101 -1306
  45. package/dist/send-42c83fb2.development.esm.js +364 -0
  46. package/dist/send-51717e53.cjs.js +349 -0
  47. package/dist/send-f53778f6.development.cjs.js +374 -0
  48. package/dist/send-fff224db.esm.js +339 -0
  49. package/dist/xstate.cjs.js +114 -112
  50. package/dist/xstate.cjs.mjs +2 -2
  51. package/dist/xstate.development.cjs.js +114 -112
  52. package/dist/xstate.development.cjs.mjs +2 -2
  53. package/dist/xstate.development.esm.js +78 -74
  54. package/dist/xstate.esm.js +78 -74
  55. package/dist/xstate.umd.min.js +1 -1
  56. package/dist/xstate.umd.min.js.map +1 -1
  57. package/guards/dist/xstate-guards.cjs.js +2 -1
  58. package/guards/dist/xstate-guards.development.cjs.js +2 -1
  59. package/guards/dist/xstate-guards.development.esm.js +2 -1
  60. package/guards/dist/xstate-guards.esm.js +2 -1
  61. package/guards/dist/xstate-guards.umd.min.js.map +1 -1
  62. package/package.json +1 -1
  63. package/dist/declarations/src/constantPrefixes.d.ts +0 -6
  64. package/dist/promise-2ad94e3b.development.esm.js +0 -406
  65. package/dist/promise-3b7e3357.development.cjs.js +0 -412
  66. package/dist/promise-5b07c38e.esm.js +0 -406
  67. package/dist/promise-7a8c1768.cjs.js +0 -412
@@ -0,0 +1,773 @@
1
+ 'use strict';
2
+
3
+ var dev_dist_xstateDev = require('../dev/dist/xstate-dev.cjs.js');
4
+
5
+ const STATE_DELIMITER = '.';
6
+ const TARGETLESS_KEY = '';
7
+ const NULL_EVENT = '';
8
+ const STATE_IDENTIFIER = '#';
9
+ const WILDCARD = '*';
10
+ const XSTATE_INIT = 'xstate.init';
11
+ const XSTATE_ERROR = 'xstate.error';
12
+ const XSTATE_STOP = 'xstate.stop';
13
+
14
+ /**
15
+ * Returns an event that represents an implicit event that
16
+ * is sent after the specified `delay`.
17
+ *
18
+ * @param delayRef The delay in milliseconds
19
+ * @param id The state node ID where this event is handled
20
+ */
21
+ function createAfterEvent(delayRef, id) {
22
+ const idSuffix = id ? `#${id}` : '';
23
+ return {
24
+ type: `xstate.after(${delayRef})${idSuffix}`
25
+ };
26
+ }
27
+
28
+ /**
29
+ * Returns an event that represents that a final state node
30
+ * has been reached in the parent state node.
31
+ *
32
+ * @param id The final state node's parent state node `id`
33
+ * @param output The data to pass into the event
34
+ */
35
+ function createDoneStateEvent(id, output) {
36
+ return {
37
+ type: `xstate.done.state.${id}`,
38
+ output
39
+ };
40
+ }
41
+
42
+ /**
43
+ * Returns an event that represents that an invoked service has terminated.
44
+ *
45
+ * An invoked service is terminated when it has reached a top-level final state node,
46
+ * but not when it is canceled.
47
+ *
48
+ * @param invokeId The invoked service ID
49
+ * @param output The data to pass into the event
50
+ */
51
+ function createDoneActorEvent(invokeId, output) {
52
+ return {
53
+ type: `xstate.done.actor.${invokeId}`,
54
+ output
55
+ };
56
+ }
57
+ function createErrorActorEvent(id, data) {
58
+ return {
59
+ type: `xstate.error.actor.${id}`,
60
+ data
61
+ };
62
+ }
63
+ function createInitEvent(input) {
64
+ return {
65
+ type: XSTATE_INIT,
66
+ input
67
+ };
68
+ }
69
+
70
+ class Mailbox {
71
+ constructor(_process) {
72
+ this._process = _process;
73
+ this._active = false;
74
+ this._current = null;
75
+ this._last = null;
76
+ }
77
+ start() {
78
+ this._active = true;
79
+ this.flush();
80
+ }
81
+ clear() {
82
+ // we can't set _current to null because we might be currently processing
83
+ // and enqueue following clear shouldnt start processing the enqueued item immediately
84
+ if (this._current) {
85
+ this._current.next = null;
86
+ this._last = this._current;
87
+ }
88
+ }
89
+
90
+ // TODO: rethink this design
91
+ prepend(event) {
92
+ if (!this._current) {
93
+ this.enqueue(event);
94
+ return;
95
+ }
96
+
97
+ // we know that something is already queued up
98
+ // so the mailbox is already flushing or it's inactive
99
+ // therefore the only thing that we need to do is to reassign `this._current`
100
+ this._current = {
101
+ value: event,
102
+ next: this._current
103
+ };
104
+ }
105
+ enqueue(event) {
106
+ const enqueued = {
107
+ value: event,
108
+ next: null
109
+ };
110
+ if (this._current) {
111
+ this._last.next = enqueued;
112
+ this._last = enqueued;
113
+ return;
114
+ }
115
+ this._current = enqueued;
116
+ this._last = enqueued;
117
+ if (this._active) {
118
+ this.flush();
119
+ }
120
+ }
121
+ flush() {
122
+ while (this._current) {
123
+ // atm the given _process is responsible for implementing proper try/catch handling
124
+ // we assume here that this won't throw in a way that can affect this mailbox
125
+ const consumed = this._current;
126
+ this._process(consumed.value);
127
+ // something could have been prepended in the meantime
128
+ // so we need to be defensive here to avoid skipping over a prepended item
129
+ if (consumed === this._current) {
130
+ this._current = this._current.next;
131
+ }
132
+ }
133
+ this._last = null;
134
+ }
135
+ }
136
+
137
+ /**
138
+ * This function makes sure that unhandled errors are thrown in a separate macrotask.
139
+ * It allows those errors to be detected by global error handlers and reported to bug tracking services
140
+ * without interrupting our own stack of execution.
141
+ *
142
+ * @param err error to be thrown
143
+ */
144
+ function reportUnhandledError(err) {
145
+ setTimeout(() => {
146
+ throw err;
147
+ });
148
+ }
149
+
150
+ const symbolObservable = (() => typeof Symbol === 'function' && Symbol.observable || '@@observable')();
151
+
152
+ function createSystem() {
153
+ let sessionIdCounter = 0;
154
+ const children = new Map();
155
+ const keyedActors = new Map();
156
+ const reverseKeyedActors = new WeakMap();
157
+ const system = {
158
+ _bookId: () => `x:${sessionIdCounter++}`,
159
+ _register: (sessionId, actorRef) => {
160
+ children.set(sessionId, actorRef);
161
+ return sessionId;
162
+ },
163
+ _unregister: actorRef => {
164
+ children.delete(actorRef.sessionId);
165
+ const systemId = reverseKeyedActors.get(actorRef);
166
+ if (systemId !== undefined) {
167
+ keyedActors.delete(systemId);
168
+ reverseKeyedActors.delete(actorRef);
169
+ }
170
+ },
171
+ get: systemId => {
172
+ return keyedActors.get(systemId);
173
+ },
174
+ _set: (systemId, actorRef) => {
175
+ const existing = keyedActors.get(systemId);
176
+ if (existing && existing !== actorRef) {
177
+ throw new Error(`Actor with system ID '${systemId}' already exists.`);
178
+ }
179
+ keyedActors.set(systemId, actorRef);
180
+ reverseKeyedActors.set(actorRef, systemId);
181
+ }
182
+ };
183
+ return system;
184
+ }
185
+
186
+ function matchesState(parentStateId, childStateId) {
187
+ const parentStateValue = toStateValue(parentStateId);
188
+ const childStateValue = toStateValue(childStateId);
189
+ if (typeof childStateValue === 'string') {
190
+ if (typeof parentStateValue === 'string') {
191
+ return childStateValue === parentStateValue;
192
+ }
193
+
194
+ // Parent more specific than child
195
+ return false;
196
+ }
197
+ if (typeof parentStateValue === 'string') {
198
+ return parentStateValue in childStateValue;
199
+ }
200
+ return Object.keys(parentStateValue).every(key => {
201
+ if (!(key in childStateValue)) {
202
+ return false;
203
+ }
204
+ return matchesState(parentStateValue[key], childStateValue[key]);
205
+ });
206
+ }
207
+ function toStatePath(stateId) {
208
+ try {
209
+ if (isArray(stateId)) {
210
+ return stateId;
211
+ }
212
+ return stateId.toString().split(STATE_DELIMITER);
213
+ } catch (e) {
214
+ throw new Error(`'${stateId}' is not a valid state path.`);
215
+ }
216
+ }
217
+ function isStateLike(state) {
218
+ return typeof state === 'object' && 'value' in state && 'context' in state && 'event' in state;
219
+ }
220
+ function toStateValue(stateValue) {
221
+ if (isStateLike(stateValue)) {
222
+ return stateValue.value;
223
+ }
224
+ if (isArray(stateValue)) {
225
+ return pathToStateValue(stateValue);
226
+ }
227
+ if (typeof stateValue !== 'string') {
228
+ return stateValue;
229
+ }
230
+ const statePath = toStatePath(stateValue);
231
+ return pathToStateValue(statePath);
232
+ }
233
+ function pathToStateValue(statePath) {
234
+ if (statePath.length === 1) {
235
+ return statePath[0];
236
+ }
237
+ const value = {};
238
+ let marker = value;
239
+ for (let i = 0; i < statePath.length - 1; i++) {
240
+ if (i === statePath.length - 2) {
241
+ marker[statePath[i]] = statePath[i + 1];
242
+ } else {
243
+ const previous = marker;
244
+ marker = {};
245
+ previous[statePath[i]] = marker;
246
+ }
247
+ }
248
+ return value;
249
+ }
250
+ function mapValues(collection, iteratee) {
251
+ const result = {};
252
+ const collectionKeys = Object.keys(collection);
253
+ for (let i = 0; i < collectionKeys.length; i++) {
254
+ const key = collectionKeys[i];
255
+ result[key] = iteratee(collection[key], key, collection, i);
256
+ }
257
+ return result;
258
+ }
259
+ function flatten(array) {
260
+ return [].concat(...array);
261
+ }
262
+ function toArrayStrict(value) {
263
+ if (isArray(value)) {
264
+ return value;
265
+ }
266
+ return [value];
267
+ }
268
+ function toArray(value) {
269
+ if (value === undefined) {
270
+ return [];
271
+ }
272
+ return toArrayStrict(value);
273
+ }
274
+ function mapContext(mapper, context, event, self) {
275
+ if (typeof mapper === 'function') {
276
+ return mapper({
277
+ context,
278
+ event,
279
+ self
280
+ });
281
+ }
282
+ return mapper;
283
+ }
284
+ function isArray(value) {
285
+ return Array.isArray(value);
286
+ }
287
+ function isErrorActorEvent(event) {
288
+ return event.type.startsWith('xstate.error.actor');
289
+ }
290
+ function toTransitionConfigArray(configLike) {
291
+ return toArrayStrict(configLike).map(transitionLike => {
292
+ if (typeof transitionLike === 'undefined' || typeof transitionLike === 'string') {
293
+ return {
294
+ target: transitionLike
295
+ };
296
+ }
297
+ return transitionLike;
298
+ });
299
+ }
300
+ function normalizeTarget(target) {
301
+ if (target === undefined || target === TARGETLESS_KEY) {
302
+ return undefined;
303
+ }
304
+ return toArray(target);
305
+ }
306
+ function toObserver(nextHandler, errorHandler, completionHandler) {
307
+ const isObserver = typeof nextHandler === 'object';
308
+ const self = isObserver ? nextHandler : undefined;
309
+ return {
310
+ next: (isObserver ? nextHandler.next : nextHandler)?.bind(self),
311
+ error: (isObserver ? nextHandler.error : errorHandler)?.bind(self),
312
+ complete: (isObserver ? nextHandler.complete : completionHandler)?.bind(self)
313
+ };
314
+ }
315
+ function createInvokeId(stateNodeId, index) {
316
+ return `${stateNodeId}:invocation[${index}]`;
317
+ }
318
+ function resolveReferencedActor(referenced) {
319
+ return referenced ? 'transition' in referenced ? {
320
+ src: referenced,
321
+ input: undefined
322
+ } : referenced : undefined;
323
+ }
324
+
325
+ let ActorStatus = /*#__PURE__*/function (ActorStatus) {
326
+ ActorStatus[ActorStatus["NotStarted"] = 0] = "NotStarted";
327
+ ActorStatus[ActorStatus["Running"] = 1] = "Running";
328
+ ActorStatus[ActorStatus["Stopped"] = 2] = "Stopped";
329
+ return ActorStatus;
330
+ }({});
331
+
332
+ /**
333
+ * @deprecated Use `ActorStatus` instead.
334
+ */
335
+ const InterpreterStatus = ActorStatus;
336
+ const defaultOptions = {
337
+ clock: {
338
+ setTimeout: (fn, ms) => {
339
+ return setTimeout(fn, ms);
340
+ },
341
+ clearTimeout: id => {
342
+ return clearTimeout(id);
343
+ }
344
+ },
345
+ logger: console.log.bind(console),
346
+ devTools: false
347
+ };
348
+ class Actor {
349
+ /**
350
+ * The current internal state of the actor.
351
+ */
352
+
353
+ /**
354
+ * The clock that is responsible for setting and clearing timeouts, such as delayed events and transitions.
355
+ */
356
+
357
+ /**
358
+ * The unique identifier for this actor relative to its parent.
359
+ */
360
+
361
+ /**
362
+ * Whether the service is started.
363
+ */
364
+
365
+ // Actor Ref
366
+
367
+ // TODO: add typings for system
368
+
369
+ /**
370
+ * The globally unique process ID for this invocation.
371
+ */
372
+
373
+ /**
374
+ * Creates a new actor instance for the given logic with the provided options, if any.
375
+ *
376
+ * @param logic The logic to create an actor from
377
+ * @param options Actor options
378
+ */
379
+ constructor(logic, options) {
380
+ this.logic = logic;
381
+ this._state = void 0;
382
+ this.clock = void 0;
383
+ this.options = void 0;
384
+ this.id = void 0;
385
+ this.mailbox = new Mailbox(this._process.bind(this));
386
+ this.delayedEventsMap = {};
387
+ this.observers = new Set();
388
+ this.logger = void 0;
389
+ this.status = ActorStatus.NotStarted;
390
+ this._parent = void 0;
391
+ this.ref = void 0;
392
+ this._actorContext = void 0;
393
+ this._systemId = void 0;
394
+ this.sessionId = void 0;
395
+ this.system = void 0;
396
+ this._doneEvent = void 0;
397
+ this.src = void 0;
398
+ this._deferred = [];
399
+ const resolvedOptions = {
400
+ ...defaultOptions,
401
+ ...options
402
+ };
403
+ const {
404
+ clock,
405
+ logger,
406
+ parent,
407
+ id,
408
+ systemId
409
+ } = resolvedOptions;
410
+ const self = this;
411
+ this.system = parent?.system ?? createSystem();
412
+ if (systemId) {
413
+ this._systemId = systemId;
414
+ this.system._set(systemId, this);
415
+ }
416
+ this.sessionId = this.system._bookId();
417
+ this.id = id ?? this.sessionId;
418
+ this.logger = logger;
419
+ this.clock = clock;
420
+ this._parent = parent;
421
+ this.options = resolvedOptions;
422
+ this.src = resolvedOptions.src;
423
+ this.ref = this;
424
+ this._actorContext = {
425
+ self,
426
+ id: this.id,
427
+ sessionId: this.sessionId,
428
+ logger: this.logger,
429
+ defer: fn => {
430
+ this._deferred.push(fn);
431
+ },
432
+ system: this.system,
433
+ stopChild: child => {
434
+ if (child._parent !== this) {
435
+ throw new Error(`Cannot stop child actor ${child.id} of ${this.id} because it is not a child`);
436
+ }
437
+ child._stop();
438
+ }
439
+ };
440
+
441
+ // Ensure that the send method is bound to this Actor instance
442
+ // if destructured
443
+ this.send = this.send.bind(this);
444
+ this._initState();
445
+ }
446
+ _initState() {
447
+ this._state = this.options.state ? this.logic.restoreState ? this.logic.restoreState(this.options.state, this._actorContext) : this.options.state : this.logic.getInitialState(this._actorContext, this.options?.input);
448
+ }
449
+
450
+ // array of functions to defer
451
+
452
+ update(state) {
453
+ // Update state
454
+ this._state = state;
455
+ const snapshot = this.getSnapshot();
456
+
457
+ // Execute deferred effects
458
+ let deferredFn;
459
+ while (deferredFn = this._deferred.shift()) {
460
+ deferredFn();
461
+ }
462
+ for (const observer of this.observers) {
463
+ // TODO: should observers be notified in case of the error?
464
+ try {
465
+ observer.next?.(snapshot);
466
+ } catch (err) {
467
+ reportUnhandledError(err);
468
+ }
469
+ }
470
+ const status = this.logic.getStatus?.(state);
471
+ switch (status?.status) {
472
+ case 'done':
473
+ this._stopProcedure();
474
+ this._complete();
475
+ this._doneEvent = createDoneActorEvent(this.id, status.data);
476
+ this._parent?.send(this._doneEvent);
477
+ break;
478
+ case 'error':
479
+ this._stopProcedure();
480
+ this._error(status.data);
481
+ this._parent?.send(createErrorActorEvent(this.id, status.data));
482
+ break;
483
+ }
484
+ }
485
+ subscribe(nextListenerOrObserver, errorListener, completeListener) {
486
+ const observer = toObserver(nextListenerOrObserver, errorListener, completeListener);
487
+ if (this.status !== ActorStatus.Stopped) {
488
+ this.observers.add(observer);
489
+ } else {
490
+ try {
491
+ observer.complete?.();
492
+ } catch (err) {
493
+ reportUnhandledError(err);
494
+ }
495
+ }
496
+ return {
497
+ unsubscribe: () => {
498
+ this.observers.delete(observer);
499
+ }
500
+ };
501
+ }
502
+
503
+ /**
504
+ * Starts the Actor from the initial state
505
+ */
506
+ start() {
507
+ if (this.status === ActorStatus.Running) {
508
+ // Do not restart the service if it is already started
509
+ return this;
510
+ }
511
+ this.system._register(this.sessionId, this);
512
+ if (this._systemId) {
513
+ this.system._set(this._systemId, this);
514
+ }
515
+ this.status = ActorStatus.Running;
516
+ const status = this.logic.getStatus?.(this._state);
517
+ switch (status?.status) {
518
+ case 'done':
519
+ // a state machine can be "done" upon intialization (it could reach a final state using initial microsteps)
520
+ // we still need to complete observers, flush deferreds etc
521
+ this.update(this._state);
522
+ // fallthrough
523
+ case 'error':
524
+ // TODO: rethink cleanup of observers, mailbox, etc
525
+ return this;
526
+ }
527
+ if (this.logic.start) {
528
+ try {
529
+ this.logic.start(this._state, this._actorContext);
530
+ } catch (err) {
531
+ this._stopProcedure();
532
+ this._error(err);
533
+ this._parent?.send(createErrorActorEvent(this.id, err));
534
+ return this;
535
+ }
536
+ }
537
+
538
+ // TODO: this notifies all subscribers but usually this is redundant
539
+ // there is no real change happening here
540
+ // we need to rethink if this needs to be refactored
541
+ this.update(this._state);
542
+ if (this.options.devTools) {
543
+ this.attachDevTools();
544
+ }
545
+ this.mailbox.start();
546
+ return this;
547
+ }
548
+ _process(event) {
549
+ // TODO: reexamine what happens when an action (or a guard or smth) throws
550
+ let nextState;
551
+ let caughtError;
552
+ try {
553
+ nextState = this.logic.transition(this._state, event, this._actorContext);
554
+ } catch (err) {
555
+ // we wrap it in a box so we can rethrow it later even if falsy value gets caught here
556
+ caughtError = {
557
+ err
558
+ };
559
+ }
560
+ if (caughtError) {
561
+ const {
562
+ err
563
+ } = caughtError;
564
+ this._stopProcedure();
565
+ this._error(err);
566
+ this._parent?.send(createErrorActorEvent(this.id, err));
567
+ return;
568
+ }
569
+ this.update(nextState);
570
+ if (event.type === XSTATE_STOP) {
571
+ this._stopProcedure();
572
+ this._complete();
573
+ }
574
+ }
575
+ _stop() {
576
+ if (this.status === ActorStatus.Stopped) {
577
+ return this;
578
+ }
579
+ this.mailbox.clear();
580
+ if (this.status === ActorStatus.NotStarted) {
581
+ this.status = ActorStatus.Stopped;
582
+ return this;
583
+ }
584
+ this.mailbox.enqueue({
585
+ type: XSTATE_STOP
586
+ });
587
+ return this;
588
+ }
589
+
590
+ /**
591
+ * Stops the Actor and unsubscribe all listeners.
592
+ */
593
+ stop() {
594
+ if (this._parent) {
595
+ throw new Error('A non-root actor cannot be stopped directly.');
596
+ }
597
+ return this._stop();
598
+ }
599
+ _complete() {
600
+ for (const observer of this.observers) {
601
+ try {
602
+ observer.complete?.();
603
+ } catch (err) {
604
+ reportUnhandledError(err);
605
+ }
606
+ }
607
+ this.observers.clear();
608
+ }
609
+ _error(err) {
610
+ if (!this.observers.size) {
611
+ if (!this._parent) {
612
+ reportUnhandledError(err);
613
+ }
614
+ return;
615
+ }
616
+ let reportError = false;
617
+ for (const observer of this.observers) {
618
+ const errorListener = observer.error;
619
+ reportError ||= !errorListener;
620
+ try {
621
+ errorListener?.(err);
622
+ } catch (err2) {
623
+ reportUnhandledError(err2);
624
+ }
625
+ }
626
+ this.observers.clear();
627
+ if (reportError) {
628
+ reportUnhandledError(err);
629
+ }
630
+ }
631
+ _stopProcedure() {
632
+ if (this.status !== ActorStatus.Running) {
633
+ // Actor already stopped; do nothing
634
+ return this;
635
+ }
636
+
637
+ // Cancel all delayed events
638
+ for (const key of Object.keys(this.delayedEventsMap)) {
639
+ this.clock.clearTimeout(this.delayedEventsMap[key]);
640
+ }
641
+
642
+ // TODO: mailbox.reset
643
+ this.mailbox.clear();
644
+ // TODO: after `stop` we must prepare ourselves for receiving events again
645
+ // events sent *after* stop signal must be queued
646
+ // it seems like this should be the common behavior for all of our consumers
647
+ // so perhaps this should be unified somehow for all of them
648
+ this.mailbox = new Mailbox(this._process.bind(this));
649
+ this.status = ActorStatus.Stopped;
650
+ this.system._unregister(this);
651
+ return this;
652
+ }
653
+
654
+ /**
655
+ * Sends an event to the running Actor to trigger a transition.
656
+ *
657
+ * @param event The event to send
658
+ */
659
+ send(event) {
660
+ if (typeof event === 'string') {
661
+ throw new Error(`Only event objects may be sent to actors; use .send({ type: "${event}" }) instead`);
662
+ }
663
+ if (this.status === ActorStatus.Stopped) {
664
+ return;
665
+ }
666
+ this.mailbox.enqueue(event);
667
+ }
668
+
669
+ // TODO: make private (and figure out a way to do this within the machine)
670
+ delaySend({
671
+ event,
672
+ id,
673
+ delay,
674
+ to
675
+ }) {
676
+ const timerId = this.clock.setTimeout(() => {
677
+ if (to) {
678
+ to.send(event);
679
+ } else {
680
+ this.send(event);
681
+ }
682
+ }, delay);
683
+
684
+ // TODO: consider the rehydration story here
685
+ if (id) {
686
+ this.delayedEventsMap[id] = timerId;
687
+ }
688
+ }
689
+
690
+ // TODO: make private (and figure out a way to do this within the machine)
691
+ cancel(sendId) {
692
+ this.clock.clearTimeout(this.delayedEventsMap[sendId]);
693
+ delete this.delayedEventsMap[sendId];
694
+ }
695
+ attachDevTools() {
696
+ const {
697
+ devTools
698
+ } = this.options;
699
+ if (devTools) {
700
+ const resolvedDevToolsAdapter = typeof devTools === 'function' ? devTools : dev_dist_xstateDev.devToolsAdapter;
701
+ resolvedDevToolsAdapter(this);
702
+ }
703
+ }
704
+ toJSON() {
705
+ return {
706
+ id: this.id
707
+ };
708
+ }
709
+ getPersistedState() {
710
+ return this.logic.getPersistedState?.(this._state);
711
+ }
712
+ [symbolObservable]() {
713
+ return this;
714
+ }
715
+ getSnapshot() {
716
+ return this.logic.getSnapshot ? this.logic.getSnapshot(this._state) : this._state;
717
+ }
718
+ }
719
+
720
+ /**
721
+ * Creates a new `ActorRef` instance for the given machine with the provided options, if any.
722
+ *
723
+ * @param machine The machine to create an actor from
724
+ * @param options `ActorRef` options
725
+ */
726
+
727
+ function createActor(logic, options) {
728
+ const interpreter = new Actor(logic, options);
729
+ return interpreter;
730
+ }
731
+
732
+ /**
733
+ * Creates a new Interpreter instance for the given machine with the provided options, if any.
734
+ *
735
+ * @deprecated Use `createActor` instead
736
+ */
737
+ const interpret = createActor;
738
+
739
+ /**
740
+ * @deprecated Use `Actor` instead.
741
+ */
742
+
743
+ exports.Actor = Actor;
744
+ exports.ActorStatus = ActorStatus;
745
+ exports.InterpreterStatus = InterpreterStatus;
746
+ exports.NULL_EVENT = NULL_EVENT;
747
+ exports.STATE_DELIMITER = STATE_DELIMITER;
748
+ exports.STATE_IDENTIFIER = STATE_IDENTIFIER;
749
+ exports.WILDCARD = WILDCARD;
750
+ exports.XSTATE_ERROR = XSTATE_ERROR;
751
+ exports.XSTATE_INIT = XSTATE_INIT;
752
+ exports.XSTATE_STOP = XSTATE_STOP;
753
+ exports.createActor = createActor;
754
+ exports.createAfterEvent = createAfterEvent;
755
+ exports.createDoneStateEvent = createDoneStateEvent;
756
+ exports.createErrorActorEvent = createErrorActorEvent;
757
+ exports.createInitEvent = createInitEvent;
758
+ exports.createInvokeId = createInvokeId;
759
+ exports.flatten = flatten;
760
+ exports.interpret = interpret;
761
+ exports.isArray = isArray;
762
+ exports.isErrorActorEvent = isErrorActorEvent;
763
+ exports.mapContext = mapContext;
764
+ exports.mapValues = mapValues;
765
+ exports.matchesState = matchesState;
766
+ exports.normalizeTarget = normalizeTarget;
767
+ exports.pathToStateValue = pathToStateValue;
768
+ exports.resolveReferencedActor = resolveReferencedActor;
769
+ exports.toArray = toArray;
770
+ exports.toObserver = toObserver;
771
+ exports.toStatePath = toStatePath;
772
+ exports.toStateValue = toStateValue;
773
+ exports.toTransitionConfigArray = toTransitionConfigArray;