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,8 +1,409 @@
1
- import { a6 as symbolObservable, H as ActorStatus, E as createActor } from '../../dist/actions-020463e9.esm.js';
2
- import { d as fromTransition } from '../../dist/promise-5b07c38e.esm.js';
3
- export { f as fromCallback, a as fromEventObservable, b as fromObservable, c as fromPromise, d as fromTransition } from '../../dist/promise-5b07c38e.esm.js';
1
+ import { X as XSTATE_INIT, j as isPromiseLike, k as createDoneActorEvent, l as createErrorActorEvent, n as XSTATE_STOP, s as symbolObservable, f as ActorStatus, d as createActor } from '../../dist/interpreter-b5203bcb.esm.js';
4
2
  import '../../dev/dist/xstate-dev.esm.js';
5
3
 
4
+ /**
5
+ * Returns actor logic from a transition function and its initial state.
6
+ *
7
+ * A transition function is a function that takes the current state and an event and returns the next state.
8
+ *
9
+ * @param transition The transition function that returns the next state given the current state and event.
10
+ * @param initialState The initial state of the transition function.
11
+ * @returns Actor logic
12
+ */
13
+ function fromTransition(transition, initialState) {
14
+ return {
15
+ config: transition,
16
+ transition: (state, event, actorContext) => {
17
+ return transition(state, event, actorContext);
18
+ },
19
+ getInitialState: (_, input) => {
20
+ return typeof initialState === 'function' ? initialState({
21
+ input
22
+ }) : initialState;
23
+ },
24
+ getSnapshot: state => state,
25
+ getPersistedState: state => state,
26
+ restoreState: state => state
27
+ };
28
+ }
29
+
30
+ function fromCallback(invokeCallback) {
31
+ return {
32
+ config: invokeCallback,
33
+ start: (_state, {
34
+ self
35
+ }) => {
36
+ self.send({
37
+ type: XSTATE_INIT
38
+ });
39
+ },
40
+ transition: (state, event, {
41
+ self,
42
+ id,
43
+ system
44
+ }) => {
45
+ if (event.type === XSTATE_INIT) {
46
+ const sendBack = eventForParent => {
47
+ if (state.canceled) {
48
+ return;
49
+ }
50
+ self._parent?.send(eventForParent);
51
+ };
52
+ const receive = newListener => {
53
+ state.receivers.add(newListener);
54
+ };
55
+ state.dispose = invokeCallback({
56
+ input: state.input,
57
+ system,
58
+ self: self,
59
+ sendBack,
60
+ receive
61
+ });
62
+ if (isPromiseLike(state.dispose)) {
63
+ state.dispose.then(resolved => {
64
+ self._parent?.send(createDoneActorEvent(id, resolved));
65
+ state.canceled = true;
66
+ }, errorData => {
67
+ state.canceled = true;
68
+ self._parent?.send(createErrorActorEvent(id, errorData));
69
+ });
70
+ }
71
+ return state;
72
+ }
73
+ if (event.type === XSTATE_STOP) {
74
+ state.canceled = true;
75
+ if (typeof state.dispose === 'function') {
76
+ state.dispose();
77
+ }
78
+ return state;
79
+ }
80
+ state.receivers.forEach(receiver => receiver(event));
81
+ return state;
82
+ },
83
+ getInitialState: (_, input) => {
84
+ return {
85
+ canceled: false,
86
+ receivers: new Set(),
87
+ dispose: undefined,
88
+ input
89
+ };
90
+ },
91
+ getSnapshot: () => undefined,
92
+ getPersistedState: ({
93
+ input,
94
+ canceled
95
+ }) => ({
96
+ input,
97
+ canceled
98
+ })
99
+ };
100
+ }
101
+
102
+ function fromObservable(observableCreator) {
103
+ const nextEventType = '$$xstate.next';
104
+ const errorEventType = '$$xstate.error';
105
+ const completeEventType = '$$xstate.complete';
106
+ return {
107
+ config: observableCreator,
108
+ transition: (state, event, {
109
+ self,
110
+ id,
111
+ defer
112
+ }) => {
113
+ if (state.status !== 'active') {
114
+ return state;
115
+ }
116
+ switch (event.type) {
117
+ case nextEventType:
118
+ // match the exact timing of events sent by machines
119
+ // send actions are not executed immediately
120
+ defer(() => {
121
+ self._parent?.send({
122
+ type: `xstate.snapshot.${id}`,
123
+ data: event.data
124
+ });
125
+ });
126
+ return {
127
+ ...state,
128
+ data: event.data
129
+ };
130
+ case errorEventType:
131
+ return {
132
+ ...state,
133
+ status: 'error',
134
+ input: undefined,
135
+ data: event.data,
136
+ // TODO: if we keep this as `data` we should reflect this in the type
137
+ subscription: undefined
138
+ };
139
+ case completeEventType:
140
+ return {
141
+ ...state,
142
+ status: 'done',
143
+ input: undefined,
144
+ subscription: undefined
145
+ };
146
+ case XSTATE_STOP:
147
+ state.subscription.unsubscribe();
148
+ return {
149
+ ...state,
150
+ status: 'canceled',
151
+ input: undefined,
152
+ subscription: undefined
153
+ };
154
+ default:
155
+ return state;
156
+ }
157
+ },
158
+ getInitialState: (_, input) => {
159
+ return {
160
+ subscription: undefined,
161
+ status: 'active',
162
+ data: undefined,
163
+ input
164
+ };
165
+ },
166
+ start: (state, {
167
+ self,
168
+ system
169
+ }) => {
170
+ if (state.status === 'done') {
171
+ // Do not restart a completed observable
172
+ return;
173
+ }
174
+ state.subscription = observableCreator({
175
+ input: state.input,
176
+ system,
177
+ self
178
+ }).subscribe({
179
+ next: value => {
180
+ self.send({
181
+ type: nextEventType,
182
+ data: value
183
+ });
184
+ },
185
+ error: err => {
186
+ self.send({
187
+ type: errorEventType,
188
+ data: err
189
+ });
190
+ },
191
+ complete: () => {
192
+ self.send({
193
+ type: completeEventType
194
+ });
195
+ }
196
+ });
197
+ },
198
+ getSnapshot: state => state.data,
199
+ getPersistedState: ({
200
+ status,
201
+ data,
202
+ input
203
+ }) => ({
204
+ status,
205
+ data,
206
+ input
207
+ }),
208
+ getStatus: state => state,
209
+ restoreState: state => ({
210
+ ...state,
211
+ subscription: undefined
212
+ })
213
+ };
214
+ }
215
+
216
+ /**
217
+ * Creates event observable logic that listens to an observable
218
+ * that delivers event objects.
219
+ *
220
+ *
221
+ * @param lazyObservable A function that creates an observable
222
+ * @returns Event observable logic
223
+ */
224
+
225
+ function fromEventObservable(lazyObservable) {
226
+ const errorEventType = '$$xstate.error';
227
+ const completeEventType = '$$xstate.complete';
228
+
229
+ // TODO: event types
230
+ return {
231
+ config: lazyObservable,
232
+ transition: (state, event) => {
233
+ if (state.status !== 'active') {
234
+ return state;
235
+ }
236
+ switch (event.type) {
237
+ case errorEventType:
238
+ return {
239
+ ...state,
240
+ status: 'error',
241
+ input: undefined,
242
+ data: event.data,
243
+ // TODO: if we keep this as `data` we should reflect this in the type
244
+ subscription: undefined
245
+ };
246
+ case completeEventType:
247
+ return {
248
+ ...state,
249
+ status: 'done',
250
+ input: undefined,
251
+ subscription: undefined
252
+ };
253
+ case XSTATE_STOP:
254
+ state.subscription.unsubscribe();
255
+ return {
256
+ ...state,
257
+ status: 'canceled',
258
+ input: undefined,
259
+ subscription: undefined
260
+ };
261
+ default:
262
+ return state;
263
+ }
264
+ },
265
+ getInitialState: (_, input) => {
266
+ return {
267
+ subscription: undefined,
268
+ status: 'active',
269
+ data: undefined,
270
+ input
271
+ };
272
+ },
273
+ start: (state, {
274
+ self,
275
+ system
276
+ }) => {
277
+ if (state.status === 'done') {
278
+ // Do not restart a completed observable
279
+ return;
280
+ }
281
+ state.subscription = lazyObservable({
282
+ input: state.input,
283
+ system,
284
+ self
285
+ }).subscribe({
286
+ next: value => {
287
+ self._parent?.send(value);
288
+ },
289
+ error: err => {
290
+ self.send({
291
+ type: errorEventType,
292
+ data: err
293
+ });
294
+ },
295
+ complete: () => {
296
+ self.send({
297
+ type: completeEventType
298
+ });
299
+ }
300
+ });
301
+ },
302
+ getSnapshot: _ => undefined,
303
+ getPersistedState: ({
304
+ status,
305
+ data,
306
+ input
307
+ }) => ({
308
+ status,
309
+ data,
310
+ input
311
+ }),
312
+ getStatus: state => state,
313
+ restoreState: state => ({
314
+ ...state,
315
+ subscription: undefined
316
+ })
317
+ };
318
+ }
319
+
320
+ const resolveEventType = '$$xstate.resolve';
321
+ const rejectEventType = '$$xstate.reject';
322
+ function fromPromise(
323
+ // TODO: add types
324
+ promiseCreator) {
325
+ // TODO: add event types
326
+ const logic = {
327
+ config: promiseCreator,
328
+ transition: (state, event) => {
329
+ if (state.status !== 'active') {
330
+ return state;
331
+ }
332
+ switch (event.type) {
333
+ case resolveEventType:
334
+ return {
335
+ ...state,
336
+ status: 'done',
337
+ data: event.data,
338
+ input: undefined
339
+ };
340
+ case rejectEventType:
341
+ return {
342
+ ...state,
343
+ status: 'error',
344
+ data: event.data,
345
+ // TODO: if we keep this as `data` we should reflect this in the type
346
+ input: undefined
347
+ };
348
+ case XSTATE_STOP:
349
+ return {
350
+ ...state,
351
+ status: 'canceled',
352
+ input: undefined
353
+ };
354
+ default:
355
+ return state;
356
+ }
357
+ },
358
+ start: (state, {
359
+ self,
360
+ system
361
+ }) => {
362
+ // TODO: determine how to allow customizing this so that promises
363
+ // can be restarted if necessary
364
+ if (state.status !== 'active') {
365
+ return;
366
+ }
367
+ const resolvedPromise = Promise.resolve(promiseCreator({
368
+ input: state.input,
369
+ system,
370
+ self
371
+ }));
372
+ resolvedPromise.then(response => {
373
+ // TODO: remove this condition once dead letter queue lands
374
+ if (self._state.status !== 'active') {
375
+ return;
376
+ }
377
+ self.send({
378
+ type: resolveEventType,
379
+ data: response
380
+ });
381
+ }, errorData => {
382
+ // TODO: remove this condition once dead letter queue lands
383
+ if (self._state.status !== 'active') {
384
+ return;
385
+ }
386
+ self.send({
387
+ type: rejectEventType,
388
+ data: errorData
389
+ });
390
+ });
391
+ },
392
+ getInitialState: (_, input) => {
393
+ return {
394
+ status: 'active',
395
+ data: undefined,
396
+ input
397
+ };
398
+ },
399
+ getSnapshot: state => state.data,
400
+ getStatus: state => state,
401
+ getPersistedState: state => state,
402
+ restoreState: state => state
403
+ };
404
+ return logic;
405
+ }
406
+
6
407
  function isActorRef(item) {
7
408
  return !!item && typeof item === 'object' && typeof item.send === 'function';
8
409
  }
