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,781 @@
1
+ 'use strict';
2
+
3
+ var dev_dist_xstateDev = require('../dev/dist/xstate-dev.development.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
+ if (typeof mapper === 'object' && Object.values(mapper).some(val => typeof val === 'function')) {
283
+ console.warn(`Dynamically mapping values to individual properties is deprecated. Use a single function that returns the mapped object instead.\nFound object containing properties whose values are possibly mapping functions: ${Object.entries(mapper).filter(([key, value]) => typeof value === 'function').map(([key, value]) => `\n - ${key}: ${value.toString().replace(/\n\s*/g, '')}`).join('')}`);
284
+ }
285
+ return mapper;
286
+ }
287
+ function isArray(value) {
288
+ return Array.isArray(value);
289
+ }
290
+ function isErrorActorEvent(event) {
291
+ return event.type.startsWith('xstate.error.actor');
292
+ }
293
+ function toTransitionConfigArray(configLike) {
294
+ return toArrayStrict(configLike).map(transitionLike => {
295
+ if (typeof transitionLike === 'undefined' || typeof transitionLike === 'string') {
296
+ return {
297
+ target: transitionLike
298
+ };
299
+ }
300
+ return transitionLike;
301
+ });
302
+ }
303
+ function normalizeTarget(target) {
304
+ if (target === undefined || target === TARGETLESS_KEY) {
305
+ return undefined;
306
+ }
307
+ return toArray(target);
308
+ }
309
+ function toObserver(nextHandler, errorHandler, completionHandler) {
310
+ const isObserver = typeof nextHandler === 'object';
311
+ const self = isObserver ? nextHandler : undefined;
312
+ return {
313
+ next: (isObserver ? nextHandler.next : nextHandler)?.bind(self),
314
+ error: (isObserver ? nextHandler.error : errorHandler)?.bind(self),
315
+ complete: (isObserver ? nextHandler.complete : completionHandler)?.bind(self)
316
+ };
317
+ }
318
+ function createInvokeId(stateNodeId, index) {
319
+ return `${stateNodeId}:invocation[${index}]`;
320
+ }
321
+ function resolveReferencedActor(referenced) {
322
+ return referenced ? 'transition' in referenced ? {
323
+ src: referenced,
324
+ input: undefined
325
+ } : referenced : undefined;
326
+ }
327
+
328
+ let ActorStatus = /*#__PURE__*/function (ActorStatus) {
329
+ ActorStatus[ActorStatus["NotStarted"] = 0] = "NotStarted";
330
+ ActorStatus[ActorStatus["Running"] = 1] = "Running";
331
+ ActorStatus[ActorStatus["Stopped"] = 2] = "Stopped";
332
+ return ActorStatus;
333
+ }({});
334
+
335
+ /**
336
+ * @deprecated Use `ActorStatus` instead.
337
+ */
338
+ const InterpreterStatus = ActorStatus;
339
+ const defaultOptions = {
340
+ clock: {
341
+ setTimeout: (fn, ms) => {
342
+ return setTimeout(fn, ms);
343
+ },
344
+ clearTimeout: id => {
345
+ return clearTimeout(id);
346
+ }
347
+ },
348
+ logger: console.log.bind(console),
349
+ devTools: false
350
+ };
351
+ class Actor {
352
+ /**
353
+ * The current internal state of the actor.
354
+ */
355
+
356
+ /**
357
+ * The clock that is responsible for setting and clearing timeouts, such as delayed events and transitions.
358
+ */
359
+
360
+ /**
361
+ * The unique identifier for this actor relative to its parent.
362
+ */
363
+
364
+ /**
365
+ * Whether the service is started.
366
+ */
367
+
368
+ // Actor Ref
369
+
370
+ // TODO: add typings for system
371
+
372
+ /**
373
+ * The globally unique process ID for this invocation.
374
+ */
375
+
376
+ /**
377
+ * Creates a new actor instance for the given logic with the provided options, if any.
378
+ *
379
+ * @param logic The logic to create an actor from
380
+ * @param options Actor options
381
+ */
382
+ constructor(logic, options) {
383
+ this.logic = logic;
384
+ this._state = void 0;
385
+ this.clock = void 0;
386
+ this.options = void 0;
387
+ this.id = void 0;
388
+ this.mailbox = new Mailbox(this._process.bind(this));
389
+ this.delayedEventsMap = {};
390
+ this.observers = new Set();
391
+ this.logger = void 0;
392
+ this.status = ActorStatus.NotStarted;
393
+ this._parent = void 0;
394
+ this.ref = void 0;
395
+ this._actorContext = void 0;
396
+ this._systemId = void 0;
397
+ this.sessionId = void 0;
398
+ this.system = void 0;
399
+ this._doneEvent = void 0;
400
+ this.src = void 0;
401
+ this._deferred = [];
402
+ const resolvedOptions = {
403
+ ...defaultOptions,
404
+ ...options
405
+ };
406
+ const {
407
+ clock,
408
+ logger,
409
+ parent,
410
+ id,
411
+ systemId
412
+ } = resolvedOptions;
413
+ const self = this;
414
+ this.system = parent?.system ?? createSystem();
415
+ if (systemId) {
416
+ this._systemId = systemId;
417
+ this.system._set(systemId, this);
418
+ }
419
+ this.sessionId = this.system._bookId();
420
+ this.id = id ?? this.sessionId;
421
+ this.logger = logger;
422
+ this.clock = clock;
423
+ this._parent = parent;
424
+ this.options = resolvedOptions;
425
+ this.src = resolvedOptions.src;
426
+ this.ref = this;
427
+ this._actorContext = {
428
+ self,
429
+ id: this.id,
430
+ sessionId: this.sessionId,
431
+ logger: this.logger,
432
+ defer: fn => {
433
+ this._deferred.push(fn);
434
+ },
435
+ system: this.system,
436
+ stopChild: child => {
437
+ if (child._parent !== this) {
438
+ throw new Error(`Cannot stop child actor ${child.id} of ${this.id} because it is not a child`);
439
+ }
440
+ child._stop();
441
+ }
442
+ };
443
+
444
+ // Ensure that the send method is bound to this Actor instance
445
+ // if destructured
446
+ this.send = this.send.bind(this);
447
+ this._initState();
448
+ }
449
+ _initState() {
450
+ 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);
451
+ }
452
+
453
+ // array of functions to defer
454
+
455
+ update(state) {
456
+ // Update state
457
+ this._state = state;
458
+ const snapshot = this.getSnapshot();
459
+
460
+ // Execute deferred effects
461
+ let deferredFn;
462
+ while (deferredFn = this._deferred.shift()) {
463
+ deferredFn();
464
+ }
465
+ for (const observer of this.observers) {
466
+ // TODO: should observers be notified in case of the error?
467
+ try {
468
+ observer.next?.(snapshot);
469
+ } catch (err) {
470
+ reportUnhandledError(err);
471
+ }
472
+ }
473
+ const status = this.logic.getStatus?.(state);
474
+ switch (status?.status) {
475
+ case 'done':
476
+ this._stopProcedure();
477
+ this._complete();
478
+ this._doneEvent = createDoneActorEvent(this.id, status.data);
479
+ this._parent?.send(this._doneEvent);
480
+ break;
481
+ case 'error':
482
+ this._stopProcedure();
483
+ this._error(status.data);
484
+ this._parent?.send(createErrorActorEvent(this.id, status.data));
485
+ break;
486
+ }
487
+ }
488
+ subscribe(nextListenerOrObserver, errorListener, completeListener) {
489
+ const observer = toObserver(nextListenerOrObserver, errorListener, completeListener);
490
+ if (this.status !== ActorStatus.Stopped) {
491
+ this.observers.add(observer);
492
+ } else {
493
+ try {
494
+ observer.complete?.();
495
+ } catch (err) {
496
+ reportUnhandledError(err);
497
+ }
498
+ }
499
+ return {
500
+ unsubscribe: () => {
501
+ this.observers.delete(observer);
502
+ }
503
+ };
504
+ }
505
+
506
+ /**
507
+ * Starts the Actor from the initial state
508
+ */
509
+ start() {
510
+ if (this.status === ActorStatus.Running) {
511
+ // Do not restart the service if it is already started
512
+ return this;
513
+ }
514
+ this.system._register(this.sessionId, this);
515
+ if (this._systemId) {
516
+ this.system._set(this._systemId, this);
517
+ }
518
+ this.status = ActorStatus.Running;
519
+ const status = this.logic.getStatus?.(this._state);
520
+ switch (status?.status) {
521
+ case 'done':
522
+ // a state machine can be "done" upon intialization (it could reach a final state using initial microsteps)
523
+ // we still need to complete observers, flush deferreds etc
524
+ this.update(this._state);
525
+ // fallthrough
526
+ case 'error':
527
+ // TODO: rethink cleanup of observers, mailbox, etc
528
+ return this;
529
+ }
530
+ if (this.logic.start) {
531
+ try {
532
+ this.logic.start(this._state, this._actorContext);
533
+ } catch (err) {
534
+ this._stopProcedure();
535
+ this._error(err);
536
+ this._parent?.send(createErrorActorEvent(this.id, err));
537
+ return this;
538
+ }
539
+ }
540
+
541
+ // TODO: this notifies all subscribers but usually this is redundant
542
+ // there is no real change happening here
543
+ // we need to rethink if this needs to be refactored
544
+ this.update(this._state);
545
+ if (this.options.devTools) {
546
+ this.attachDevTools();
547
+ }
548
+ this.mailbox.start();
549
+ return this;
550
+ }
551
+ _process(event) {
552
+ // TODO: reexamine what happens when an action (or a guard or smth) throws
553
+ let nextState;
554
+ let caughtError;
555
+ try {
556
+ nextState = this.logic.transition(this._state, event, this._actorContext);
557
+ } catch (err) {
558
+ // we wrap it in a box so we can rethrow it later even if falsy value gets caught here
559
+ caughtError = {
560
+ err
561
+ };
562
+ }
563
+ if (caughtError) {
564
+ const {
565
+ err
566
+ } = caughtError;
567
+ this._stopProcedure();
568
+ this._error(err);
569
+ this._parent?.send(createErrorActorEvent(this.id, err));
570
+ return;
571
+ }
572
+ this.update(nextState);
573
+ if (event.type === XSTATE_STOP) {
574
+ this._stopProcedure();
575
+ this._complete();
576
+ }
577
+ }
578
+ _stop() {
579
+ if (this.status === ActorStatus.Stopped) {
580
+ return this;
581
+ }
582
+ this.mailbox.clear();
583
+ if (this.status === ActorStatus.NotStarted) {
584
+ this.status = ActorStatus.Stopped;
585
+ return this;
586
+ }
587
+ this.mailbox.enqueue({
588
+ type: XSTATE_STOP
589
+ });
590
+ return this;
591
+ }
592
+
593
+ /**
594
+ * Stops the Actor and unsubscribe all listeners.
595
+ */
596
+ stop() {
597
+ if (this._parent) {
598
+ throw new Error('A non-root actor cannot be stopped directly.');
599
+ }
600
+ return this._stop();
601
+ }
602
+ _complete() {
603
+ for (const observer of this.observers) {
604
+ try {
605
+ observer.complete?.();
606
+ } catch (err) {
607
+ reportUnhandledError(err);
608
+ }
609
+ }
610
+ this.observers.clear();
611
+ }
612
+ _error(err) {
613
+ if (!this.observers.size) {
614
+ if (!this._parent) {
615
+ reportUnhandledError(err);
616
+ }
617
+ return;
618
+ }
619
+ let reportError = false;
620
+ for (const observer of this.observers) {
621
+ const errorListener = observer.error;
622
+ reportError ||= !errorListener;
623
+ try {
624
+ errorListener?.(err);
625
+ } catch (err2) {
626
+ reportUnhandledError(err2);
627
+ }
628
+ }
629
+ this.observers.clear();
630
+ if (reportError) {
631
+ reportUnhandledError(err);
632
+ }
633
+ }
634
+ _stopProcedure() {
635
+ if (this.status !== ActorStatus.Running) {
636
+ // Actor already stopped; do nothing
637
+ return this;
638
+ }
639
+
640
+ // Cancel all delayed events
641
+ for (const key of Object.keys(this.delayedEventsMap)) {
642
+ this.clock.clearTimeout(this.delayedEventsMap[key]);
643
+ }
644
+
645
+ // TODO: mailbox.reset
646
+ this.mailbox.clear();
647
+ // TODO: after `stop` we must prepare ourselves for receiving events again
648
+ // events sent *after* stop signal must be queued
649
+ // it seems like this should be the common behavior for all of our consumers
650
+ // so perhaps this should be unified somehow for all of them
651
+ this.mailbox = new Mailbox(this._process.bind(this));
652
+ this.status = ActorStatus.Stopped;
653
+ this.system._unregister(this);
654
+ return this;
655
+ }
656
+
657
+ /**
658
+ * Sends an event to the running Actor to trigger a transition.
659
+ *
660
+ * @param event The event to send
661
+ */
662
+ send(event) {
663
+ if (typeof event === 'string') {
664
+ throw new Error(`Only event objects may be sent to actors; use .send({ type: "${event}" }) instead`);
665
+ }
666
+ if (this.status === ActorStatus.Stopped) {
667
+ // do nothing
668
+ {
669
+ const eventString = JSON.stringify(event);
670
+ console.warn(`Event "${event.type}" was sent to stopped actor "${this.id} (${this.sessionId})". This actor has already reached its final state, and will not transition.\nEvent: ${eventString}`);
671
+ }
672
+ return;
673
+ }
674
+ this.mailbox.enqueue(event);
675
+ }
676
+
677
+ // TODO: make private (and figure out a way to do this within the machine)
678
+ delaySend({
679
+ event,
680
+ id,
681
+ delay,
682
+ to
683
+ }) {
684
+ const timerId = this.clock.setTimeout(() => {
685
+ if (to) {
686
+ to.send(event);
687
+ } else {
688
+ this.send(event);
689
+ }
690
+ }, delay);
691
+
692
+ // TODO: consider the rehydration story here
693
+ if (id) {
694
+ this.delayedEventsMap[id] = timerId;
695
+ }
696
+ }
697
+
698
+ // TODO: make private (and figure out a way to do this within the machine)
699
+ cancel(sendId) {
700
+ this.clock.clearTimeout(this.delayedEventsMap[sendId]);
701
+ delete this.delayedEventsMap[sendId];
702
+ }
703
+ attachDevTools() {
704
+ const {
705
+ devTools
706
+ } = this.options;
707
+ if (devTools) {
708
+ const resolvedDevToolsAdapter = typeof devTools === 'function' ? devTools : dev_dist_xstateDev.devToolsAdapter;
709
+ resolvedDevToolsAdapter(this);
710
+ }
711
+ }
712
+ toJSON() {
713
+ return {
714
+ id: this.id
715
+ };
716
+ }
717
+ getPersistedState() {
718
+ return this.logic.getPersistedState?.(this._state);
719
+ }
720
+ [symbolObservable]() {
721
+ return this;
722
+ }
723
+ getSnapshot() {
724
+ return this.logic.getSnapshot ? this.logic.getSnapshot(this._state) : this._state;
725
+ }
726
+ }
727
+
728
+ /**
729
+ * Creates a new `ActorRef` instance for the given machine with the provided options, if any.
730
+ *
731
+ * @param machine The machine to create an actor from
732
+ * @param options `ActorRef` options
733
+ */
734
+
735
+ function createActor(logic, options) {
736
+ const interpreter = new Actor(logic, options);
737
+ return interpreter;
738
+ }
739
+
740
+ /**
741
+ * Creates a new Interpreter instance for the given machine with the provided options, if any.
742
+ *
743
+ * @deprecated Use `createActor` instead
744
+ */
745
+ const interpret = createActor;
746
+
747
+ /**
748
+ * @deprecated Use `Actor` instead.
749
+ */
750
+
751
+ exports.Actor = Actor;
752
+ exports.ActorStatus = ActorStatus;
753
+ exports.InterpreterStatus = InterpreterStatus;
754
+ exports.NULL_EVENT = NULL_EVENT;
755
+ exports.STATE_DELIMITER = STATE_DELIMITER;
756
+ exports.STATE_IDENTIFIER = STATE_IDENTIFIER;
757
+ exports.WILDCARD = WILDCARD;
758
+ exports.XSTATE_ERROR = XSTATE_ERROR;
759
+ exports.XSTATE_INIT = XSTATE_INIT;
760
+ exports.XSTATE_STOP = XSTATE_STOP;
761
+ exports.createActor = createActor;
762
+ exports.createAfterEvent = createAfterEvent;
763
+ exports.createDoneStateEvent = createDoneStateEvent;
764
+ exports.createErrorActorEvent = createErrorActorEvent;
765
+ exports.createInitEvent = createInitEvent;
766
+ exports.createInvokeId = createInvokeId;
767
+ exports.flatten = flatten;
768
+ exports.interpret = interpret;
769
+ exports.isArray = isArray;
770
+ exports.isErrorActorEvent = isErrorActorEvent;
771
+ exports.mapContext = mapContext;
772
+ exports.mapValues = mapValues;
773
+ exports.matchesState = matchesState;
774
+ exports.normalizeTarget = normalizeTarget;
775
+ exports.pathToStateValue = pathToStateValue;
776
+ exports.resolveReferencedActor = resolveReferencedActor;
777
+ exports.toArray = toArray;
778
+ exports.toObserver = toObserver;
779
+ exports.toStatePath = toStatePath;
780
+ exports.toStateValue = toStateValue;
781
+ exports.toTransitionConfigArray = toTransitionConfigArray;