xstate 5.0.0-beta.27 → 5.0.0-beta.28

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 (59) 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 +413 -11
  11. package/actors/dist/xstate-actors.development.cjs.js +413 -11
  12. package/actors/dist/xstate-actors.development.esm.js +405 -4
  13. package/actors/dist/xstate-actors.esm.js +405 -4
  14. package/actors/dist/xstate-actors.umd.min.js +1 -1
  15. package/actors/dist/xstate-actors.umd.min.js.map +1 -1
  16. package/dist/declarations/src/StateNode.d.ts +3 -3
  17. package/dist/declarations/src/actions/assign.d.ts +8 -3
  18. package/dist/declarations/src/actions/choose.d.ts +4 -3
  19. package/dist/declarations/src/actions/pure.d.ts +5 -4
  20. package/dist/declarations/src/actions.d.ts +8 -44
  21. package/dist/declarations/src/actors/index.d.ts +2 -2
  22. package/dist/declarations/src/constants.d.ts +1 -0
  23. package/dist/declarations/src/index.d.ts +9 -16
  24. package/dist/declarations/src/spawn.d.ts +25 -0
  25. package/dist/declarations/src/stateUtils.d.ts +1 -1
  26. package/dist/declarations/src/typegenTypes.d.ts +4 -4
  27. package/dist/declarations/src/types.d.ts +72 -94
  28. package/dist/declarations/src/utils.d.ts +2 -2
  29. package/dist/interpreter-672794ae.cjs.js +792 -0
  30. package/dist/interpreter-a1432c7d.development.cjs.js +800 -0
  31. package/dist/interpreter-a77bb0ec.development.esm.js +765 -0
  32. package/dist/interpreter-b5203bcb.esm.js +757 -0
  33. package/dist/{actions-9754d2ca.development.esm.js → raise-436a57a2.cjs.js} +130 -1307
  34. package/dist/{actions-ca622922.development.cjs.js → raise-74b72ca5.development.cjs.js} +101 -1306
  35. package/dist/{actions-020463e9.esm.js → raise-a60c9290.development.esm.js} +109 -1203
  36. package/dist/{actions-d1dba4ac.cjs.js → raise-b9c9a234.esm.js} +65 -1267
  37. package/dist/send-35e1a689.cjs.js +349 -0
  38. package/dist/send-4192e7bc.esm.js +339 -0
  39. package/dist/send-e63b7b83.development.esm.js +364 -0
  40. package/dist/send-e8b55d00.development.cjs.js +374 -0
  41. package/dist/xstate.cjs.js +110 -106
  42. package/dist/xstate.cjs.mjs +4 -2
  43. package/dist/xstate.development.cjs.js +110 -106
  44. package/dist/xstate.development.cjs.mjs +4 -2
  45. package/dist/xstate.development.esm.js +72 -68
  46. package/dist/xstate.esm.js +72 -68
  47. package/dist/xstate.umd.min.js +1 -1
  48. package/dist/xstate.umd.min.js.map +1 -1
  49. package/guards/dist/xstate-guards.cjs.js +2 -1
  50. package/guards/dist/xstate-guards.development.cjs.js +2 -1
  51. package/guards/dist/xstate-guards.development.esm.js +2 -1
  52. package/guards/dist/xstate-guards.esm.js +2 -1
  53. package/guards/dist/xstate-guards.umd.min.js.map +1 -1
  54. package/package.json +1 -1
  55. package/dist/declarations/src/constantPrefixes.d.ts +0 -6
  56. package/dist/promise-2ad94e3b.development.esm.js +0 -406
  57. package/dist/promise-3b7e3357.development.cjs.js +0 -412
  58. package/dist/promise-5b07c38e.esm.js +0 -406
  59. package/dist/promise-7a8c1768.cjs.js +0 -412