@@ -32,4 +433,4 @@ function createEmptyActor() {
32
433
  return createActor(emptyLogic);
33
434
  }
34
435
 
35
- export { createEmptyActor, isActorRef, toActorRef };
436
+ export { createEmptyActor, fromCallback, fromEventObservable, fromObservable, fromPromise, fromTransition, isActorRef, toActorRef };
@@ -1,2 +1,2 @@
1
- !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).XStateActors={})}(this,(function(t){"use strict";class e{constructor(t){this._process=t,this._active=!1,this._current=null,this._last=null}start(){this._active=!0,this.flush()}clear(){this._current&&(this._current.next=null,this._last=this._current)}prepend(t){this._current?this._current={value:t,next:this._current}:this.enqueue(t)}enqueue(t){const e={value:t,next:null};if(this._current)return this._last.next=e,void(this._last=e);this._current=e,this._last=e,this._active&&this.flush()}flush(){for(;this._current;){const t=this._current;this._process(t.value),t===this._current&&(this._current=this._current.next)}this._last=null}}let s=function(t){return t.After="xstate.after",t.DoneState="done.state",t.DoneInvoke="done.invoke",t.ErrorExecution="error.execution",t.ErrorCommunication="error.communication",t.ErrorPlatform="error.platform",t.ErrorCustom="xstate.error",t}({});const i="xstate.init",r="xstate.stop";function n(t,e){const i=function(t){return`${s.DoneInvoke}.${t}`}(t),r={type:i,output:e,toString:()=>i};return r}function o(t,e){const i=function(t){return`${s.ErrorPlatform}.${t}`}(t),r={type:i,data:e,toString:()=>i};return r}function a(){const t="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:window;if(t.__xstate__)return t.__xstate__}const c=t=>{const e=a();e&&e.register(t)};function u(t){setTimeout((()=>{throw t}))}const d="function"==typeof Symbol&&Symbol.observable||"@@observable";let h=function(t){return t[t.NotStarted=0]="NotStarted",t[t.Running=1]="Running",t[t.Stopped=2]="Stopped",t}({});const p={deferEvents:!0,clock:{setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t)},logger:console.log.bind(console),devTools:!1};class l{constructor(t,s){this.logic=t,this._state=void 0,this.clock=void 0,this.options=void 0,this.id=void 0,this.mailbox=new e(this._process.bind(this)),this.delayedEventsMap={},this.observers=new Set,this.logger=void 0,this.status=h.NotStarted,this._parent=void 0,this.ref=void 0,this._actorContext=void 0,this._systemId=void 0,this.sessionId=void 0,this.system=void 0,this._doneEvent=void 0,this.src=void 0,this._deferred=[];const i={...p,...s},{clock:r,logger:n,parent:o,id:a,systemId:c}=i;this.system=o?.system??function(){let t=0;const e=new Map,s=new Map,i=new WeakMap;return{_bookId:()=>"x:"+t++,_register:(t,s)=>(e.set(t,s),t),_unregister:t=>{e.delete(t.sessionId);const r=i.get(t);void 0!==r&&(s.delete(r),i.delete(t))},get:t=>s.get(t),_set:(t,e)=>{const r=s.get(t);if(r&&r!==e)throw new Error(`Actor with system ID '${t}' already exists.`);s.set(t,e),i.set(e,t)}}}(),c&&(this._systemId=c,this.system._set(c,this)),this.sessionId=this.system._bookId(),this.id=a??this.sessionId,this.logger=n,this.clock=r,this._parent=o,this.options=i,this.src=i.src,this.ref=this,this._actorContext={self:this,id:this.id,sessionId:this.sessionId,logger:this.logger,defer:t=>{this._deferred.push(t)},system:this.system,stopChild:t=>{if(t._parent!==this)throw new Error(`Cannot stop child actor ${t.id} of ${this.id} because it is not a child`);t._stop()}},this.send=this.send.bind(this),this._initState()}_initState(){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)}update(t){this._state=t;const e=this.getSnapshot();let s;for(;s=this._deferred.shift();)s();for(const t of this.observers)try{t.next?.(e)}catch(t){u(t)}const i=this.logic.getStatus?.(t);switch(i?.status){case"done":this._stopProcedure(),this._complete(),this._doneEvent=n(this.id,i.data),this._parent?.send(this._doneEvent);break;case"error":this._stopProcedure(),this._error(i.data),this._parent?.send(o(this.id,i.data))}}subscribe(t,e,s){const i=function(t,e,s){const i="object"==typeof t,r=i?t:void 0;return{next:(i?t.next:t)?.bind(r),error:(i?t.error:e)?.bind(r),complete:(i?t.complete:s)?.bind(r)}}(t,e,s);if(this.status!==h.Stopped)this.observers.add(i);else try{i.complete?.()}catch(t){u(t)}return{unsubscribe:()=>{this.observers.delete(i)}}}start(){if(this.status===h.Running)return this;this.system._register(this.sessionId,this),this._systemId&&this.system._set(this._systemId,this),this.status=h.Running;const t=this.logic.getStatus?.(this._state);switch(t?.status){case"done":this.update(this._state);case"error":return this}if(this.logic.start)try{this.logic.start(this._state,this._actorContext)}catch(t){return this._stopProcedure(),this._error(t),this._parent?.send(o(this.id,t)),this}return this.update(this._state),this.options.devTools&&this.attachDevTools(),this.mailbox.start(),this}_process(t){let e,s;try{e=this.logic.transition(this._state,t,this._actorContext)}catch(t){s={err:t}}if(s){const{err:t}=s;return this._stopProcedure(),this._error(t),void this._parent?.send(o(this.id,t))}this.update(e),t.type===r&&(this._stopProcedure(),this._complete())}_stop(){return this.status===h.Stopped?this:(this.mailbox.clear(),this.status===h.NotStarted?(this.status=h.Stopped,this):(this.mailbox.enqueue({type:r}),this))}stop(){if(this._parent)throw new Error("A non-root actor cannot be stopped directly.");return this._stop()}_complete(){for(const t of this.observers)try{t.complete?.()}catch(t){u(t)}this.observers.clear()}_error(t){if(!this.observers.size)return void(this._parent||u(t));let e=!1;for(const s of this.observers){const i=s.error;e||=!i;try{i?.(t)}catch(t){u(t)}}this.observers.clear(),e&&u(t)}_stopProcedure(){if(this.status!==h.Running)return this;for(const t of Object.keys(this.delayedEventsMap))this.clock.clearTimeout(this.delayedEventsMap[t]);return this.mailbox.clear(),this.mailbox=new e(this._process.bind(this)),this.status=h.Stopped,this.system._unregister(this),this}send(t){if("string"==typeof t)throw new Error(`Only event objects may be sent to actors; use .send({ type: "${t}" }) instead`);if(this.status!==h.Stopped){if(this.status!==h.Running&&!this.options.deferEvents)throw new Error(`Event "${t.type}" was sent to uninitialized actor "${this.id}". Make sure .start() is called for this actor, or set { deferEvents: true } in the actor options.\nEvent: ${JSON.stringify(t)}`);this.mailbox.enqueue(t)}}delaySend({event:t,id:e,delay:s,to:i}){const r=this.clock.setTimeout((()=>{i?i.send(t):this.send(t)}),s);e&&(this.delayedEventsMap[e]=r)}cancel(t){this.clock.clearTimeout(this.delayedEventsMap[t]),delete this.delayedEventsMap[t]}attachDevTools(){const{devTools:t}=this.options;if(t){("function"==typeof t?t:c)(this)}}toJSON(){return{id:this.id}}getPersistedState(){return this.logic.getPersistedState?.(this._state)}[d](){return this}getSnapshot(){return this.logic.getSnapshot?this.logic.getSnapshot(this._state):this._state}}function f(t,e){return{config:t,transition:(e,s,i)=>t(e,s,i),getInitialState:(t,s)=>"function"==typeof e?e({input:s}):e,getSnapshot:t=>t,getPersistedState:t=>t,restoreState:t=>t}}const _="$$xstate.resolve",v="$$xstate.reject";const y=f((t=>{}),void 0);t.createEmptyActor=function(){return new l(y,t);var t},t.fromCallback=function(t){return{config:t,start:(t,{self:e})=>{e.send({type:i})},transition:(e,s,{self:a,id:c,system:u})=>{if(s.type===i){const s=t=>{e.canceled||a._parent?.send(t)},i=t=>{e.receivers.add(t)};return e.dispose=t({input:e.input,system:u,self:a,sendBack:s,receive:i}),((d=e.dispose)instanceof Promise||null!==d&&("function"==typeof d||"object"==typeof d)&&"function"==typeof d.then)&&e.dispose.then((t=>{a._parent?.send(n(c,t)),e.canceled=!0}),(t=>{e.canceled=!0,a._parent?.send(o(c,t))})),e}var d;return s.type===r?(e.canceled=!0,"function"==typeof e.dispose&&e.dispose(),e):(e.receivers.forEach((t=>t(s))),e)},getInitialState:(t,e)=>({canceled:!1,receivers:new Set,dispose:void 0,input:e}),getSnapshot:()=>{},getPersistedState:({input:t,canceled:e})=>({input:t,canceled:e})}},t.fromEventObservable=function(t){const e="$$xstate.error",s="$$xstate.complete";return{config:t,transition:(t,i)=>{if("active"!==t.status)return t;switch(i.type){case e:return{...t,status:"error",input:void 0,data:i.data,subscription:void 0};case s:return{...t,status:"done",input:void 0,subscription:void 0};case r:return t.subscription.unsubscribe(),{...t,status:"canceled",input:void 0,subscription:void 0};default:return t}},getInitialState:(t,e)=>({subscription:void 0,status:"active",data:void 0,input:e}),start:(i,{self:r,system:n})=>{"done"!==i.status&&(i.subscription=t({input:i.input,system:n,self:r}).subscribe({next:t=>{r._parent?.send(t)},error:t=>{r.send({type:e,data:t})},complete:()=>{r.send({type:s})}}))},getSnapshot:t=>{},getPersistedState:({status:t,data:e,input:s})=>({status:t,data:e,input:s}),getStatus:t=>t,restoreState:t=>({...t,subscription:void 0})}},t.fromObservable=function(t){const e="$$xstate.next",s="$$xstate.error",i="$$xstate.complete";return{config:t,transition:(t,n,{self:o,id:a,defer:c})=>{if("active"!==t.status)return t;switch(n.type){case e:return c((()=>{o._parent?.send({type:`xstate.snapshot.${a}`,data:n.data})})),{...t,data:n.data};case s:return{...t,status:"error",input:void 0,data:n.data,subscription:void 0};case i:return{...t,status:"done",input:void 0,subscription:void 0};case r:return t.subscription.unsubscribe(),{...t,status:"canceled",input:void 0,subscription:void 0};default:return t}},getInitialState:(t,e)=>({subscription:void 0,status:"active",data:void 0,input:e}),start:(r,{self:n,system:o})=>{"done"!==r.status&&(r.subscription=t({input:r.input,system:o,self:n}).subscribe({next:t=>{n.send({type:e,data:t})},error:t=>{n.send({type:s,data:t})},complete:()=>{n.send({type:i})}}))},getSnapshot:t=>t.data,getPersistedState:({status:t,data:e,input:s})=>({status:t,data:e,input:s}),getStatus:t=>t,restoreState:t=>({...t,subscription:void 0})}},t.fromPromise=function(t){return{config:t,transition:(t,e)=>{if("active"!==t.status)return t;switch(e.type){case _:return{...t,status:"done",data:e.data,input:void 0};case v:return{...t,status:"error",data:e.data,input:void 0};case r:return{...t,status:"canceled",input:void 0};default:return t}},start:(e,{self:s,system:i})=>{if("active"!==e.status)return;Promise.resolve(t({input:e.input,system:i,self:s})).then((t=>{"active"===s._state.status&&s.send({type:_,data:t})}),(t=>{"active"===s._state.status&&s.send({type:v,data:t})}))},getInitialState:(t,e)=>({status:"active",data:void 0,input:e}),getSnapshot:t=>t.data,getStatus:t=>t,getPersistedState:t=>t,restoreState:t=>t}},t.fromTransition=f,t.isActorRef=function(t){return!!t&&"object"==typeof t&&"function"==typeof t.send},t.toActorRef=function(t){return{subscribe:()=>({unsubscribe:()=>{}}),id:"anonymous",sessionId:"",getSnapshot:()=>{},[d]:function(){return this},status:h.Running,stop:()=>{},...t}},Object.defineProperty(t,"__esModule",{value:!0})}));
1
+ !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).XStateActors={})}(this,(function(t){"use strict";class e{constructor(t){this._process=t,this._active=!1,this._current=null,this._last=null}start(){this._active=!0,this.flush()}clear(){this._current&&(this._current.next=null,this._last=this._current)}prepend(t){this._current?this._current={value:t,next:this._current}:this.enqueue(t)}enqueue(t){const e={value:t,next:null};if(this._current)return this._last.next=e,void(this._last=e);this._current=e,this._last=e,this._active&&this.flush()}flush(){for(;this._current;){const t=this._current;this._process(t.value),t===this._current&&(this._current=this._current.next)}this._last=null}}const s="xstate.init",i="xstate.stop";function n(t,e){return{type:`xstate.done.actor.${t}`,output:e}}function o(t,e){return{type:`xstate.error.actor.${t}`,data:e}}function r(){const t="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:window;if(t.__xstate__)return t.__xstate__}const a=t=>{const e=r();e&&e.register(t)};function c(t){setTimeout((()=>{throw t}))}const d="function"==typeof Symbol&&Symbol.observable||"@@observable";let u=function(t){return t[t.NotStarted=0]="NotStarted",t[t.Running=1]="Running",t[t.Stopped=2]="Stopped",t}({});const h={deferEvents:!0,clock:{setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t)},logger:console.log.bind(console),devTools:!1};class p{constructor(t,s){this.logic=t,this._state=void 0,this.clock=void 0,this.options=void 0,this.id=void 0,this.mailbox=new e(this._process.bind(this)),this.delayedEventsMap={},this.observers=new Set,this.logger=void 0,this.status=u.NotStarted,this._parent=void 0,this.ref=void 0,this._actorContext=void 0,this._systemId=void 0,this.sessionId=void 0,this.system=void 0,this._doneEvent=void 0,this.src=void 0,this._deferred=[];const i={...h,...s},{clock:n,logger:o,parent:r,id:a,systemId:c}=i;this.system=r?.system??function(){let t=0;const e=new Map,s=new Map,i=new WeakMap;return{_bookId:()=>"x:"+t++,_register:(t,s)=>(e.set(t,s),t),_unregister:t=>{e.delete(t.sessionId);const n=i.get(t);void 0!==n&&(s.delete(n),i.delete(t))},get:t=>s.get(t),_set:(t,e)=>{const n=s.get(t);if(n&&n!==e)throw new Error(`Actor with system ID '${t}' already exists.`);s.set(t,e),i.set(e,t)}}}(),c&&(this._systemId=c,this.system._set(c,this)),this.sessionId=this.system._bookId(),this.id=a??this.sessionId,this.logger=o,this.clock=n,this._parent=r,this.options=i,this.src=i.src,this.ref=this,this._actorContext={self:this,id:this.id,sessionId:this.sessionId,logger:this.logger,defer:t=>{this._deferred.push(t)},system:this.system,stopChild:t=>{if(t._parent!==this)throw new Error(`Cannot stop child actor ${t.id} of ${this.id} because it is not a child`);t._stop()}},this.send=this.send.bind(this),this._initState()}_initState(){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)}update(t){this._state=t;const e=this.getSnapshot();let s;for(;s=this._deferred.shift();)s();for(const t of this.observers)try{t.next?.(e)}catch(t){c(t)}const i=this.logic.getStatus?.(t);switch(i?.status){case"done":this._stopProcedure(),this._complete(),this._doneEvent=n(this.id,i.data),this._parent?.send(this._doneEvent);break;case"error":this._stopProcedure(),this._error(i.data),this._parent?.send(o(this.id,i.data))}}subscribe(t,e,s){const i=function(t,e,s){const i="object"==typeof t,n=i?t:void 0;return{next:(i?t.next:t)?.bind(n),error:(i?t.error:e)?.bind(n),complete:(i?t.complete:s)?.bind(n)}}(t,e,s);if(this.status!==u.Stopped)this.observers.add(i);else try{i.complete?.()}catch(t){c(t)}return{unsubscribe:()=>{this.observers.delete(i)}}}start(){if(this.status===u.Running)return this;this.system._register(this.sessionId,this),this._systemId&&this.system._set(this._systemId,this),this.status=u.Running;const t=this.logic.getStatus?.(this._state);switch(t?.status){case"done":this.update(this._state);case"error":return this}if(this.logic.start)try{this.logic.start(this._state,this._actorContext)}catch(t){return this._stopProcedure(),this._error(t),this._parent?.send(o(this.id,t)),this}return this.update(this._state),this.options.devTools&&this.attachDevTools(),this.mailbox.start(),this}_process(t){let e,s;try{e=this.logic.transition(this._state,t,this._actorContext)}catch(t){s={err:t}}if(s){const{err:t}=s;return this._stopProcedure(),this._error(t),void this._parent?.send(o(this.id,t))}this.update(e),t.type===i&&(this._stopProcedure(),this._complete())}_stop(){return this.status===u.Stopped?this:(this.mailbox.clear(),this.status===u.NotStarted?(this.status=u.Stopped,this):(this.mailbox.enqueue({type:i}),this))}stop(){if(this._parent)throw new Error("A non-root actor cannot be stopped directly.");return this._stop()}_complete(){for(const t of this.observers)try{t.complete?.()}catch(t){c(t)}this.observers.clear()}_error(t){if(!this.observers.size)return void(this._parent||c(t));let e=!1;for(const s of this.observers){const i=s.error;e||=!i;try{i?.(t)}catch(t){c(t)}}this.observers.clear(),e&&c(t)}_stopProcedure(){if(this.status!==u.Running)return this;for(const t of Object.keys(this.delayedEventsMap))this.clock.clearTimeout(this.delayedEventsMap[t]);return this.mailbox.clear(),this.mailbox=new e(this._process.bind(this)),this.status=u.Stopped,this.system._unregister(this),this}send(t){if("string"==typeof t)throw new Error(`Only event objects may be sent to actors; use .send({ type: "${t}" }) instead`);if(this.status!==u.Stopped){if(this.status!==u.Running&&!this.options.deferEvents)throw new Error(`Event "${t.type}" was sent to uninitialized actor "${this.id}". Make sure .start() is called for this actor, or set { deferEvents: true } in the actor options.\nEvent: ${JSON.stringify(t)}`);this.mailbox.enqueue(t)}}delaySend({event:t,id:e,delay:s,to:i}){const n=this.clock.setTimeout((()=>{i?i.send(t):this.send(t)}),s);e&&(this.delayedEventsMap[e]=n)}cancel(t){this.clock.clearTimeout(this.delayedEventsMap[t]),delete this.delayedEventsMap[t]}attachDevTools(){const{devTools:t}=this.options;if(t){("function"==typeof t?t:a)(this)}}toJSON(){return{id:this.id}}getPersistedState(){return this.logic.getPersistedState?.(this._state)}[d](){return this}getSnapshot(){return this.logic.getSnapshot?this.logic.getSnapshot(this._state):this._state}}function l(t,e){return{config:t,transition:(e,s,i)=>t(e,s,i),getInitialState:(t,s)=>"function"==typeof e?e({input:s}):e,getSnapshot:t=>t,getPersistedState:t=>t,restoreState:t=>t}}const f="$$xstate.resolve",_="$$xstate.reject";const v=l((t=>{}),void 0);t.createEmptyActor=function(){return new p(v,t);var t},t.fromCallback=function(t){return{config:t,start:(t,{self:e})=>{e.send({type:s})},transition:(e,r,{self:a,id:c,system:d})=>{if(r.type===s){const s=t=>{e.canceled||a._parent?.send(t)},i=t=>{e.receivers.add(t)};return e.dispose=t({input:e.input,system:d,self:a,sendBack:s,receive:i}),((u=e.dispose)instanceof Promise||null!==u&&("function"==typeof u||"object"==typeof u)&&"function"==typeof u.then)&&e.dispose.then((t=>{a._parent?.send(n(c,t)),e.canceled=!0}),(t=>{e.canceled=!0,a._parent?.send(o(c,t))})),e}var u;return r.type===i?(e.canceled=!0,"function"==typeof e.dispose&&e.dispose(),e):(e.receivers.forEach((t=>t(r))),e)},getInitialState:(t,e)=>({canceled:!1,receivers:new Set,dispose:void 0,input:e}),getSnapshot:()=>{},getPersistedState:({input:t,canceled:e})=>({input:t,canceled:e})}},t.fromEventObservable=function(t){const e="$$xstate.error",s="$$xstate.complete";return{config:t,transition:(t,n)=>{if("active"!==t.status)return t;switch(n.type){case e:return{...t,status:"error",input:void 0,data:n.data,subscription:void 0};case s:return{...t,status:"done",input:void 0,subscription:void 0};case i:return t.subscription.unsubscribe(),{...t,status:"canceled",input:void 0,subscription:void 0};default:return t}},getInitialState:(t,e)=>({subscription:void 0,status:"active",data:void 0,input:e}),start:(i,{self:n,system:o})=>{"done"!==i.status&&(i.subscription=t({input:i.input,system:o,self:n}).subscribe({next:t=>{n._parent?.send(t)},error:t=>{n.send({type:e,data:t})},complete:()=>{n.send({type:s})}}))},getSnapshot:t=>{},getPersistedState:({status:t,data:e,input:s})=>({status:t,data:e,input:s}),getStatus:t=>t,restoreState:t=>({...t,subscription:void 0})}},t.fromObservable=function(t){const e="$$xstate.next",s="$$xstate.error",n="$$xstate.complete";return{config:t,transition:(t,o,{self:r,id:a,defer:c})=>{if("active"!==t.status)return t;switch(o.type){case e:return c((()=>{r._parent?.send({type:`xstate.snapshot.${a}`,data:o.data})})),{...t,data:o.data};case s:return{...t,status:"error",input:void 0,data:o.data,subscription:void 0};case n:return{...t,status:"done",input:void 0,subscription:void 0};case i:return t.subscription.unsubscribe(),{...t,status:"canceled",input:void 0,subscription:void 0};default:return t}},getInitialState:(t,e)=>({subscription:void 0,status:"active",data:void 0,input:e}),start:(i,{self:o,system:r})=>{"done"!==i.status&&(i.subscription=t({input:i.input,system:r,self:o}).subscribe({next:t=>{o.send({type:e,data:t})},error:t=>{o.send({type:s,data:t})},complete:()=>{o.send({type:n})}}))},getSnapshot:t=>t.data,getPersistedState:({status:t,data:e,input:s})=>({status:t,data:e,input:s}),getStatus:t=>t,restoreState:t=>({...t,subscription:void 0})}},t.fromPromise=function(t){return{config:t,transition:(t,e)=>{if("active"!==t.status)return t;switch(e.type){case f:return{...t,status:"done",data:e.data,input:void 0};case _:return{...t,status:"error",data:e.data,input:void 0};case i:return{...t,status:"canceled",input:void 0};default:return t}},start:(e,{self:s,system:i})=>{if("active"!==e.status)return;Promise.resolve(t({input:e.input,system:i,self:s})).then((t=>{"active"===s._state.status&&s.send({type:f,data:t})}),(t=>{"active"===s._state.status&&s.send({type:_,data:t})}))},getInitialState:(t,e)=>({status:"active",data:void 0,input:e}),getSnapshot:t=>t.data,getStatus:t=>t,getPersistedState:t=>t,restoreState:t=>t}},t.fromTransition=l,t.isActorRef=function(t){return!!t&&"object"==typeof t&&"function"==typeof t.send},t.toActorRef=function(t){return{subscribe:()=>({unsubscribe:()=>{}}),id:"anonymous",sessionId:"",getSnapshot:()=>{},[d]:function(){return this},status:u.Running,stop:()=>{},...t}},Object.defineProperty(t,"__esModule",{value:!0})}));
2
2
  //# sourceMappingURL=xstate-actors.umd.min.js.map