xstate 5.0.0-beta.42 → 5.0.0-beta.44

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