@@ -1,196 +1,4 @@
1
- import { devToolsAdapter } from '../dev/dist/xstate-dev.esm.js';
2
-
3
- /**
4
- * `T | unknown` reduces to `unknown` and that can be problematic when it comes to contextual typing.
5
- * It especially is a problem when the union has a function member, like here:
6
- *
7
- * ```ts
8
- * declare function test(cbOrVal: ((arg: number) => unknown) | unknown): void;
9
- * test((arg) => {}) // oops, implicit any
10
- * ```
11
- *
12
- * This type can be used to avoid this problem. This union represents the same value space as `unknown`.
13
- */
14
-
15
- // https://github.com/microsoft/TypeScript/issues/23182#issuecomment-379091887
16
-
17
- /**
18
- * The full definition of an event, with a string `type`.
19
- */
20
-
21
- // TODO: do not accept machines without all implementations
22
- // we should also accept a raw machine as actor logic here
23
- // or just make machine actor logic
24
-
25
- /**
26
- * The string or object representing the state value relative to the parent state node.
27
- *
28
- * - For a child atomic state node, this is a string, e.g., `"pending"`.
29
- * - For complex state nodes, this is an object, e.g., `{ success: "someChildState" }`.
30
- */
31
-
32
- // TODO: remove once TS fixes this type-widening issue
33
-
34
- // TODO: possibly refactor this somehow, use even a simpler type, and maybe even make `machine.options` private or something
35
-
36
- let ConstantPrefix = /*#__PURE__*/function (ConstantPrefix) {
37
- ConstantPrefix["After"] = "xstate.after";
38
- ConstantPrefix["DoneState"] = "done.state";
39
- ConstantPrefix["DoneInvoke"] = "done.invoke";
40
- ConstantPrefix["ErrorExecution"] = "error.execution";
41
- ConstantPrefix["ErrorCommunication"] = "error.communication";
42
- ConstantPrefix["ErrorPlatform"] = "error.platform";
43
- ConstantPrefix["ErrorCustom"] = "xstate.error";
44
- return ConstantPrefix;
45
- }({});
46
- let SpecialTargets = /*#__PURE__*/function (SpecialTargets) {
47
- SpecialTargets["Parent"] = "#_parent";
48
- SpecialTargets["Internal"] = "#_internal";
49
- return SpecialTargets;
50
- }({});
51
-
52
- const after$1 = ConstantPrefix.After;
53
- const doneState = ConstantPrefix.DoneState;
54
- const errorExecution = ConstantPrefix.ErrorExecution;
55
- const errorPlatform = ConstantPrefix.ErrorPlatform;
56
- const error$1 = ConstantPrefix.ErrorCustom;
57
-
58
- var constantPrefixes = /*#__PURE__*/Object.freeze({
59
- __proto__: null,
60
- after: after$1,
61
- doneState: doneState,
62
- errorExecution: errorExecution,
63
- errorPlatform: errorPlatform,
64
- error: error$1
65
- });
66
-
67
- const STATE_DELIMITER = '.';
68
- const TARGETLESS_KEY = '';
69
- const NULL_EVENT = '';
70
- const STATE_IDENTIFIER = '#';
71
- const WILDCARD = '*';
72
- const XSTATE_INIT = 'xstate.init';
73
- const XSTATE_STOP = 'xstate.stop';
74
-
75
- function resolve$8(actorContext, state, args, {
76
- to,
77
- event: eventOrExpr,
78
- id,
79
- delay
80
- }) {
81
- const delaysMap = state.machine.implementations.delays;
82
- if (typeof eventOrExpr === 'string') {
83
- throw new Error(`Only event objects may be used with sendTo; use sendTo({ type: "${eventOrExpr}" }) instead`);
84
- }
85
- const resolvedEvent = typeof eventOrExpr === 'function' ? eventOrExpr(args) : eventOrExpr;
86
- let resolvedDelay;
87
- if (typeof delay === 'string') {
88
- const configDelay = delaysMap && delaysMap[delay];
89
- resolvedDelay = typeof configDelay === 'function' ? configDelay(args) : configDelay;
90
- } else {
91
- resolvedDelay = typeof delay === 'function' ? delay(args) : delay;
92
- }
93
- const resolvedTarget = typeof to === 'function' ? to(args) : to;
94
- let targetActorRef;
95
- if (typeof resolvedTarget === 'string') {
96
- if (resolvedTarget === SpecialTargets.Parent) {
97
- targetActorRef = actorContext?.self._parent;
98
- } else if (resolvedTarget === SpecialTargets.Internal) {
99
- targetActorRef = actorContext?.self;
100
- } else if (resolvedTarget.startsWith('#_')) {
101
- // SCXML compatibility: https://www.w3.org/TR/scxml/#SCXMLEventProcessor
102
- // #_invokeid. If the target is the special term '#_invokeid', where invokeid is the invokeid of an SCXML session that the sending session has created by <invoke>, the Processor must add the event to the external queue of that session.
103
- targetActorRef = state.children[resolvedTarget.slice(2)];
104
- } else {
105
- targetActorRef = state.children[resolvedTarget];
106
- }
107
- if (!targetActorRef) {
108
- throw new Error(`Unable to send event to actor '${resolvedTarget}' from machine '${state.machine.id}'.`);
109
- }
110
- } else {
111
- targetActorRef = resolvedTarget || actorContext?.self;
112
- }
113
- return [state, {
114
- to: targetActorRef,
115
- event: resolvedEvent,
116
- id,
117
- delay: resolvedDelay
118
- }];
119
- }
120
- function execute$5(actorContext, params) {
121
- if (typeof params.delay === 'number') {
122
- actorContext.self.delaySend(params);
123
- return;
124
- }
125
- const {
126
- to,
127
- event
128
- } = params;
129
- actorContext.defer(() => {
130
- to.send(event.type === error$1 ? {
131
- type: `${error(actorContext.self.id)}`,
132
- data: event.data
133
- } : event);
134
- });
135
- }
136
- /**
137
- * Sends an event to an actor.
138
- *
139
- * @param actor The `ActorRef` to send the event to.
140
- * @param event The event to send, or an expression that evaluates to the event to send
141
- * @param options Send action options
142
- * - `id` - The unique send event identifier (used with `cancel()`).
143
- * - `delay` - The number of milliseconds to delay the sending of the event.
144
- */
145
- function sendTo(to, eventOrExpr, options) {
146
- function sendTo(_) {
147
- }
148
- sendTo.type = 'xstate.sendTo';
149
- sendTo.to = to;
150
- sendTo.event = eventOrExpr;
151
- sendTo.id = options?.id;
152
- sendTo.delay = options?.delay;
153
- sendTo.resolve = resolve$8;
154
- sendTo.execute = execute$5;
155
- return sendTo;
156
- }
157
-
158
- /**
159
- * Sends an event to this machine's parent.
160
- *
161
- * @param event The event to send to the parent machine.
162
- * @param options Options to pass into the send event.
163
- */
164
- function sendParent(event, options) {
165
- return sendTo(SpecialTargets.Parent, event, options);
166
- }
167
- /**
168
- * Forwards (sends) an event to a specified service.
169
- *
170
- * @param target The target service to forward the event to.
171
- * @param options Options to pass into the send action creator.
172
- */
173
- function forwardTo(target, options) {
174
- return sendTo(target, ({
175
- event
176
- }) => event, options);
177
- }
178
-
179
- /**
180
- * Escalates an error by sending it as an event to this machine's parent.
181
- *
182
- * @param errorData The error data to send, or the expression function that
183
- * takes in the `context`, `event`, and `meta`, and returns the error data to send.
184
- * @param options Options to pass into the send action creator.
185
- */
186
- function escalate(errorData, options) {
187
- return sendParent(arg => {
188
- return {
189
- type: error$1,
190
- data: typeof errorData === 'function' ? errorData(arg) : errorData
191
- };
192
- }, options);
193
- }
1
+ import { r as resolveReferencedActor, d as createActor, f as ActorStatus, l as createErrorActorEvent, o as toStateValue, q as STATE_IDENTIFIER, u as normalizeTarget, t as toArray, N as NULL_EVENT, a as toTransitionConfigArray, S as STATE_DELIMITER, v as toStatePath, w as createDoneStateEvent, x as mapContext, W as WILDCARD, n as XSTATE_STOP, X as XSTATE_INIT, y as isArray, z as createAfterEvent, B as flatten, e as matchesState } from './interpreter-a77bb0ec.development.esm.js';
194
2
 
195
3
  const cache = new WeakMap();
