xstate 5.0.0-beta.43 → 5.0.0-beta.45

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 (55) 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 +98 -10
  8. package/actors/dist/xstate-actors.development.cjs.js +98 -10
  9. package/actors/dist/xstate-actors.development.esm.js +93 -5
  10. package/actors/dist/xstate-actors.esm.js +93 -5
  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 +14 -18
  14. package/dist/declarations/src/StateMachine.d.ts +1 -1
  15. package/dist/declarations/src/actions/choose.d.ts +3 -3
  16. package/dist/declarations/src/actions/pure.d.ts +4 -4
  17. package/dist/declarations/src/actions/spawn.d.ts +11 -16
  18. package/dist/declarations/src/actors/observable.d.ts +39 -0
  19. package/dist/declarations/src/actors/transition.d.ts +53 -4
  20. package/dist/declarations/src/{Machine.d.ts → createMachine.d.ts} +1 -1
  21. package/dist/declarations/src/guards.d.ts +27 -5
  22. package/dist/declarations/src/index.d.ts +3 -2
  23. package/dist/declarations/src/interpreter.d.ts +1 -0
  24. package/dist/declarations/src/setup.d.ts +32 -0
  25. package/dist/declarations/src/spawn.d.ts +9 -13
  26. package/dist/declarations/src/stateUtils.d.ts +11 -11
  27. package/dist/declarations/src/types.d.ts +31 -29
  28. package/dist/declarations/src/utils.d.ts +1 -3
  29. package/dist/{raise-8dc8e1aa.esm.js → raise-2b5a4e4c.esm.js} +934 -103
  30. package/dist/{raise-f4ad5a87.development.esm.js → raise-90139fbc.development.esm.js} +945 -103
  31. package/dist/{raise-23dea0d7.development.cjs.js → raise-b3fb3c65.development.cjs.js} +999 -137
  32. package/dist/{raise-e0fe5c2d.cjs.js → raise-fabffc3d.cjs.js} +986 -135
  33. package/dist/{send-5d129d95.development.esm.js → send-24cc8018.development.esm.js} +4 -30
  34. package/dist/{send-84e2e742.esm.js → send-8e7e41e7.esm.js} +4 -30
  35. package/dist/{send-87bbaaab.cjs.js → send-c124176f.cjs.js} +13 -39
  36. package/dist/{send-0174c155.development.cjs.js → send-d0bc7eed.development.cjs.js} +13 -39
  37. package/dist/xstate.cjs.js +67 -35
  38. package/dist/xstate.cjs.mjs +2 -0
  39. package/dist/xstate.development.cjs.js +67 -35
  40. package/dist/xstate.development.cjs.mjs +2 -0
  41. package/dist/xstate.development.esm.js +42 -13
  42. package/dist/xstate.esm.js +42 -13
  43. package/dist/xstate.umd.min.js +1 -1
  44. package/dist/xstate.umd.min.js.map +1 -1
  45. package/guards/dist/xstate-guards.cjs.js +1 -2
  46. package/guards/dist/xstate-guards.development.cjs.js +1 -2
  47. package/guards/dist/xstate-guards.development.esm.js +1 -2
  48. package/guards/dist/xstate-guards.esm.js +1 -2
  49. package/guards/dist/xstate-guards.umd.min.js +1 -1
  50. package/guards/dist/xstate-guards.umd.min.js.map +1 -1
  51. package/package.json +1 -1
  52. package/dist/interpreter-36d5556e.cjs.js +0 -887
  53. package/dist/interpreter-4e8e2a0d.development.cjs.js +0 -898
  54. package/dist/interpreter-63c80754.esm.js +0 -857
  55. package/dist/interpreter-80eb3bec.development.esm.js +0 -868