196
4
  function memo(object, key, fn) {
@@ -206,13 +14,13 @@ function memo(object, key, fn) {
206
14
  return memoizedData[key];
207
15
  }
208
16
 
209
- function resolve$7(_, state, actionArgs, {
17
+ function resolve$3(_, state, actionArgs, {
210
18
  sendId
211
19
  }) {
212
20
  const resolvedSendId = typeof sendId === 'function' ? sendId(actionArgs) : sendId;
213
21
  return [state, resolvedSendId];
214
22
  }
215
- function execute$4(actorContext, resolvedSendId) {
23
+ function execute$3(actorContext, resolvedSendId) {
216
24
  actorContext.self.cancel(resolvedSendId);
217
25
  }
218
26
  /**
@@ -224,704 +32,18 @@ function execute$4(actorContext, resolvedSendId) {
224
32
  */
225
33
  function cancel(sendId) {
226
34
  function cancel(_) {
35
+ {
36
+ throw new Error(`This isn't supposed to be called`);
37
+ }
227
38
  }
228
39
  cancel.type = 'xstate.cancel';
229
40
  cancel.sendId = sendId;
230
- cancel.resolve = resolve$7;
231
- cancel.execute = execute$4;
41
+ cancel.resolve = resolve$3;
42
+ cancel.execute = execute$3;
232
43
  return cancel;
233
44
  }
234
45
 
235
- class Mailbox {
236
- constructor(_process) {
237
- this._process = _process;
238
- this._active = false;
239
- this._current = null;
240
- this._last = null;
241
- }
242
- start() {
243
- this._active = true;
244
- this.flush();
245
- }
246
- clear() {
247
- // we can't set _current to null because we might be currently processing
248
- // and enqueue following clear shouldnt start processing the enqueued item immediately
249
- if (this._current) {
250
- this._current.next = null;
251
- this._last = this._current;
252
- }
253
- }
254
-
255
- // TODO: rethink this design
256
- prepend(event) {
257
- if (!this._current) {
258
- this.enqueue(event);
259
- return;
260
- }
261
-
262
- // we know that something is already queued up
263
- // so the mailbox is already flushing or it's inactive
264
- // therefore the only thing that we need to do is to reassign `this._current`
265
- this._current = {
266
- value: event,
267
- next: this._current
268
- };
269
- }
270
- enqueue(event) {
271
- const enqueued = {
272
- value: event,
273
- next: null
274
- };
275
- if (this._current) {
276
- this._last.next = enqueued;
277
- this._last = enqueued;
278
- return;
279
- }
280
- this._current = enqueued;
281
- this._last = enqueued;
282
- if (this._active) {
283
- this.flush();
284
- }
285
- }
286
- flush() {
287
- while (this._current) {
288
- // atm the given _process is responsible for implementing proper try/catch handling
289
- // we assume here that this won't throw in a way that can affect this mailbox
290
- const consumed = this._current;
291
- this._process(consumed.value);
292
- // something could have been prepended in the meantime
293
- // so we need to be defensive here to avoid skipping over a prepended item
294
- if (consumed === this._current) {
295
- this._current = this._current.next;
296
- }
297
- }
298
- this._last = null;
299
- }
300
- }
301
-
302
- /**
303
- * This function makes sure that unhandled errors are thrown in a separate macrotask.
304
- * It allows those errors to be detected by global error handlers and reported to bug tracking services
305
- * without interrupting our own stack of execution.
306
- *
307
- * @param err error to be thrown
308
- */
309
- function reportUnhandledError(err) {
310
- setTimeout(() => {
311
- throw err;
312
- });
313
- }
314
-
315
- const symbolObservable = (() => typeof Symbol === 'function' && Symbol.observable || '@@observable')();
316
-
317
- function createSystem() {
318
- let sessionIdCounter = 0;
319
- const children = new Map();
320
- const keyedActors = new Map();
321
- const reverseKeyedActors = new WeakMap();
322
- const system = {
323
- _bookId: () => `x:${sessionIdCounter++}`,
324
- _register: (sessionId, actorRef) => {
325
- children.set(sessionId, actorRef);
326
- return sessionId;
327
- },
328
- _unregister: actorRef => {
329
- children.delete(actorRef.sessionId);
330
- const systemId = reverseKeyedActors.get(actorRef);
331
- if (systemId !== undefined) {
332
- keyedActors.delete(systemId);
333
- reverseKeyedActors.delete(actorRef);
334
- }
335
- },
336
- get: systemId => {
337
- return keyedActors.get(systemId);
338
- },
339
- _set: (systemId, actorRef) => {
340
- const existing = keyedActors.get(systemId);
341
- if (existing && existing !== actorRef) {
342
- throw new Error(`Actor with system ID '${systemId}' already exists.`);
343
- }
344
- keyedActors.set(systemId, actorRef);
345
- reverseKeyedActors.set(actorRef, systemId);
346
- }
347
- };
348
- return system;
349
- }
350
-
351
- function matchesState(parentStateId, childStateId) {
352
- const parentStateValue = toStateValue(parentStateId);
353
- const childStateValue = toStateValue(childStateId);
354
- if (typeof childStateValue === 'string') {
355
- if (typeof parentStateValue === 'string') {
356
- return childStateValue === parentStateValue;
357
- }
358
-
359
- // Parent more specific than child
360
- return false;
361
- }
362
- if (typeof parentStateValue === 'string') {
363
- return parentStateValue in childStateValue;
364
- }
365
- return Object.keys(parentStateValue).every(key => {
366
- if (!(key in childStateValue)) {
367
- return false;
368
- }
369
- return matchesState(parentStateValue[key], childStateValue[key]);
370
- });
371
- }
372
- function toStatePath(stateId) {
373
- try {
374
- if (isArray(stateId)) {
375
- return stateId;
376
- }
377
- return stateId.toString().split(STATE_DELIMITER);
378
- } catch (e) {
379
- throw new Error(`'${stateId}' is not a valid state path.`);
380
- }
381
- }
382
- function isStateLike(state) {
383
- return typeof state === 'object' && 'value' in state && 'context' in state && 'event' in state;
384
- }
385
- function toStateValue(stateValue) {
386
- if (isStateLike(stateValue)) {
387
- return stateValue.value;
388
- }
389
- if (isArray(stateValue)) {
390
- return pathToStateValue(stateValue);
391
- }
392
- if (typeof stateValue !== 'string') {
393
- return stateValue;
394
- }
395
- const statePath = toStatePath(stateValue);
396
- return pathToStateValue(statePath);
397
- }
398
- function pathToStateValue(statePath) {
399
- if (statePath.length === 1) {
400
- return statePath[0];
401
- }
402
- const value = {};
403
- let marker = value;
404
- for (let i = 0; i < statePath.length - 1; i++) {
405
- if (i === statePath.length - 2) {
406
- marker[statePath[i]] = statePath[i + 1];
407
- } else {
408
- const previous = marker;
409
- marker = {};
410
- previous[statePath[i]] = marker;
411
- }
412
- }
413
- return value;
414
- }
415
- function mapValues(collection, iteratee) {
416
- const result = {};
417
- const collectionKeys = Object.keys(collection);
418
- for (let i = 0; i < collectionKeys.length; i++) {
419
- const key = collectionKeys[i];
420
- result[key] = iteratee(collection[key], key, collection, i);
421
- }
422
- return result;
423
- }
424
- function flatten(array) {
425
- return [].concat(...array);
426
- }
427
- function toArrayStrict(value) {
428
- if (isArray(value)) {
429
- return value;
430
- }
431
- return [value];
432
- }
433
- function toArray(value) {
434
- if (value === undefined) {
435
- return [];
436
- }
437
- return toArrayStrict(value);
438
- }
439
- function mapContext(mapper, context, event, self) {
440
- if (typeof mapper === 'function') {
441
- return mapper({
442
- context,
443
- event,
444
- self
445
- });
446
- }
447
- return mapper;
448
- }
449
- function isPromiseLike(value) {
450
- if (value instanceof Promise) {
451
- return true;
452
- }
453
- // Check if shape matches the Promise/A+ specification for a "thenable".
454
- if (value !== null && (typeof value === 'function' || typeof value === 'object') && typeof value.then === 'function') {
455
- return true;
456
- }
457
- return false;
458
- }
459
- function isArray(value) {
460
- return Array.isArray(value);
461
- }
462
- function isErrorEvent(event) {
463
- return typeof event.type === 'string' && (event.type === errorExecution || event.type.startsWith(errorPlatform));
464
- }
465
- function toTransitionConfigArray(configLike) {
466
- return toArrayStrict(configLike).map(transitionLike => {
467
- if (typeof transitionLike === 'undefined' || typeof transitionLike === 'string') {
468
- return {
469
- target: transitionLike
470
- };
471
- }
472
- return transitionLike;
473
- });
474
- }
475
- function normalizeTarget(target) {
476
- if (target === undefined || target === TARGETLESS_KEY) {
477
- return undefined;
478
- }
479
- return toArray(target);
480
- }
481
- function toObserver(nextHandler, errorHandler, completionHandler) {
482
- const isObserver = typeof nextHandler === 'object';
483
- const self = isObserver ? nextHandler : undefined;
484
- return {
485
- next: (isObserver ? nextHandler.next : nextHandler)?.bind(self),
486
- error: (isObserver ? nextHandler.error : errorHandler)?.bind(self),
487
- complete: (isObserver ? nextHandler.complete : completionHandler)?.bind(self)
488
- };
489
- }
490
- function createInvokeId(stateNodeId, index) {
491
- return `${stateNodeId}:invocation[${index}]`;
492
- }
493
- function resolveReferencedActor(referenced) {
494
- return referenced ? 'transition' in referenced ? {
495
- src: referenced,
496
- input: undefined
497
- } : referenced : undefined;
498
- }
499
-
500
- let ActorStatus = /*#__PURE__*/function (ActorStatus) {
501
- ActorStatus[ActorStatus["NotStarted"] = 0] = "NotStarted";
502
- ActorStatus[ActorStatus["Running"] = 1] = "Running";
503
- ActorStatus[ActorStatus["Stopped"] = 2] = "Stopped";
504
- return ActorStatus;
505
- }({});
506
-
507
- /**
508
- * @deprecated Use `ActorStatus` instead.
509
- */
510
- const InterpreterStatus = ActorStatus;
511
- const defaultOptions = {
512
- deferEvents: true,
513
- clock: {
514
- setTimeout: (fn, ms) => {
515
- return setTimeout(fn, ms);
516
- },
517
- clearTimeout: id => {
518
- return clearTimeout(id);
519
- }
520
- },
521
- logger: console.log.bind(console),
522
- devTools: false
523
- };
524
- class Actor {
525
- /**
526
- * The current internal state of the actor.
527
- */
528
-
529
- /**
530
- * The clock that is responsible for setting and clearing timeouts, such as delayed events and transitions.
531
- */
532
-
533
- /**
534
- * The unique identifier for this actor relative to its parent.
535
- */
536
-
537
- /**
538
- * Whether the service is started.
539
- */
540
-
541
- // Actor Ref
542
-
543
- // TODO: add typings for system
544
-
545
- /**
546
- * The globally unique process ID for this invocation.
547
- */
548
-
549
- /**
550
- * Creates a new actor instance for the given logic with the provided options, if any.
551
- *
552
- * @param logic The logic to create an actor from
553
- * @param options Actor options
554
- */
555
- constructor(logic, options) {
556
- this.logic = logic;
557
- this._state = void 0;
558
- this.clock = void 0;
559
- this.options = void 0;
560
- this.id = void 0;
561
- this.mailbox = new Mailbox(this._process.bind(this));
562
- this.delayedEventsMap = {};
563
- this.observers = new Set();
564
- this.logger = void 0;
565
- this.status = ActorStatus.NotStarted;
566
- this._parent = void 0;
567
- this.ref = void 0;
568
- this._actorContext = void 0;
569
- this._systemId = void 0;
570
- this.sessionId = void 0;
571
- this.system = void 0;
572
- this._doneEvent = void 0;
573
- this.src = void 0;
574
- this._deferred = [];
575
- const resolvedOptions = {
576
- ...defaultOptions,
577
- ...options
578
- };
579
- const {
580
- clock,
581
- logger,
582
- parent,
583
- id,
584
- systemId
585
- } = resolvedOptions;
586
- const self = this;
587
- this.system = parent?.system ?? createSystem();
588
- if (systemId) {
589
- this._systemId = systemId;
590
- this.system._set(systemId, this);
591
- }
592
- this.sessionId = this.system._bookId();
593
- this.id = id ?? this.sessionId;
594
- this.logger = logger;
595
- this.clock = clock;
596
- this._parent = parent;
597
- this.options = resolvedOptions;
598
- this.src = resolvedOptions.src;
599
- this.ref = this;
600
- this._actorContext = {
601
- self,
602
- id: this.id,
603
- sessionId: this.sessionId,
604
- logger: this.logger,
605
- defer: fn => {
606
- this._deferred.push(fn);
607
- },
608
- system: this.system,
609
- stopChild: child => {
610
- if (child._parent !== this) {
611
- throw new Error(`Cannot stop child actor ${child.id} of ${this.id} because it is not a child`);
612
- }
613
- child._stop();
614
- }
615
- };
616
-
617
- // Ensure that the send method is bound to this Actor instance
618
- // if destructured
619
- this.send = this.send.bind(this);
620
- this._initState();
621
- }
622
- _initState() {
623
- 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);
624
- }
625
-
626
- // array of functions to defer
627
-
628
- update(state) {
629
- // Update state
630
- this._state = state;
631
- const snapshot = this.getSnapshot();
632
-
633
- // Execute deferred effects
634
- let deferredFn;
635
- while (deferredFn = this._deferred.shift()) {
636
- deferredFn();
637
- }
638
- for (const observer of this.observers) {
639
- // TODO: should observers be notified in case of the error?
640
- try {
641
- observer.next?.(snapshot);
642
- } catch (err) {
643
- reportUnhandledError(err);
644
- }
645
- }
646
- const status = this.logic.getStatus?.(state);
647
- switch (status?.status) {
648
- case 'done':
649
- this._stopProcedure();
650
- this._complete();
651
- this._doneEvent = doneInvoke(this.id, status.data);
652
- this._parent?.send(this._doneEvent);
653
- break;
654
- case 'error':
655
- this._stopProcedure();
656
- this._error(status.data);
657
- this._parent?.send(error(this.id, status.data));
658
- break;
659
- }
660
- }
661
- subscribe(nextListenerOrObserver, errorListener, completeListener) {
662
- const observer = toObserver(nextListenerOrObserver, errorListener, completeListener);
663
- if (this.status !== ActorStatus.Stopped) {
664
- this.observers.add(observer);
665
- } else {
666
- try {
667
- observer.complete?.();
668
- } catch (err) {
669
- reportUnhandledError(err);
670
- }
671
- }
672
- return {
673
- unsubscribe: () => {
674
- this.observers.delete(observer);
675
- }
676
- };
677
- }
678
-
679
- /**
680
- * Starts the Actor from the initial state
681
- */
682
- start() {
683
- if (this.status === ActorStatus.Running) {
684
- // Do not restart the service if it is already started
685
- return this;
686
- }
687
- this.system._register(this.sessionId, this);
688
- if (this._systemId) {
689
- this.system._set(this._systemId, this);
690
- }
691
- this.status = ActorStatus.Running;
692
- const status = this.logic.getStatus?.(this._state);
693
- switch (status?.status) {
694
- case 'done':
695
- // a state machine can be "done" upon intialization (it could reach a final state using initial microsteps)
696
- // we still need to complete observers, flush deferreds etc
697
- this.update(this._state);
698
- // fallthrough
699
- case 'error':
700
- // TODO: rethink cleanup of observers, mailbox, etc
701
- return this;
702
- }
703
- if (this.logic.start) {
704
- try {
705
- this.logic.start(this._state, this._actorContext);
706
- } catch (err) {
707
- this._stopProcedure();
708
- this._error(err);
709
- this._parent?.send(error(this.id, err));
710
- return this;
711
- }
712
- }
713
-
714
- // TODO: this notifies all subscribers but usually this is redundant
715
- // there is no real change happening here
716
- // we need to rethink if this needs to be refactored
717
- this.update(this._state);
718
- if (this.options.devTools) {
719
- this.attachDevTools();
720
- }
721
- this.mailbox.start();
722
- return this;
723
- }
724
- _process(event) {
725
- // TODO: reexamine what happens when an action (or a guard or smth) throws
726
- let nextState;
727
- let caughtError;
728
- try {
729
- nextState = this.logic.transition(this._state, event, this._actorContext);
730
- } catch (err) {
731
- // we wrap it in a box so we can rethrow it later even if falsy value gets caught here
732
- caughtError = {
733
- err
734
- };
735
- }
736
- if (caughtError) {
737
- const {
738
- err
739
- } = caughtError;
740
- this._stopProcedure();
741
- this._error(err);
742
- this._parent?.send(error(this.id, err));
743
- return;
744
- }
745
- this.update(nextState);
746
- if (event.type === XSTATE_STOP) {
747
- this._stopProcedure();
748
- this._complete();
749
- }
750
- }
751
- _stop() {
752
- if (this.status === ActorStatus.Stopped) {
753
- return this;
754
- }
755
- this.mailbox.clear();
756
- if (this.status === ActorStatus.NotStarted) {
757
- this.status = ActorStatus.Stopped;
758
- return this;
759
- }
760
- this.mailbox.enqueue({
761
- type: XSTATE_STOP
762
- });
763
- return this;
764
- }
765
-
766
- /**
767
- * Stops the Actor and unsubscribe all listeners.
768
- */
769
- stop() {
770
- if (this._parent) {
771
- throw new Error('A non-root actor cannot be stopped directly.');
772
- }
773
- return this._stop();
774
- }
775
- _complete() {
776
- for (const observer of this.observers) {
777
- try {
778
- observer.complete?.();
779
- } catch (err) {
780
- reportUnhandledError(err);
781
- }
782
- }
783
- this.observers.clear();
784
- }
785
- _error(err) {
786
- if (!this.observers.size) {
787
- if (!this._parent) {
788
- reportUnhandledError(err);
789
- }
790
- return;
791
- }
792
- let reportError = false;
793
- for (const observer of this.observers) {
794
- const errorListener = observer.error;
795
- reportError ||= !errorListener;
796
- try {
797
- errorListener?.(err);
798
- } catch (err2) {
799
- reportUnhandledError(err2);
800
- }
801
- }
802
- this.observers.clear();
803
- if (reportError) {
804
- reportUnhandledError(err);
805
- }
806
- }
807
- _stopProcedure() {
808
- if (this.status !== ActorStatus.Running) {
809
- // Actor already stopped; do nothing
810
- return this;
811
- }
812
-
813
- // Cancel all delayed events
814
- for (const key of Object.keys(this.delayedEventsMap)) {
815
- this.clock.clearTimeout(this.delayedEventsMap[key]);
816
- }
817
-
818
- // TODO: mailbox.reset
819
- this.mailbox.clear();
820
- // TODO: after `stop` we must prepare ourselves for receiving events again
821
- // events sent *after* stop signal must be queued
822
- // it seems like this should be the common behavior for all of our consumers
823
- // so perhaps this should be unified somehow for all of them
824
- this.mailbox = new Mailbox(this._process.bind(this));
825
- this.status = ActorStatus.Stopped;
826
- this.system._unregister(this);
827
- return this;
828
- }
829
-
830
- /**
831
- * Sends an event to the running Actor to trigger a transition.
832
- *
833
- * @param event The event to send
834
- */
835
- send(event) {
836
- if (typeof event === 'string') {
837
- throw new Error(`Only event objects may be sent to actors; use .send({ type: "${event}" }) instead`);
838
- }
839
- if (this.status === ActorStatus.Stopped) {
840
- return;
841
- }
842
- if (this.status !== ActorStatus.Running && !this.options.deferEvents) {
843
- throw new Error(`Event "${event.type}" was sent to uninitialized actor "${this.id
844
- // tslint:disable-next-line:max-line-length
845
- }". Make sure .start() is called for this actor, or set { deferEvents: true } in the actor options.\nEvent: ${JSON.stringify(event)}`);
846
- }
847
- this.mailbox.enqueue(event);
848
- }
849
-
850
- // TODO: make private (and figure out a way to do this within the machine)
851
- delaySend({
852
- event,
853
- id,
854
- delay,
855
- to
856
- }) {
857
- const timerId = this.clock.setTimeout(() => {
858
- if (to) {
859
- to.send(event);
860
- } else {
861
- this.send(event);
862
- }
863
- }, delay);
864
-
865
- // TODO: consider the rehydration story here
866
- if (id) {
867
- this.delayedEventsMap[id] = timerId;
868
- }
869
- }
870
-
871
- // TODO: make private (and figure out a way to do this within the machine)
872
- cancel(sendId) {
873
- this.clock.clearTimeout(this.delayedEventsMap[sendId]);
874
- delete this.delayedEventsMap[sendId];
875
- }
876
- attachDevTools() {
877
- const {
878
- devTools
879
- } = this.options;
880
- if (devTools) {
881
- const resolvedDevToolsAdapter = typeof devTools === 'function' ? devTools : devToolsAdapter;
882
- resolvedDevToolsAdapter(this);
883
- }
884
- }
885
- toJSON() {
886
- return {
887
- id: this.id
888
- };
889
- }
890
- getPersistedState() {
891
- return this.logic.getPersistedState?.(this._state);
892
- }
893
- [symbolObservable]() {
894
- return this;
895
- }
896
- getSnapshot() {
897
- return this.logic.getSnapshot ? this.logic.getSnapshot(this._state) : this._state;
898
- }
899
- }
900
-
901
- /**
902
- * Creates a new `ActorRef` instance for the given machine with the provided options, if any.
903
- *
904
- * @param machine The machine to create an actor from
905
- * @param options `ActorRef` options
906
- */
907
-
908
- function createActor(logic, options) {
909
- const interpreter = new Actor(logic, options);
910
- return interpreter;
911
- }
912
-
913
- /**
914
- * Creates a new Interpreter instance for the given machine with the provided options, if any.
915
- *
916
- * @deprecated Use `createActor` instead
917
- */
918
- const interpret = createActor;
919
-
920
- /**
921
- * @deprecated Use `Actor` instead.
922
- */
923
-
924
- function resolve$6(actorContext, state, actionArgs, {
46
+ function resolve$2(actorContext, state, actionArgs, {
925
47
  id,
926
48
  systemId,
927
49
  src,
@@ -944,6 +66,9 @@ function resolve$6(actorContext, state, actionArgs, {
944
66
  }) : configuredInput
945
67
  });
946
68
  }
69
+ if (!actorRef) {
70
+ console.warn(`Actor type '${src}' not found in machine '${actorContext.id}'.`);
71
+ }
947
72
  return [cloneState(state, {
948
73
  children: {
949
74
  ...state.children,
@@ -954,7 +79,7 @@ function resolve$6(actorContext, state, actionArgs, {
954
79
  actorRef
955
80
  }];
956
81
  }
957
- function execute$3(actorContext, {
82
+ function execute$2(actorContext, {
958
83
  id,
959
84
  actorRef
960
85
  }) {
@@ -968,7 +93,7 @@ function execute$3(actorContext, {
968
93
  try {
969
94
  actorRef.start?.();
970
95
  } catch (err) {
971
- actorContext.self.send(error(id, err));
96
+ actorContext.self.send(createErrorActorEvent(id, err));
972
97
  return;
973
98
  }
974
99
  });
@@ -983,17 +108,67 @@ function invoke({
983
108
  input
984
109
  }) {
985
110
  function invoke(_) {
111
+ {
112
+ throw new Error(`This isn't supposed to be called`);
113
+ }
986
114
  }
987
115
  invoke.type = 'xstate.invoke';
988
116
  invoke.id = id;
989
117
  invoke.systemId = systemId;
990
118
  invoke.src = src;
991
119
  invoke.input = input;
992
- invoke.resolve = resolve$6;
993
- invoke.execute = execute$3;
120
+ invoke.resolve = resolve$2;
121
+ invoke.execute = execute$2;
994
122
  return invoke;
995
123
  }
996
124
 
125
+ function resolve$1(_, state, args, {
126
+ actorRef
127
+ }) {
128
+ const actorRefOrString = typeof actorRef === 'function' ? actorRef(args) : actorRef;
129
+ const resolvedActorRef = typeof actorRefOrString === 'string' ? state.children[actorRefOrString] : actorRefOrString;
130
+ let children = state.children;
131
+ if (resolvedActorRef) {
132
+ children = {
133
+ ...children
134
+ };
135
+ delete children[resolvedActorRef.id];
136
+ }
137
+ return [cloneState(state, {
138
+ children
139
+ }), resolvedActorRef];
140
+ }
141
+ function execute$1(actorContext, actorRef) {
142
+ if (!actorRef) {
143
+ return;
144
+ }
145
+ if (actorRef.status !== ActorStatus.Running) {
146
+ actorContext.stopChild(actorRef);
147
+ return;
148
+ }
149
+ // TODO: recheck why this one has to be deferred
150
+ actorContext.defer(() => {
151
+ actorContext.stopChild(actorRef);
152
+ });
153
+ }
154
+ /**
155
+ * Stops an actor.
156
+ *
157
+ * @param actorRef The actor to stop.
158
+ */
159
+ function stop(actorRef) {
160
+ function stop(_) {
161
+ {
162
+ throw new Error(`This isn't supposed to be called`);
163
+ }
164
+ }
165
+ stop.type = 'xstate.stop';
166
+ stop.actorRef = actorRef;
167
+ stop.resolve = resolve$1;
168
+ stop.execute = execute$1;
169
+ return stop;
170
+ }
171
+
997
172
  function checkStateIn(state, _, {
998
173
  stateValue
999
174
  }) {
@@ -1004,7 +179,9 @@ function checkStateIn(state, _, {
1004
179
  }
1005
180
  function stateIn(stateValue) {
1006
181
  function stateIn(_) {
1007
- return false;
182
+ {
183
+ throw new Error(`This isn't supposed to be called`);
184
+ }
1008
185
  }
1009
186
  stateIn.check = checkStateIn;
1010
187
  stateIn.stateValue = stateValue;
@@ -1020,7 +197,9 @@ function checkNot(state, {
1020
197
  }
1021
198
  function not(guard) {
1022
199
  function not(_) {
1023
- return false;
200
+ {
201
+ throw new Error(`This isn't supposed to be called`);
202
+ }
1024
203
  }
1025
204
  not.check = checkNot;
1026
205
  not.guards = [guard];
@@ -1036,7 +215,9 @@ function checkAnd(state, {
1036
215
  }
1037
216
  function and(guards) {
1038
217
  function and(_) {
1039
- return false;
218
+ {
219
+ throw new Error(`This isn't supposed to be called`);
220
+ }
1040
221
  }
1041
222
  and.check = checkAnd;
1042
223
  and.guards = guards;
@@ -1052,7 +233,9 @@ function checkOr(state, {
1052
233
  }
1053
234
  function or(guards) {
1054
235
  function or(_) {
1055
- return false;
236
+ {
237
+ throw new Error(`This isn't supposed to be called`);
238
+ }
1056
239
  }
1057
240
  or.check = checkOr;
1058
241
  or.guards = guards;
@@ -1213,6 +396,9 @@ function getCandidates(stateNode, receivedEventType) {
1213
396
  if (!descriptor.endsWith('.*')) {
1214
397
  return false;
1215
398
  }
399
+ if (/.*\*.+/.test(descriptor)) {
400
+ console.warn(`Wildcards can only be the last token of an event descriptor (e.g., "event.*") or the entire event descriptor ("*"). Check the "${descriptor}" event.`);
401
+ }
1216
402
  const partialEventTokens = descriptor.split('.');
1217
403
  const eventTokens = receivedEventType.split('.');
1218
404
  for (let tokenIndex = 0; tokenIndex < partialEventTokens.length; tokenIndex++) {
@@ -1220,6 +406,9 @@ function getCandidates(stateNode, receivedEventType) {
1220
406
  const eventToken = eventTokens[tokenIndex];
1221
407
  if (partialEventToken === '*') {
1222
408
  const isLastToken = tokenIndex === partialEventTokens.length - 1;
409
+ if (!isLastToken) {
410
+ console.warn(`Infix wildcards in transition events are not allowed. Check the "${descriptor}" transition.`);
411
+ }
1223
412
  return isLastToken;
1224
413
  }
1225
414
  if (partialEventToken !== eventToken) {
@@ -1241,10 +430,9 @@ function getDelayedTransitions(stateNode) {
1241
430
  }
1242
431
  const mutateEntryExit = (delay, i) => {
1243
432
  const delayRef = typeof delay === 'function' ? `${stateNode.id}:delay[${i}]` : delay;
1244
- const eventType = after(delayRef, stateNode.id);
1245
- stateNode.entry.push(raise({
1246
- type: eventType
1247
- }, {
433
+ const afterEvent = createAfterEvent(delayRef, stateNode.id);
434
+ const eventType = afterEvent.type;
435
+ stateNode.entry.push(raise(afterEvent, {
1248
436
  id: eventType,
1249
437
  delay
1250
438
  }));
@@ -1284,6 +472,11 @@ function formatTransition(stateNode, descriptor, transitionConfig) {
1284
472
  const normalizedTarget = normalizeTarget(transitionConfig.target);
1285
473
  const reenter = transitionConfig.reenter ?? false;
1286
474
  const target = resolveTarget(stateNode, normalizedTarget);
475
+
476
+ // TODO: should this be part of a lint rule instead?
477
+ if (transitionConfig.cond) {
478
+ throw new Error(`State "${stateNode.id}" has declared \`cond\` for one of its transitions. This property has been renamed to \`guard\`. Please update your code.`);
479
+ }
1287
480
  const transition = {
1288
481
  ...transitionConfig,
1289
482
  actions: toArray(transitionConfig.actions),
@@ -1312,16 +505,16 @@ function formatTransitions(stateNode) {
1312
505
  }
1313
506
  }
1314
507
  if (stateNode.config.onDone) {
1315
- const descriptor = String(done(stateNode.id));
508
+ const descriptor = `xstate.done.state.${stateNode.id}`;
1316
509
  transitions.set(descriptor, toTransitionConfigArray(stateNode.config.onDone).map(t => formatTransition(stateNode, descriptor, t)));
1317
510
  }
1318
511
  for (const invokeDef of stateNode.invoke) {
1319
512
  if (invokeDef.onDone) {
1320
- const descriptor = `done.invoke.${invokeDef.id}`;
513
+ const descriptor = `xstate.done.actor.${invokeDef.id}`;
1321
514
  transitions.set(descriptor, toTransitionConfigArray(invokeDef.onDone).map(t => formatTransition(stateNode, descriptor, t)));
1322
515
  }
1323
516
  if (invokeDef.onError) {
1324
- const descriptor = `error.platform.${invokeDef.id}`;
517
+ const descriptor = `xstate.error.actor.${invokeDef.id}`;
1325
518
  transitions.set(descriptor, toTransitionConfigArray(invokeDef.onError).map(t => formatTransition(stateNode, descriptor, t)));
1326
519
  }
1327
520
  if (invokeDef.onSnapshot) {
@@ -1766,12 +959,12 @@ function enterStates(event, filteredTransitions, mutConfiguration, actions, inte
1766
959
  if (!parent.parent) {
1767
960
  continue;
1768
961
  }
1769
- internalQueue.push(done(parent.id, stateNodeToEnter.output ? mapContext(stateNodeToEnter.output, currentState.context, event, actorContext.self) : undefined));
962
+ internalQueue.push(createDoneStateEvent(parent.id, stateNodeToEnter.output ? mapContext(stateNodeToEnter.output, currentState.context, event, actorContext.self) : undefined));
1770
963
  if (parent.parent) {
1771
964
  const grandparent = parent.parent;
1772
965
  if (grandparent.type === 'parallel') {
1773
966
  if (getChildren(grandparent).every(parentNode => isInFinalState([...mutConfiguration], parentNode))) {
1774
- internalQueue.push(done(grandparent.id));
967
+ internalQueue.push(createDoneStateEvent(grandparent.id));
1775
968
  }
1776
969
  }
1777
970
  }
@@ -1936,6 +1129,9 @@ function resolveActionsAndContext(actions, event, currentState, actorCtx) {
1936
1129
  return intermediateState;
1937
1130
  }
1938
1131
  function macrostep(state, event, actorCtx) {
1132
+ if (event.type === WILDCARD) {
1133
+ throw new Error(`An event cannot have the wildcard type ('${WILDCARD}')`);
1134
+ }
1939
1135
  let nextState = state;
1940
1136
  const states = [];
1941
1137
 
@@ -2164,6 +1360,9 @@ class State {
2164
1360
  * @returns Whether the event will cause a transition
2165
1361
  */
2166
1362
  can(event) {
1363
+ if (!this.machine) {
1364
+ console.warn(`state.can(...) used outside of a machine-created State object; this will always return false.`);
1365
+ }
2167
1366
  const transitionData = this.machine.getTransitionData(this, event);
2168
1367
  return !!transitionData?.length &&
2169
1368
  // Check that at least one transition is not forbidden
@@ -2214,200 +1413,7 @@ function getPersistedState(state) {
2214
1413
  };
2215
1414
  }
2216
1415
 
2217
- function resolve$5(_, state, args, {
2218
- actorRef
2219
- }) {
2220
- const actorRefOrString = typeof actorRef === 'function' ? actorRef(args) : actorRef;
2221
- const resolvedActorRef = typeof actorRefOrString === 'string' ? state.children[actorRefOrString] : actorRefOrString;
2222
- let children = state.children;
2223
- if (resolvedActorRef) {
2224
- children = {
2225
- ...children
2226
- };
2227
- delete children[resolvedActorRef.id];
2228
- }
2229
- return [cloneState(state, {
2230
- children
2231
- }), resolvedActorRef];
2232
- }
2233
- function execute$2(actorContext, actorRef) {
2234
- if (!actorRef) {
2235
- return;
2236
- }
2237
- if (actorRef.status !== ActorStatus.Running) {
2238
- actorContext.stopChild(actorRef);
2239
- return;
2240
- }
2241
- // TODO: recheck why this one has to be deferred
2242
- actorContext.defer(() => {
2243
- actorContext.stopChild(actorRef);
2244
- });
2245
- }
2246
- /**
2247
- * Stops an actor.
2248
- *
2249
- * @param actorRef The actor to stop.
2250
- */
2251
- function stop(actorRef) {
2252
- function stop(_) {
2253
- }
2254
- stop.type = 'xstate.stop';
2255
- stop.actorRef = actorRef;
2256
- stop.resolve = resolve$5;
2257
- stop.execute = execute$2;
2258
- return stop;
2259
- }
2260
-
2261
- function resolve$4(_, state, actionArgs, {
2262
- value,
2263
- label
2264
- }) {
2265
- return [state, {
2266
- value: typeof value === 'function' ? value(actionArgs) : value,
2267
- label
2268
- }];
2269
- }
2270
- function execute$1({
2271
- logger
2272
- }, {
2273
- value,
2274
- label
2275
- }) {
2276
- if (label) {
2277
- logger(label, value);
2278
- } else {
2279
- logger(value);
2280
- }
2281
- }
2282
- /**
2283
- *
2284
- * @param expr The expression function to evaluate which will be logged.
2285
- * Takes in 2 arguments:
2286
- * - `ctx` - the current state context
2287
- * - `event` - the event that caused this action to be executed.
2288
- * @param label The label to give to the logged expression.
2289
- */
2290
- function log(value = ({
2291
- context,
2292
- event
2293
- }) => ({
2294
- context,
2295
- event
2296
- }), label) {
2297
- function log(_) {
2298
- }
2299
- log.type = 'xstate.log';
2300
- log.value = value;
2301
- log.label = label;
2302
- log.resolve = resolve$4;
2303
- log.execute = execute$1;
2304
- return log;
2305
- }
2306
-
2307
- function createSpawner(actorContext, {
2308
- machine,
2309
- context
2310
- }, event, spawnedChildren) {
2311
- const spawn = (src, options = {}) => {
2312
- const {
2313
- systemId
2314
- } = options;
2315
- if (typeof src === 'string') {
2316
- const referenced = resolveReferencedActor(machine.implementations.actors[src]);
2317
- if (!referenced) {
2318
- throw new Error(`Actor logic '${src}' not implemented in machine '${machine.id}'`);
2319
- }
2320
- const input = 'input' in options ? options.input : referenced.input;
2321
-
2322
- // TODO: this should also receive `src`
2323
- const actor = createActor(referenced.src, {
2324
- id: options.id,
2325
- parent: actorContext.self,
2326
- input: typeof input === 'function' ? input({
2327
- context,
2328
- event,
2329
- self: actorContext.self
2330
- }) : input,
2331
- systemId
2332
- });
2333
- spawnedChildren[actor.id] = actor;
2334
- return actor;
2335
- } else {
2336
- // TODO: this should also receive `src`
2337
- return createActor(src, {
2338
- id: options.id,
2339
- parent: actorContext.self,
2340
- input: options.input,
2341
- systemId
2342
- });
2343
- }
2344
- };
2345
- return (src, options) => {
2346
- const actorRef = spawn(src, options); // TODO: fix types
2347
- spawnedChildren[actorRef.id] = actorRef;
2348
- actorContext.defer(() => {
2349
- if (actorRef.status === ActorStatus.Stopped) {
2350
- return;
2351
- }
2352
- try {
2353
- actorRef.start?.();
2354
- } catch (err) {
2355
- actorContext.self.send(error(actorRef.id, err));
2356
- return;
2357
- }
2358
- });
2359
- return actorRef;
2360
- };
2361
- }
2362
-
2363
- function resolve$3(actorContext, state, actionArgs, {
2364
- assignment
2365
- }) {
2366
- if (!state.context) {
2367
- throw new Error('Cannot assign to undefined `context`. Ensure that `context` is defined in the machine config.');
2368
- }
2369
- const spawnedChildren = {};
2370
- const assignArgs = {
2371
- context: state.context,
2372
- event: actionArgs.event,
2373
- action: actionArgs.action,
2374
- spawn: createSpawner(actorContext, state, actionArgs.event, spawnedChildren),
2375
- self: actorContext?.self,
2376
- system: actorContext?.system
2377
- };
2378
- let partialUpdate = {};
2379
- if (typeof assignment === 'function') {
2380
- partialUpdate = assignment(assignArgs);
2381
- } else {
2382
- for (const key of Object.keys(assignment)) {
2383
- const propAssignment = assignment[key];
2384
- partialUpdate[key] = typeof propAssignment === 'function' ? propAssignment(assignArgs) : propAssignment;
2385
- }
2386
- }
2387
- const updatedContext = Object.assign({}, state.context, partialUpdate);
2388
- return [cloneState(state, {
2389
- context: updatedContext,
2390
- children: Object.keys(spawnedChildren).length ? {
2391
- ...state.children,
2392
- ...spawnedChildren
2393
- } : state.children
2394
- })];
2395
- }
2396
- /**
2397
- * Updates the current context of the machine.
2398
- *
2399
- * @param assignment An object that represents the partial context to update.
2400
- */
2401
- function assign(assignment) {
2402
- function assign(_) {
2403
- }
2404
- assign.type = 'xstate.assign';
2405
- assign.assignment = assignment;
2406
- assign.resolve = resolve$3;
2407
- return assign;
2408
- }
2409
-
2410
- function resolve$2(_, state, args, {
1416
+ function resolve(_, state, args, {
2411
1417
  event: eventOrExpr,
2412
1418
  id,
2413
1419
  delay
@@ -2446,117 +1452,17 @@ function execute(actorContext, params) {
2446
1452
  */
2447
1453
  function raise(eventOrExpr, options) {
2448
1454
  function raise(_) {
1455
+ {
1456
+ throw new Error(`This isn't supposed to be called`);
1457
+ }
2449
1458
  }
2450
1459
  raise.type = 'xstate.raise';
2451
1460
  raise.event = eventOrExpr;
2452
1461
  raise.id = options?.id;
2453
1462
  raise.delay = options?.delay;
2454
- raise.resolve = resolve$2;
1463
+ raise.resolve = resolve;
2455
1464
  raise.execute = execute;
2456
1465
  return raise;
2457
1466
  }
2458
1467
 
2459
- function resolve$1(_, state, actionArgs, {
2460
- branches
2461
- }) {
2462
- const matchedActions = branches.find(condition => {
2463
- return !condition.guard || evaluateGuard(condition.guard, state.context, actionArgs.event, state);
2464
- })?.actions;
2465
- return [state, undefined, toArray(matchedActions)];
2466
- }
2467
- function choose(branches) {
2468
- function choose(_) {
2469
- }
2470
- choose.type = 'xstate.choose';
2471
- choose.branches = branches;
2472
- choose.resolve = resolve$1;
2473
- return choose;
2474
- }
2475
-
2476
- function resolve(_, state, args, {
2477
- get
2478
- }) {
2479
- return [state, undefined, toArray(get({
2480
- context: args.context,
2481
- event: args.event
2482
- }))];
2483
- }
2484
- function pure(getActions) {
2485
- function pure(_) {
2486
- }
2487
- pure.type = 'xstate.pure';
2488
- pure.get = getActions;
2489
- pure.resolve = resolve;
2490
- return pure;
2491
- }
2492
-
2493
- /**
2494
- * Returns an event type that represents an implicit event that
2495
- * is sent after the specified `delay`.
2496
- *
2497
- * @param delayRef The delay in milliseconds
2498
- * @param id The state node ID where this event is handled
2499
- */
2500
- function after(delayRef, id) {
2501
- const idSuffix = id ? `#${id}` : '';
2502
- return `${ConstantPrefix.After}(${delayRef})${idSuffix}`;
2503
- }
2504
-
2505
- /**
2506
- * Returns an event that represents that a final state node
2507
- * has been reached in the parent state node.
2508
- *
2509
- * @param id The final state node's parent state node `id`
2510
- * @param output The data to pass into the event
2511
- */
2512
- function done(id, output) {
2513
- const type = `${ConstantPrefix.DoneState}.${id}`;
2514
- const eventObject = {
2515
- type,
2516
- output
2517
- };
2518
- eventObject.toString = () => type;
2519
- return eventObject;
2520
- }
2521
- function doneInvokeEventType(invokeId) {
2522
- return `${ConstantPrefix.DoneInvoke}.${invokeId}`;
2523
- }
2524
-
2525
- /**
2526
- * Returns an event that represents that an invoked service has terminated.
2527
- *
2528
- * An invoked service is terminated when it has reached a top-level final state node,
2529
- * but not when it is canceled.
2530
- *
2531
- * @param invokeId The invoked service ID
2532
- * @param output The data to pass into the event
2533
- */
2534
- function doneInvoke(invokeId, output) {
2535
- const type = doneInvokeEventType(invokeId);
2536
- const eventObject = {
2537
- type,
2538
- output
2539
- };
2540
- eventObject.toString = () => type;
2541
- return eventObject;
2542
- }
2543
- function errorEventType(id) {
2544
- return `${ConstantPrefix.ErrorPlatform}.${id}`;
2545
- }
2546
- function error(id, data) {
2547
- const type = errorEventType(id);
2548
- const eventObject = {
2549
- type,
2550
- data
2551
- };
2552
- eventObject.toString = () => type;
2553
- return eventObject;
2554
- }
2555
- function createInitEvent(input) {
2556
- return {
2557
- type: XSTATE_INIT,
2558
- input
2559
- };
2560
- }
2561
-
2562
- export { stateIn as $, isStateId as A, getStateNodeByPath as B, getPersistedState as C, resolveReferencedActor as D, createActor as E, matchesState as F, Actor as G, ActorStatus as H, doneInvoke as I, interpret as J, InterpreterStatus as K, cancel as L, choose as M, NULL_EVENT as N, log as O, pure as P, raise as Q, forwardTo as R, STATE_DELIMITER as S, sendParent as T, sendTo as U, stop as V, pathToStateValue as W, toObserver as X, and as Y, not as Z, or as _, toTransitionConfigArray as a, ConstantPrefix as a0, SpecialTargets as a1, XSTATE_INIT as a2, isPromiseLike as a3, error as a4, XSTATE_STOP as a5, symbolObservable as a6, constantPrefixes as a7, after as a8, done as a9, doneInvokeEventType as aa, errorEventType as ab, escalate as ac, formatTransition as b, memo as c, createInvokeId as d, evaluateGuard as e, formatTransitions as f, getDelayedTransitions as g, formatInitialTransition as h, getCandidates as i, getConfiguration as j, getStateNodes as k, isInFinalState as l, mapValues as m, State as n, isErrorEvent as o, cloneState as p, macrostep as q, resolveStateValue as r, transitionNode as s, toArray as t, getInitialConfiguration as u, resolveActionsAndContext as v, assign as w, createInitEvent as x, microstep as y, isAtomicStateNode as z };
1468
+ export { raise as A, stop as B, State as S, formatTransition as a, formatInitialTransition as b, getCandidates as c, getConfiguration as d, evaluateGuard as e, formatTransitions as f, getDelayedTransitions as g, getStateNodes as h, isInFinalState as i, cloneState as j, macrostep as k, getInitialConfiguration as l, memo as m, resolveActionsAndContext as n, microstep as o, isAtomicStateNode as p, isStateId as q, resolveStateValue as r, getStateNodeByPath as s, transitionNode as t, getPersistedState as u, and as v, not as w, or as x, stateIn as y, cancel as z };