@@ -1,887 +0,0 @@
1
- 'use strict';
2
-
3
- var dev_dist_xstateDev = require('../dev/dist/xstate-dev.cjs.js');
4
-
5
- class Mailbox {
6
- constructor(_process) {
7
- this._process = _process;
8
- this._active = false;
9
- this._current = null;
10
- this._last = null;
11
- }
12
- start() {
13
- this._active = true;
14
- this.flush();
15
- }
16
- clear() {
17
- // we can't set _current to null because we might be currently processing
18
- // and enqueue following clear shouldnt start processing the enqueued item immediately
19
- if (this._current) {
20
- this._current.next = null;
21
- this._last = this._current;
22
- }
23
- }
24
- enqueue(event) {
25
- const enqueued = {
26
- value: event,
27
- next: null
28
- };
29
- if (this._current) {
30
- this._last.next = enqueued;
31
- this._last = enqueued;
32
- return;
33
- }
34
- this._current = enqueued;
35
- this._last = enqueued;
36
- if (this._active) {
37
- this.flush();
38
- }
39
- }
40
- flush() {
41
- while (this._current) {
42
- // atm the given _process is responsible for implementing proper try/catch handling
43
- // we assume here that this won't throw in a way that can affect this mailbox
44
- const consumed = this._current;
45
- this._process(consumed.value);
46
- this._current = consumed.next;
47
- }
48
- this._last = null;
49
- }
50
- }
51
-
52
- const STATE_DELIMITER = '.';
53
- const TARGETLESS_KEY = '';
54
- const NULL_EVENT = '';
55
- const STATE_IDENTIFIER = '#';
56
- const WILDCARD = '*';
57
- const XSTATE_INIT = 'xstate.init';
58
- const XSTATE_ERROR = 'xstate.error';
59
- const XSTATE_STOP = 'xstate.stop';
60
-
61
- /**
62
- * Returns an event that represents an implicit event that
63
- * is sent after the specified `delay`.
64
- *
65
- * @param delayRef The delay in milliseconds
66
- * @param id The state node ID where this event is handled
67
- */
68
- function createAfterEvent(delayRef, id) {
69
- const idSuffix = id ? `#${id}` : '';
70
- return {
71
- type: `xstate.after(${delayRef})${idSuffix}`
72
- };
73
- }
74
-
75
- /**
76
- * Returns an event that represents that a final state node
77
- * has been reached in the parent state node.
78
- *
79
- * @param id The final state node's parent state node `id`
80
- * @param output The data to pass into the event
81
- */
82
- function createDoneStateEvent(id, output) {
83
- return {
84
- type: `xstate.done.state.${id}`,
85
- output
86
- };
87
- }
88
-
89
- /**
90
- * Returns an event that represents that an invoked service has terminated.
91
- *
92
- * An invoked service is terminated when it has reached a top-level final state node,
93
- * but not when it is canceled.
94
- *
95
- * @param invokeId The invoked service ID
96
- * @param output The data to pass into the event
97
- */
98
- function createDoneActorEvent(invokeId, output) {
99
- return {
100
- type: `xstate.done.actor.${invokeId}`,
101
- output
102
- };
103
- }
104
- function createErrorActorEvent(id, data) {
105
- return {
106
- type: `xstate.error.actor.${id}`,
107
- data
108
- };
109
- }
110
- function createInitEvent(input) {
111
- return {
112
- type: XSTATE_INIT,
113
- input
114
- };
115
- }
116
-
117
- /**
118
- * This function makes sure that unhandled errors are thrown in a separate macrotask.
119
- * It allows those errors to be detected by global error handlers and reported to bug tracking services
120
- * without interrupting our own stack of execution.
121
- *
122
- * @param err error to be thrown
123
- */
124
- function reportUnhandledError(err) {
125
- setTimeout(() => {
126
- throw err;
127
- });
128
- }
129
-
130
- const symbolObservable = (() => typeof Symbol === 'function' && Symbol.observable || '@@observable')();
131
-
132
- let idCounter = 0;
133
- function createSystem(rootActor) {
134
- const children = new Map();
135
- const keyedActors = new Map();
136
- const reverseKeyedActors = new WeakMap();
137
- const observers = new Set();
138
- const system = {
139
- _bookId: () => `x:${idCounter++}`,
140
- _register: (sessionId, actorRef) => {
141
- children.set(sessionId, actorRef);
142
- return sessionId;
143
- },
144
- _unregister: actorRef => {
145
- children.delete(actorRef.sessionId);
146
- const systemId = reverseKeyedActors.get(actorRef);
147
- if (systemId !== undefined) {
148
- keyedActors.delete(systemId);
149
- reverseKeyedActors.delete(actorRef);
150
- }
151
- },
152
- get: systemId => {
153
- return keyedActors.get(systemId);
154
- },
155
- _set: (systemId, actorRef) => {
156
- const existing = keyedActors.get(systemId);
157
- if (existing && existing !== actorRef) {
158
- throw new Error(`Actor with system ID '${systemId}' already exists.`);
159
- }
160
- keyedActors.set(systemId, actorRef);
161
- reverseKeyedActors.set(actorRef, systemId);
162
- },
163
- inspect: observer => {
164
- observers.add(observer);
165
- },
166
- _sendInspectionEvent: event => {
167
- const resolvedInspectionEvent = {
168
- ...event,
169
- rootId: rootActor.sessionId
170
- };
171
- observers.forEach(observer => observer.next?.(resolvedInspectionEvent));
172
- },
173
- _relay: (source, target, event) => {
174
- system._sendInspectionEvent({
175
- type: '@xstate.event',
176
- sourceRef: source,
177
- actorRef: target,
178
- event
179
- });
180
- target._send(event);
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 resolveOutput(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}[${index}]`;
317
- }
318
- function resolveReferencedActor(machine, src) {
319
- if (src.startsWith('xstate#')) {
320
- const [, indexStr] = src.match(/\[(\d+)\]$/);
321
- const node = machine.getStateNodeById(src.slice(7, -(indexStr.length + 2)));
322
- const invokeConfig = node.config.invoke;
323
- return (Array.isArray(invokeConfig) ? invokeConfig[indexStr] : invokeConfig).src;
324
- }
325
- return machine.implementations.actors[src];
326
- }
327
-
328
- const $$ACTOR_TYPE = 1;
329
- // those values are currently used by @xstate/react directly so it's important to keep the assigned values in sync
330
- let ProcessingStatus = /*#__PURE__*/function (ProcessingStatus) {
331
- ProcessingStatus[ProcessingStatus["NotStarted"] = 0] = "NotStarted";
332
- ProcessingStatus[ProcessingStatus["Running"] = 1] = "Running";
333
- ProcessingStatus[ProcessingStatus["Stopped"] = 2] = "Stopped";
334
- return ProcessingStatus;
335
- }({});
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
-
349
- /**
350
- * 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.
351
- */
352
- class Actor {
353
- /**
354
- * The current internal state of the actor.
355
- */
356
-
357
- /**
358
- * The clock that is responsible for setting and clearing timeouts, such as delayed events and transitions.
359
- */
360
-
361
- /**
362
- * The unique identifier for this actor relative to its parent.
363
- */
364
-
365
- /** @internal */
366
-
367
- // Actor Ref
368
-
369
- // TODO: add typings for system
370
-
371
- /**
372
- * The globally unique process ID for this invocation.
373
- */
374
-
375
- /**
376
- * The system to which this actor belongs.
377
- */
378
-
379
- /**
380
- * Creates a new actor instance for the given logic with the provided options, if any.
381
- *
382
- * @param logic The logic to create an actor from
383
- * @param options Actor options
384
- */
385
- constructor(logic, options) {
386
- this.logic = logic;
387
- this._state = void 0;
388
- this.clock = void 0;
389
- this.options = void 0;
390
- this.id = void 0;
391
- this.mailbox = new Mailbox(this._process.bind(this));
392
- this.delayedEventsMap = {};
393
- this.observers = new Set();
394
- this.logger = void 0;
395
- this._processingStatus = ProcessingStatus.NotStarted;
396
- this._parent = void 0;
397
- this.ref = void 0;
398
- this._actorScope = void 0;
399
- this._systemId = void 0;
400
- this.sessionId = void 0;
401
- this.system = void 0;
402
- this._doneEvent = void 0;
403
- this.src = void 0;
404
- this._deferred = [];
405
- const resolvedOptions = {
406
- ...defaultOptions,
407
- ...options
408
- };
409
- const {
410
- clock,
411
- logger,
412
- parent,
413
- id,
414
- systemId,
415
- inspect
416
- } = resolvedOptions;
417
- this.system = parent?.system ?? createSystem(this);
418
- if (inspect && !parent) {
419
- // Always inspect at the system-level
420
- this.system.inspect(toObserver(inspect));
421
- }
422
- this.sessionId = this.system._bookId();
423
- this.id = id ?? this.sessionId;
424
- this.logger = logger;
425
- this.clock = clock;
426
- this._parent = parent;
427
- this.options = resolvedOptions;
428
- this.src = resolvedOptions.src ?? logic;
429
- this.ref = this;
430
- this._actorScope = {
431
- self: this,
432
- id: this.id,
433
- sessionId: this.sessionId,
434
- logger: this.logger,
435
- defer: fn => {
436
- this._deferred.push(fn);
437
- },
438
- system: this.system,
439
- stopChild: child => {
440
- if (child._parent !== this) {
441
- throw new Error(`Cannot stop child actor ${child.id} of ${this.id} because it is not a child`);
442
- }
443
- child._stop();
444
- }
445
- };
446
-
447
- // Ensure that the send method is bound to this Actor instance
448
- // if destructured
449
- this.send = this.send.bind(this);
450
- this.system._sendInspectionEvent({
451
- type: '@xstate.actor',
452
- actorRef: this
453
- });
454
- this._initState(options?.state);
455
- if (systemId && this._state.status === 'active') {
456
- this._systemId = systemId;
457
- this.system._set(systemId, this);
458
- }
459
- }
460
- _initState(persistedState) {
461
- this._state = persistedState ? this.logic.restoreState ? this.logic.restoreState(persistedState, this._actorScope) : persistedState : this.logic.getInitialState(this._actorScope, this.options?.input);
462
- }
463
-
464
- // array of functions to defer
465
-
466
- update(snapshot, event) {
467
- // Update state
468
- this._state = snapshot;
469
-
470
- // Execute deferred effects
471
- let deferredFn;
472
- while (deferredFn = this._deferred.shift()) {
473
- deferredFn();
474
- }
475
- for (const observer of this.observers) {
476
- try {
477
- observer.next?.(snapshot);
478
- } catch (err) {
479
- reportUnhandledError(err);
480
- }
481
- }
482
- switch (this._state.status) {
483
- case 'done':
484
- this._stopProcedure();
485
- this._complete();
486
- this._doneEvent = createDoneActorEvent(this.id, this._state.output);
487
- if (this._parent) {
488
- this.system._relay(this, this._parent, this._doneEvent);
489
- }
490
- break;
491
- case 'error':
492
- this._stopProcedure();
493
- this._error(this._state.error);
494
- if (this._parent) {
495
- this.system._relay(this, this._parent, createErrorActorEvent(this.id, this._state.error));
496
- }
497
- break;
498
- }
499
- this.system._sendInspectionEvent({
500
- type: '@xstate.snapshot',
501
- actorRef: this,
502
- event,
503
- snapshot
504
- });
505
- }
506
-
507
- /**
508
- * Subscribe an observer to an actor’s snapshot values.
509
- *
510
- * @remarks
511
- * The observer will receive the actor’s snapshot value when it is emitted. The observer can be:
512
- * - A plain function that receives the latest snapshot, or
513
- * - An observer object whose `.next(snapshot)` method receives the latest snapshot
514
- *
515
- * @example
516
- * ```ts
517
- * // Observer as a plain function
518
- * const subscription = actor.subscribe((snapshot) => {
519
- * console.log(snapshot);
520
- * });
521
- * ```
522
- *
523
- * @example
524
- * ```ts
525
- * // Observer as an object
526
- * const subscription = actor.subscribe({
527
- * next(snapshot) {
528
- * console.log(snapshot);
529
- * },
530
- * error(err) {
531
- * // ...
532
- * },
533
- * complete() {
534
- * // ...
535
- * },
536
- * });
537
- * ```
538
- *
539
- * 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:
540
- *
541
- * @example
542
- * ```ts
543
- * const subscription = actor.subscribe((snapshot) => {
544
- * // ...
545
- * });
546
- *
547
- * // Unsubscribe the observer
548
- * subscription.unsubscribe();
549
- * ```
550
- *
551
- * When the actor is stopped, all of its observers will automatically be unsubscribed.
552
- *
553
- * @param observer - Either a plain function that receives the latest snapshot, or an observer object whose `.next(snapshot)` method receives the latest snapshot
554
- */
555
-
556
- subscribe(nextListenerOrObserver, errorListener, completeListener) {
557
- const observer = toObserver(nextListenerOrObserver, errorListener, completeListener);
558
- if (this._processingStatus !== ProcessingStatus.Stopped) {
559
- this.observers.add(observer);
560
- } else {
561
- try {
562
- observer.complete?.();
563
- } catch (err) {
564
- reportUnhandledError(err);
565
- }
566
- }
567
- return {
568
- unsubscribe: () => {
569
- this.observers.delete(observer);
570
- }
571
- };
572
- }
573
-
574
- /**
575
- * Starts the Actor from the initial state
576
- */
577
- start() {
578
- if (this._processingStatus === ProcessingStatus.Running) {
579
- // Do not restart the service if it is already started
580
- return this;
581
- }
582
- this.system._register(this.sessionId, this);
583
- if (this._systemId) {
584
- this.system._set(this._systemId, this);
585
- }
586
- this._processingStatus = ProcessingStatus.Running;
587
-
588
- // TODO: this isn't correct when rehydrating
589
- const initEvent = createInitEvent(this.options.input);
590
- this.system._sendInspectionEvent({
591
- type: '@xstate.event',
592
- sourceRef: this._parent,
593
- actorRef: this,
594
- event: initEvent
595
- });
596
- const status = this._state.status;
597
- switch (status) {
598
- case 'done':
599
- // a state machine can be "done" upon initialization (it could reach a final state using initial microsteps)
600
- // we still need to complete observers, flush deferreds etc
601
- this.update(this._state, initEvent);
602
- // fallthrough
603
- case 'error':
604
- // TODO: rethink cleanup of observers, mailbox, etc
605
- return this;
606
- }
607
- if (this.logic.start) {
608
- try {
609
- this.logic.start(this._state, this._actorScope);
610
- } catch (err) {
611
- this._stopProcedure();
612
- this._error(err);
613
- this._parent?.send(createErrorActorEvent(this.id, err));
614
- return this;
615
- }
616
- }
617
-
618
- // TODO: this notifies all subscribers but usually this is redundant
619
- // there is no real change happening here
620
- // we need to rethink if this needs to be refactored
621
- this.update(this._state, initEvent);
622
- if (this.options.devTools) {
623
- this.attachDevTools();
624
- }
625
- this.mailbox.start();
626
- return this;
627
- }
628
- _process(event) {
629
- // TODO: reexamine what happens when an action (or a guard or smth) throws
630
- let nextState;
631
- let caughtError;
632
- try {
633
- nextState = this.logic.transition(this._state, event, this._actorScope);
634
- } catch (err) {
635
- // we wrap it in a box so we can rethrow it later even if falsy value gets caught here
636
- caughtError = {
637
- err
638
- };
639
- }
640
- if (caughtError) {
641
- const {
642
- err
643
- } = caughtError;
644
- this._stopProcedure();
645
- this._error(err);
646
- this._parent?.send(createErrorActorEvent(this.id, err));
647
- return;
648
- }
649
- this.update(nextState, event);
650
- if (event.type === XSTATE_STOP) {
651
- this._stopProcedure();
652
- this._complete();
653
- }
654
- }
655
- _stop() {
656
- if (this._processingStatus === ProcessingStatus.Stopped) {
657
- return this;
658
- }
659
- this.mailbox.clear();
660
- if (this._processingStatus === ProcessingStatus.NotStarted) {
661
- this._processingStatus = ProcessingStatus.Stopped;
662
- return this;
663
- }
664
- this.mailbox.enqueue({
665
- type: XSTATE_STOP
666
- });
667
- return this;
668
- }
669
-
670
- /**
671
- * Stops the Actor and unsubscribe all listeners.
672
- */
673
- stop() {
674
- if (this._parent) {
675
- throw new Error('A non-root actor cannot be stopped directly.');
676
- }
677
- return this._stop();
678
- }
679
- _complete() {
680
- for (const observer of this.observers) {
681
- try {
682
- observer.complete?.();
683
- } catch (err) {
684
- reportUnhandledError(err);
685
- }
686
- }
687
- this.observers.clear();
688
- }
689
- _error(err) {
690
- if (!this.observers.size) {
691
- if (!this._parent) {
692
- reportUnhandledError(err);
693
- }
694
- return;
695
- }
696
- let reportError = false;
697
- for (const observer of this.observers) {
698
- const errorListener = observer.error;
699
- reportError ||= !errorListener;
700
- try {
701
- errorListener?.(err);
702
- } catch (err2) {
703
- reportUnhandledError(err2);
704
- }
705
- }
706
- this.observers.clear();
707
- if (reportError) {
708
- reportUnhandledError(err);
709
- }
710
- }
711
- _stopProcedure() {
712
- if (this._processingStatus !== ProcessingStatus.Running) {
713
- // Actor already stopped; do nothing
714
- return this;
715
- }
716
-
717
- // Cancel all delayed events
718
- for (const key of Object.keys(this.delayedEventsMap)) {
719
- this.clock.clearTimeout(this.delayedEventsMap[key]);
720
- }
721
-
722
- // TODO: mailbox.reset
723
- this.mailbox.clear();
724
- // TODO: after `stop` we must prepare ourselves for receiving events again
725
- // events sent *after* stop signal must be queued
726
- // it seems like this should be the common behavior for all of our consumers
727
- // so perhaps this should be unified somehow for all of them
728
- this.mailbox = new Mailbox(this._process.bind(this));
729
- this._processingStatus = ProcessingStatus.Stopped;
730
- this.system._unregister(this);
731
- return this;
732
- }
733
-
734
- /**
735
- * @internal
736
- */
737
- _send(event) {
738
- if (this._processingStatus === ProcessingStatus.Stopped) {
739
- return;
740
- }
741
- this.mailbox.enqueue(event);
742
- }
743
-
744
- /**
745
- * Sends an event to the running Actor to trigger a transition.
746
- *
747
- * @param event The event to send
748
- */
749
- send(event) {
750
- this.system._relay(undefined, this, event);
751
- }
752
-
753
- /**
754
- * TODO: figure out a way to do this within the machine
755
- * @internal
756
- */
757
- delaySend(params) {
758
- const {
759
- event,
760
- id,
761
- delay
762
- } = params;
763
- const timerId = this.clock.setTimeout(() => {
764
- this.system._relay(this, params.to ?? this, event);
765
- }, delay);
766
-
767
- // TODO: consider the rehydration story here
768
- if (id) {
769
- this.delayedEventsMap[id] = timerId;
770
- }
771
- }
772
-
773
- /**
774
- * TODO: figure out a way to do this within the machine
775
- * @internal
776
- */
777
- cancel(sendId) {
778
- this.clock.clearTimeout(this.delayedEventsMap[sendId]);
779
- delete this.delayedEventsMap[sendId];
780
- }
781
- attachDevTools() {
782
- const {
783
- devTools
784
- } = this.options;
785
- if (devTools) {
786
- const resolvedDevToolsAdapter = typeof devTools === 'function' ? devTools : dev_dist_xstateDev.devToolsAdapter;
787
- resolvedDevToolsAdapter(this);
788
- }
789
- }
790
- toJSON() {
791
- return {
792
- xstate$$type: $$ACTOR_TYPE,
793
- id: this.id
794
- };
795
- }
796
-
797
- /**
798
- * Obtain the internal state of the actor, which can be persisted.
799
- *
800
- * @remarks
801
- * The internal state can be persisted from any actor, not only machines.
802
- *
803
- * 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.
804
- *
805
- * Can be restored with {@link ActorOptions.state}
806
- *
807
- * @see https://stately.ai/docs/persistence
808
- */
809
-
810
- getPersistedState(options) {
811
- return this.logic.getPersistedState(this._state, options);
812
- }
813
- [symbolObservable]() {
814
- return this;
815
- }
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.
824
- * An actor may emit a snapshot when a state transition occurs.
825
- *
826
- * Note that some actors, such as callback actors generated with `fromCallback`, will not emit snapshots.
827
- *
828
- * @see {@link Actor.subscribe} to subscribe to an actor’s snapshot values.
829
- * @see {@link Actor.getPersistedState} to persist the internal state of an actor (which is more than just a snapshot).
830
- */
831
- getSnapshot() {
832
- return this._state;
833
- }
834
- }
835
-
836
- /**
837
- * Creates a new `ActorRef` instance for the given machine with the provided options, if any.
838
- *
839
- * @param machine The machine to create an actor from
840
- * @param options `ActorRef` options
841
- */
842
-
843
- function createActor(logic, options) {
844
- const interpreter = new Actor(logic, options);
845
- return interpreter;
846
- }
847
-
848
- /**
849
- * Creates a new Interpreter instance for the given machine with the provided options, if any.
850
- *
851
- * @deprecated Use `createActor` instead
852
- */
853
- const interpret = createActor;
854
-
855
- /**
856
- * @deprecated Use `Actor` instead.
857
- */
858
-
859
- exports.$$ACTOR_TYPE = $$ACTOR_TYPE;
860
- exports.Actor = Actor;
861
- exports.NULL_EVENT = NULL_EVENT;
862
- exports.ProcessingStatus = ProcessingStatus;
863
- exports.STATE_DELIMITER = STATE_DELIMITER;
864
- exports.STATE_IDENTIFIER = STATE_IDENTIFIER;
865
- exports.WILDCARD = WILDCARD;
866
- exports.XSTATE_ERROR = XSTATE_ERROR;
867
- exports.XSTATE_INIT = XSTATE_INIT;
868
- exports.XSTATE_STOP = XSTATE_STOP;
869
- exports.createActor = createActor;
870
- exports.createAfterEvent = createAfterEvent;
871
- exports.createDoneStateEvent = createDoneStateEvent;
872
- exports.createErrorActorEvent = createErrorActorEvent;
873
- exports.createInitEvent = createInitEvent;
874
- exports.createInvokeId = createInvokeId;
875
- exports.flatten = flatten;
876
- exports.interpret = interpret;
877
- exports.isErrorActorEvent = isErrorActorEvent;
878
- exports.mapValues = mapValues;
879
- exports.matchesState = matchesState;
880
- exports.normalizeTarget = normalizeTarget;
881
- exports.pathToStateValue = pathToStateValue;
882
- exports.resolveOutput = resolveOutput;
883
- exports.resolveReferencedActor = resolveReferencedActor;
884
- exports.toArray = toArray;
885
- exports.toObserver = toObserver;
886
- exports.toStatePath = toStatePath;
887
- exports.toTransitionConfigArray = toTransitionConfigArray;