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AAMgR,MAAK,QAAiB,OAAcnU,KAAKkS,KAAMhf,EAASkC,UACrE4K,MACGud,EAAO,IAAI1qB,IAkBjB,OAjBA,SAAS2qB,EAAcrD,EAAajoB,GAClC,IAAIqrB,EAAK/P,IAAI2M,GAAb,CAGAoD,EAAK1V,IAAIsS,GACT,IAAK,MAAMle,KAAOke,EAAa,CAC7B,MAAM/kB,EAAQ+kB,EAAYle,GAC1B,GAAI7G,GAA0B,kBAAVA,EAAoB,CACtC,GAAI,iBAAkBA,GAASA,EAAMsV,eAAiB,EAAA+S,EAAc,CAClEtD,EAAYle,GAAO/J,EAASkD,EAAMiG,IAClC,QACF,CACAmiB,EAAcpoB,EAAOlD,EACvB,CACF,CAXA,CAYF,CACAsrB,CAAcF,EAAiB7kB,QAASvG,GACjCorB,CACT,EA6CF,SAASI,EAAchqB,EAAQI,GAC7B,OAAO,IAAIuoB,EAAa3oB,EAAQI,EAClC,CAmEA,SAAS6pB,GAAM,QACbrB,EAAO,OACPjY,EAAM,QACN1F,EAAO,OACPsN,EAAM,OACN7O,IAEA,MAAO,CACLsgB,cAAehqB,GAAUgqB,EAAc,IAClChqB,EACH4oB,WACC,CACDjY,SACA1F,UACAsN,SACA7O,WAGN","sources":["webpack://nodalview/./node_modules/use-isomorphic-layout-effect/dist/use-isomorphic-layout-effect.browser.esm.js","webpack://nodalview/./node_modules/@xstate/react/dist/xstate-react.esm.js","webpack://nodalview/./node_modules/use-sync-external-store/cjs/use-sync-external-store-shim.production.min.js","webpack://nodalview/./node_modules/use-sync-external-store/cjs/use-sync-external-store-shim/with-selector.production.min.js","webpack://nodalview/./node_modules/use-sync-external-store/shim/index.js","webpack://nodalview/./node_modules/use-sync-external-store/shim/with-selector.js","webpack://nodalview/./node_modules/xstate/actors/dist/xstate-actors.esm.js","webpack://nodalview/./node_modules/xstate/dist/log-2a773d37.esm.js","webpack://nodalview/./node_modules/xstate/dev/dist/xstate-dev.esm.js","webpack://nodalview/./node_modules/xstate/dist/raise-c17ec2bc.esm.js","webpack://nodalview/./node_modules/xstate/dist/xstate.esm.js"],"sourcesContent":["import { useLayoutEffect } from 'react';\n\nvar index =  useLayoutEffect ;\n\nexport default index;\n","import * as React from 'react';\nimport { useEffect, useState, useCallback } from 'react';\nimport { useSyncExternalStore } from 'use-sync-external-store/shim';\nimport useIsomorphicLayoutEffect from 'use-isomorphic-layout-effect';\nimport { toObserver, createActor } from 'xstate';\nimport { useSyncExternalStoreWithSelector } from 'use-sync-external-store/shim/with-selector';\n\nconst forEachActor = (actorRef, callback) => {\n  callback(actorRef);\n  const children = actorRef.getSnapshot().children;\n  if (children) {\n    Object.values(children).forEach(child => {\n      forEachActor(child, callback);\n    });\n  }\n};\nfunction stopRootWithRehydration(actorRef) {\n  // persist snapshot here in a custom way allows us to persist inline actors and to preserve actor references\n  // we do it to avoid setState in useEffect when the effect gets \"reconnected\"\n  // this currently only happens in Strict Effects but it simulates the Offscreen aka Activity API\n  // it also just allows us to end up with a somewhat more predictable behavior for the users\n  const persistedSnapshots = [];\n  forEachActor(actorRef, ref => {\n    persistedSnapshots.push([ref, ref.getSnapshot()]);\n    // muting observers allow us to avoid `useSelector` from being notified about the stopped snapshot\n    // React reconnects its subscribers (from the useSyncExternalStore) on its own\n    // and userland subscibers should basically always do the same anyway\n    // as each subscription should have its own cleanup logic and that should be called each such reconnect\n    ref.observers = new Set();\n  });\n  const systemSnapshot = actorRef.system.getSnapshot?.();\n  actorRef.stop();\n  actorRef.system._snapshot = systemSnapshot;\n  persistedSnapshots.forEach(([ref, snapshot]) => {\n    ref._processingStatus = 0;\n    ref._snapshot = snapshot;\n  });\n}\n\nfunction useIdleActorRef(logic, options) {\n  let [[currentConfig, actorRef], setCurrent] = useState(() => {\n    const actorRef = createActor(logic, options);\n    return [logic.config, actorRef];\n  });\n  if (logic.config !== currentConfig) {\n    const newActorRef = createActor(logic, {\n      ...options,\n      snapshot: actorRef.getPersistedSnapshot({\n        __unsafeAllowInlineActors: true\n      })\n    });\n    setCurrent([logic.config, newActorRef]);\n    actorRef = newActorRef;\n  }\n\n  // TODO: consider using `useAsapEffect` that would do this in `useInsertionEffect` is that's available\n  useIsomorphicLayoutEffect(() => {\n    actorRef.logic.implementations = logic.implementations;\n  });\n  return actorRef;\n}\nfunction useActorRef(machine, options = {}, observerOrListener) {\n  const actorRef = useIdleActorRef(machine, options);\n  useEffect(() => {\n    if (!observerOrListener) {\n      return;\n    }\n    let sub = actorRef.subscribe(toObserver(observerOrListener));\n    return () => {\n      sub.unsubscribe();\n    };\n  }, [observerOrListener]);\n  useEffect(() => {\n    actorRef.start();\n    return () => {\n      stopRootWithRehydration(actorRef);\n    };\n  }, [actorRef]);\n  return actorRef;\n}\n\nfunction useActor(logic, options = {}) {\n  const actorRef = useIdleActorRef(logic, options);\n  const getSnapshot = useCallback(() => {\n    return actorRef.getSnapshot();\n  }, [actorRef]);\n  const subscribe = useCallback(handleStoreChange => {\n    const {\n      unsubscribe\n    } = actorRef.subscribe(handleStoreChange);\n    return unsubscribe;\n  }, [actorRef]);\n  const actorSnapshot = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n  useEffect(() => {\n    actorRef.start();\n    return () => {\n      stopRootWithRehydration(actorRef);\n    };\n  }, [actorRef]);\n  return [actorSnapshot, actorRef.send, actorRef];\n}\n\nfunction defaultCompare(a, b) {\n  return a === b;\n}\nfunction useSelector(actor, selector, compare = defaultCompare) {\n  const subscribe = useCallback(handleStoreChange => {\n    if (!actor) {\n      return () => {};\n    }\n    const {\n      unsubscribe\n    } = actor.subscribe(handleStoreChange);\n    return unsubscribe;\n  }, [actor]);\n  const boundGetSnapshot = useCallback(() => actor?.getSnapshot(), [actor]);\n  const selectedSnapshot = useSyncExternalStoreWithSelector(subscribe, boundGetSnapshot, boundGetSnapshot, selector, compare);\n  return selectedSnapshot;\n}\n\n// From https://github.com/reduxjs/react-redux/blob/720f0ba79236cdc3e1115f4ef9a7760a21784b48/src/utils/shallowEqual.ts\nfunction is(x, y) {\n  if (x === y) {\n    return x !== 0 || y !== 0 || 1 / x === 1 / y;\n  } else {\n    return x !== x && y !== y;\n  }\n}\nfunction shallowEqual(objA, objB) {\n  if (is(objA, objB)) return true;\n  if (typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null) {\n    return false;\n  }\n  const keysA = Object.keys(objA);\n  const keysB = Object.keys(objB);\n  if (keysA.length !== keysB.length) return false;\n  for (let i = 0; i < keysA.length; i++) {\n    if (!Object.prototype.hasOwnProperty.call(objB, keysA[i]) || !is(objA[keysA[i]], objB[keysA[i]])) {\n      return false;\n    }\n  }\n  return true;\n}\n\nfunction createActorContext(actorLogic, actorOptions) {\n  const ReactContext = /*#__PURE__*/React.createContext(null);\n  const OriginalProvider = ReactContext.Provider;\n  function Provider({\n    children,\n    logic: providedLogic = actorLogic,\n    machine,\n    options: providedOptions\n  }) {\n    if (machine) {\n      throw new Error(`The \"machine\" prop has been deprecated. Please use \"logic\" instead.`);\n    }\n    const actor = useActorRef(providedLogic, {\n      ...actorOptions,\n      ...providedOptions\n    });\n    return /*#__PURE__*/React.createElement(OriginalProvider, {\n      value: actor,\n      children\n    });\n  }\n\n  // TODO: add properties to actor ref to make more descriptive\n  Provider.displayName = `ActorProvider`;\n  function useContext() {\n    const actor = React.useContext(ReactContext);\n    if (!actor) {\n      throw new Error(`You used a hook from \"${Provider.displayName}\" but it's not inside a <${Provider.displayName}> component.`);\n    }\n    return actor;\n  }\n  function useSelector$1(selector, compare) {\n    const actor = useContext();\n    return useSelector(actor, selector, compare);\n  }\n  return {\n    Provider: Provider,\n    useActorRef: useContext,\n    useSelector: useSelector$1\n  };\n}\n\n/**\n * @alias useActor\n */\nfunction useMachine(machine, options = {}) {\n  return useActor(machine, options);\n}\n\nexport { createActorContext, shallowEqual, useActor, useActorRef, useMachine, useSelector };\n","/**\n * @license React\n * use-sync-external-store-shim.production.min.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n'use strict';var e=require(\"react\");function h(a,b){return a===b&&(0!==a||1/a===1/b)||a!==a&&b!==b}var k=\"function\"===typeof Object.is?Object.is:h,l=e.useState,m=e.useEffect,n=e.useLayoutEffect,p=e.useDebugValue;function q(a,b){var d=b(),f=l({inst:{value:d,getSnapshot:b}}),c=f[0].inst,g=f[1];n(function(){c.value=d;c.getSnapshot=b;r(c)&&g({inst:c})},[a,d,b]);m(function(){r(c)&&g({inst:c});return a(function(){r(c)&&g({inst:c})})},[a]);p(d);return d}\nfunction r(a){var b=a.getSnapshot;a=a.value;try{var d=b();return!k(a,d)}catch(f){return!0}}function t(a,b){return b()}var u=\"undefined\"===typeof window||\"undefined\"===typeof window.document||\"undefined\"===typeof window.document.createElement?t:q;exports.useSyncExternalStore=void 0!==e.useSyncExternalStore?e.useSyncExternalStore:u;\n","/**\n * @license React\n * use-sync-external-store-shim/with-selector.production.min.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n'use strict';var h=require(\"react\"),n=require(\"use-sync-external-store/shim\");function p(a,b){return a===b&&(0!==a||1/a===1/b)||a!==a&&b!==b}var q=\"function\"===typeof Object.is?Object.is:p,r=n.useSyncExternalStore,t=h.useRef,u=h.useEffect,v=h.useMemo,w=h.useDebugValue;\nexports.useSyncExternalStoreWithSelector=function(a,b,e,l,g){var c=t(null);if(null===c.current){var f={hasValue:!1,value:null};c.current=f}else f=c.current;c=v(function(){function a(a){if(!c){c=!0;d=a;a=l(a);if(void 0!==g&&f.hasValue){var b=f.value;if(g(b,a))return k=b}return k=a}b=k;if(q(d,a))return b;var e=l(a);if(void 0!==g&&g(b,e))return b;d=a;return k=e}var c=!1,d,k,m=void 0===e?null:e;return[function(){return a(b())},null===m?void 0:function(){return a(m())}]},[b,e,l,g]);var d=r(a,c[0],c[1]);\nu(function(){f.hasValue=!0;f.value=d},[d]);w(d);return d};\n","'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n  module.exports = require('../cjs/use-sync-external-store-shim.production.min.js');\n} else {\n  module.exports = require('../cjs/use-sync-external-store-shim.development.js');\n}\n","'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n  module.exports = require('../cjs/use-sync-external-store-shim/with-selector.production.min.js');\n} else {\n  module.exports = require('../cjs/use-sync-external-store-shim/with-selector.development.js');\n}\n","import { X as XSTATE_STOP, A as createActor } from '../../dist/raise-c17ec2bc.esm.js';\nimport '../../dev/dist/xstate-dev.esm.js';\n\n/**\n * Represents an actor created by `fromTransition`.\n *\n * The type of `self` within the actor's logic.\n *\n * @example\n *\n * ```ts\n * import {\n *   fromTransition,\n *   createActor,\n *   type AnyActorSystem\n * } from 'xstate';\n *\n * //* The actor's stored context.\n * type Context = {\n *   // The current count.\n *   count: number;\n *   // The amount to increase `count` by.\n *   step: number;\n * };\n * // The events the actor receives.\n * type Event = { type: 'increment' };\n * // The actor's input.\n * type Input = { step?: number };\n *\n * // Actor logic that increments `count` by `step` when it receives an event of\n * // type `increment`.\n * const logic = fromTransition<Context, Event, AnyActorSystem, Input>(\n *   (state, event, actorScope) => {\n *     actorScope.self;\n *     //         ^? TransitionActorRef<Context, Event>\n *\n *     if (event.type === 'increment') {\n *       return {\n *         ...state,\n *         count: state.count + state.step\n *       };\n *     }\n *     return state;\n *   },\n *   ({ input, self }) => {\n *     self;\n *     // ^? TransitionActorRef<Context, Event>\n *\n *     return {\n *       count: 0,\n *       step: input.step ?? 1\n *     };\n *   }\n * );\n *\n * const actor = createActor(logic, { input: { step: 10 } });\n * //    ^? TransitionActorRef<Context, Event>\n * ```\n *\n * @see {@link fromTransition}\n */\n\n/**\n * Returns actor logic given a transition function and its initial state.\n *\n * A “transition function” is a function that takes the current `state` and\n * received `event` object as arguments, and returns the next state, similar to\n * a reducer.\n *\n * Actors created from transition logic (“transition actors”) can:\n *\n * - Receive events\n * - Emit snapshots of its state\n *\n * The transition function’s `state` is used as its transition actor’s\n * `context`.\n *\n * Note that the \"state\" for a transition function is provided by the initial\n * state argument, and is not the same as the State object of an actor or a\n * state within a machine configuration.\n *\n * @example\n *\n * ```ts\n * const transitionLogic = fromTransition(\n *   (state, event) => {\n *     if (event.type === 'increment') {\n *       return {\n *         ...state,\n *         count: state.count + 1\n *       };\n *     }\n *     return state;\n *   },\n *   { count: 0 }\n * );\n *\n * const transitionActor = createActor(transitionLogic);\n * transitionActor.subscribe((snapshot) => {\n *   console.log(snapshot);\n * });\n * transitionActor.start();\n * // => {\n * //   status: 'active',\n * //   context: { count: 0 },\n * //   ...\n * // }\n *\n * transitionActor.send({ type: 'increment' });\n * // => {\n * //   status: 'active',\n * //   context: { count: 1 },\n * //   ...\n * // }\n * ```\n *\n * @param transition The transition function used to describe the transition\n *   logic. It should return the next state given the current state and event.\n *   It receives the following arguments:\n *\n *   - `state` - the current state.\n *   - `event` - the received event.\n *   - `actorScope` - the actor scope object, with properties like `self` and\n *       `system`.\n *\n * @param initialContext The initial state of the transition function, either an\n *   object representing the state, or a function which returns a state object.\n *   If a function, it will receive as its only argument an object with the\n *   following properties:\n *\n *   - `input` - the `input` provided to its parent transition actor.\n *   - `self` - a reference to its parent transition actor.\n *\n * @returns Actor logic\n * @see {@link https://stately.ai/docs/input | Input docs} for more information about how input is passed\n */\nfunction fromTransition(transition, initialContext) {\n  return {\n    config: transition,\n    transition: (snapshot, event, actorScope) => {\n      return {\n        ...snapshot,\n        context: transition(snapshot.context, event, actorScope)\n      };\n    },\n    getInitialSnapshot: (_, input) => {\n      return {\n        status: 'active',\n        output: undefined,\n        error: undefined,\n        context: typeof initialContext === 'function' ? initialContext({\n          input\n        }) : initialContext\n      };\n    },\n    getPersistedSnapshot: snapshot => snapshot,\n    restoreSnapshot: snapshot => snapshot\n  };\n}\n\nconst instanceStates = /* #__PURE__ */new WeakMap();\n\n/**\n * Represents an actor created by `fromCallback`.\n *\n * The type of `self` within the actor's logic.\n *\n * @example\n *\n * ```ts\n * import { fromCallback, createActor } from 'xstate';\n *\n * // The events the actor receives.\n * type Event = { type: 'someEvent' };\n * // The actor's input.\n * type Input = { name: string };\n *\n * // Actor logic that logs whenever it receives an event of type `someEvent`.\n * const logic = fromCallback<Event, Input>(({ self, input, receive }) => {\n *   self;\n *   // ^? CallbackActorRef<Event, Input>\n *\n *   receive((event) => {\n *     if (event.type === 'someEvent') {\n *       console.log(`${input.name}: received \"someEvent\" event`);\n *       // logs 'myActor: received \"someEvent\" event'\n *     }\n *   });\n * });\n *\n * const actor = createActor(logic, { input: { name: 'myActor' } });\n * //    ^? CallbackActorRef<Event, Input>\n * ```\n *\n * @see {@link fromCallback}\n */\n\n/**\n * An actor logic creator which returns callback logic as defined by a callback\n * function.\n *\n * @remarks\n * Useful for subscription-based or other free-form logic that can send events\n * back to the parent actor.\n *\n * Actors created from callback logic (“callback actors”) can:\n *\n * - Receive events via the `receive` function\n * - Send events to the parent actor via the `sendBack` function\n *\n * Callback actors are a bit different from other actors in that they:\n *\n * - Do not work with `onDone`\n * - Do not produce a snapshot using `.getSnapshot()`\n * - Do not emit values when used with `.subscribe()`\n * - Can not be stopped with `.stop()`\n *\n * @example\n *\n * ```typescript\n * const callbackLogic = fromCallback(({ sendBack, receive }) => {\n *   let lockStatus = 'unlocked';\n *\n *   const handler = (event) => {\n *     if (lockStatus === 'locked') {\n *       return;\n *     }\n *     sendBack(event);\n *   };\n *\n *   receive((event) => {\n *     if (event.type === 'lock') {\n *       lockStatus = 'locked';\n *     } else if (event.type === 'unlock') {\n *       lockStatus = 'unlocked';\n *     }\n *   });\n *\n *   document.body.addEventListener('click', handler);\n *\n *   return () => {\n *     document.body.removeEventListener('click', handler);\n *   };\n * });\n * ```\n *\n * @param callback - The callback function used to describe the callback logic\n *   The callback function is passed an object with the following properties:\n *\n *   - `receive` - A function that can send events back to the parent actor; the\n *       listener is then called whenever events are received by the callback\n *       actor\n *   - `sendBack` - A function that can send events back to the parent actor\n *   - `input` - Data that was provided to the callback actor\n *   - `self` - The parent actor of the callback actor\n *   - `system` - The actor system to which the callback actor belongs The callback\n *       function can (optionally) return a cleanup function, which is called\n *       when the actor is stopped.\n *\n * @returns Callback logic\n * @see {@link CallbackLogicFunction} for more information about the callback function and its object argument\n * @see {@link https://stately.ai/docs/input | Input docs} for more information about how input is passed\n */\nfunction fromCallback(callback) {\n  const logic = {\n    config: callback,\n    start: (state, actorScope) => {\n      const {\n        self,\n        system,\n        emit\n      } = actorScope;\n      const callbackState = {\n        receivers: undefined,\n        dispose: undefined\n      };\n      instanceStates.set(self, callbackState);\n      callbackState.dispose = callback({\n        input: state.input,\n        system,\n        self,\n        sendBack: event => {\n          if (self.getSnapshot().status === 'stopped') {\n            return;\n          }\n          if (self._parent) {\n            system._relay(self, self._parent, event);\n          }\n        },\n        receive: listener => {\n          callbackState.receivers ??= new Set();\n          callbackState.receivers.add(listener);\n        },\n        emit\n      });\n    },\n    transition: (state, event, actorScope) => {\n      const callbackState = instanceStates.get(actorScope.self);\n      if (event.type === XSTATE_STOP) {\n        state = {\n          ...state,\n          status: 'stopped',\n          error: undefined\n        };\n        callbackState.dispose?.();\n        return state;\n      }\n      callbackState.receivers?.forEach(receiver => receiver(event));\n      return state;\n    },\n    getInitialSnapshot: (_, input) => {\n      return {\n        status: 'active',\n        output: undefined,\n        error: undefined,\n        input\n      };\n    },\n    getPersistedSnapshot: snapshot => snapshot,\n    restoreSnapshot: snapshot => snapshot\n  };\n  return logic;\n}\n\nconst XSTATE_OBSERVABLE_NEXT = 'xstate.observable.next';\nconst XSTATE_OBSERVABLE_ERROR = 'xstate.observable.error';\nconst XSTATE_OBSERVABLE_COMPLETE = 'xstate.observable.complete';\n\n/**\n * Represents an actor created by `fromObservable` or `fromEventObservable`.\n *\n * The type of `self` within the actor's logic.\n *\n * @example\n *\n * ```ts\n * import { fromObservable, createActor } from 'xstate';\n * import { interval } from 'rxjs';\n *\n * // The type of the value observed by the actor's logic.\n * type Context = number;\n * // The actor's input.\n * type Input = { period?: number };\n *\n * // Actor logic that observes a number incremented every `input.period`\n * // milliseconds (default: 1_000).\n * const logic = fromObservable<Context, Input>(({ input, self }) => {\n *   self;\n *   // ^? ObservableActorRef<Event, Input>\n *\n *   return interval(input.period ?? 1_000);\n * });\n *\n * const actor = createActor(logic, { input: { period: 2_000 } });\n * //    ^? ObservableActorRef<Event, Input>\n * ```\n *\n * @see {@link fromObservable}\n * @see {@link fromEventObservable}\n */\n\n/**\n * Observable actor logic is described by an observable stream of values. Actors\n * created from observable logic (“observable actors”) can:\n *\n * - Emit snapshots of the observable’s emitted value\n *\n * The observable’s emitted value is used as its observable actor’s `context`.\n *\n * Sending events to observable actors will have no effect.\n *\n * @example\n *\n * ```ts\n * import { fromObservable, createActor } from 'xstate';\n * import { interval } from 'rxjs';\n *\n * const logic = fromObservable((obj) => interval(1000));\n *\n * const actor = createActor(logic);\n *\n * actor.subscribe((snapshot) => {\n *   console.log(snapshot.context);\n * });\n *\n * actor.start();\n * // At every second:\n * // Logs 0\n * // Logs 1\n * // Logs 2\n * // ...\n * ```\n *\n * @param observableCreator A function that creates an observable. It receives\n *   one argument, an object with the following properties:\n *\n *   - `input` - Data that was provided to the observable actor\n *   - `self` - The parent actor\n *   - `system` - The actor system to which the observable actor belongs\n *\n *   It should return a {@link Subscribable}, which is compatible with an RxJS\n *   Observable, although RxJS is not required to create them.\n * @see {@link https://rxjs.dev} for documentation on RxJS Observable and observable creators.\n * @see {@link Subscribable} interface in XState, which is based on and compatible with RxJS Observable.\n */\nfunction fromObservable(observableCreator) {\n  // TODO: add event types\n  const logic = {\n    config: observableCreator,\n    transition: (snapshot, event) => {\n      if (snapshot.status !== 'active') {\n        return snapshot;\n      }\n      switch (event.type) {\n        case XSTATE_OBSERVABLE_NEXT:\n          {\n            const newSnapshot = {\n              ...snapshot,\n              context: event.data\n            };\n            return newSnapshot;\n          }\n        case XSTATE_OBSERVABLE_ERROR:\n          return {\n            ...snapshot,\n            status: 'error',\n            error: event.data,\n            input: undefined,\n            _subscription: undefined\n          };\n        case XSTATE_OBSERVABLE_COMPLETE:\n          return {\n            ...snapshot,\n            status: 'done',\n            input: undefined,\n            _subscription: undefined\n          };\n        case XSTATE_STOP:\n          snapshot._subscription.unsubscribe();\n          return {\n            ...snapshot,\n            status: 'stopped',\n            input: undefined,\n            _subscription: undefined\n          };\n        default:\n          return snapshot;\n      }\n    },\n    getInitialSnapshot: (_, input) => {\n      return {\n        status: 'active',\n        output: undefined,\n        error: undefined,\n        context: undefined,\n        input,\n        _subscription: undefined\n      };\n    },\n    start: (state, {\n      self,\n      system,\n      emit\n    }) => {\n      if (state.status === 'done') {\n        // Do not restart a completed observable\n        return;\n      }\n      state._subscription = observableCreator({\n        input: state.input,\n        system,\n        self,\n        emit\n      }).subscribe({\n        next: value => {\n          system._relay(self, self, {\n            type: XSTATE_OBSERVABLE_NEXT,\n            data: value\n          });\n        },\n        error: err => {\n          system._relay(self, self, {\n            type: XSTATE_OBSERVABLE_ERROR,\n            data: err\n          });\n        },\n        complete: () => {\n          system._relay(self, self, {\n            type: XSTATE_OBSERVABLE_COMPLETE\n          });\n        }\n      });\n    },\n    getPersistedSnapshot: ({\n      _subscription,\n      ...state\n    }) => state,\n    restoreSnapshot: state => ({\n      ...state,\n      _subscription: undefined\n    })\n  };\n  return logic;\n}\n\n/**\n * Creates event observable logic that listens to an observable that delivers\n * event objects.\n *\n * Event observable actor logic is described by an observable stream of\n * {@link https://stately.ai/docs/transitions#event-objects | event objects}.\n * Actors created from event observable logic (“event observable actors”) can:\n *\n * - Implicitly send events to its parent actor\n * - Emit snapshots of its emitted event objects\n *\n * Sending events to event observable actors will have no effect.\n *\n * @example\n *\n * ```ts\n * import {\n *   fromEventObservable,\n *   Subscribable,\n *   EventObject,\n *   createMachine,\n *   createActor\n * } from 'xstate';\n * import { fromEvent } from 'rxjs';\n *\n * const mouseClickLogic = fromEventObservable(\n *   () => fromEvent(document.body, 'click') as Subscribable<EventObject>\n * );\n *\n * const canvasMachine = createMachine({\n *   invoke: {\n *     // Will send mouse `click` events to the canvas actor\n *     src: mouseClickLogic\n *   }\n * });\n *\n * const canvasActor = createActor(canvasMachine);\n * canvasActor.start();\n * ```\n *\n * @param lazyObservable A function that creates an observable that delivers\n *   event objects. It receives one argument, an object with the following\n *   properties:\n *\n *   - `input` - Data that was provided to the event observable actor\n *   - `self` - The parent actor\n *   - `system` - The actor system to which the event observable actor belongs.\n *\n *   It should return a {@link Subscribable}, which is compatible with an RxJS\n *   Observable, although RxJS is not required to create them.\n */\nfunction fromEventObservable(lazyObservable) {\n  // TODO: event types\n  const logic = {\n    config: lazyObservable,\n    transition: (state, event) => {\n      if (state.status !== 'active') {\n        return state;\n      }\n      switch (event.type) {\n        case XSTATE_OBSERVABLE_ERROR:\n          return {\n            ...state,\n            status: 'error',\n            error: event.data,\n            input: undefined,\n            _subscription: undefined\n          };\n        case XSTATE_OBSERVABLE_COMPLETE:\n          return {\n            ...state,\n            status: 'done',\n            input: undefined,\n            _subscription: undefined\n          };\n        case XSTATE_STOP:\n          state._subscription.unsubscribe();\n          return {\n            ...state,\n            status: 'stopped',\n            input: undefined,\n            _subscription: undefined\n          };\n        default:\n          return state;\n      }\n    },\n    getInitialSnapshot: (_, input) => {\n      return {\n        status: 'active',\n        output: undefined,\n        error: undefined,\n        context: undefined,\n        input,\n        _subscription: undefined\n      };\n    },\n    start: (state, {\n      self,\n      system,\n      emit\n    }) => {\n      if (state.status === 'done') {\n        // Do not restart a completed observable\n        return;\n      }\n      state._subscription = lazyObservable({\n        input: state.input,\n        system,\n        self,\n        emit\n      }).subscribe({\n        next: value => {\n          if (self._parent) {\n            system._relay(self, self._parent, value);\n          }\n        },\n        error: err => {\n          system._relay(self, self, {\n            type: XSTATE_OBSERVABLE_ERROR,\n            data: err\n          });\n        },\n        complete: () => {\n          system._relay(self, self, {\n            type: XSTATE_OBSERVABLE_COMPLETE\n          });\n        }\n      });\n    },\n    getPersistedSnapshot: ({\n      _subscription,\n      ...snapshot\n    }) => snapshot,\n    restoreSnapshot: snapshot => ({\n      ...snapshot,\n      _subscription: undefined\n    })\n  };\n  return logic;\n}\n\nconst XSTATE_PROMISE_RESOLVE = 'xstate.promise.resolve';\nconst XSTATE_PROMISE_REJECT = 'xstate.promise.reject';\n\n/**\n * Represents an actor created by `fromPromise`.\n *\n * The type of `self` within the actor's logic.\n *\n * @example\n *\n * ```ts\n * import { fromPromise, createActor } from 'xstate';\n *\n * // The actor's resolved output\n * type Output = string;\n * // The actor's input.\n * type Input = { message: string };\n *\n * // Actor logic that fetches the url of an image of a cat saying `input.message`.\n * const logic = fromPromise<Output, Input>(async ({ input, self }) => {\n *   self;\n *   // ^? PromiseActorRef<Output, Input>\n *\n *   const data = await fetch(\n *     `https://cataas.com/cat/says/${input.message}`\n *   );\n *   const url = await data.json();\n *   return url;\n * });\n *\n * const actor = createActor(logic, { input: { message: 'hello world' } });\n * //    ^? PromiseActorRef<Output, Input>\n * ```\n *\n * @see {@link fromPromise}\n */\n\nconst controllerMap = new WeakMap();\n\n/**\n * An actor logic creator which returns promise logic as defined by an async\n * process that resolves or rejects after some time.\n *\n * Actors created from promise actor logic (“promise actors”) can:\n *\n * - Emit the resolved value of the promise\n * - Output the resolved value of the promise\n *\n * Sending events to promise actors will have no effect.\n *\n * @example\n *\n * ```ts\n * const promiseLogic = fromPromise(async () => {\n *   const result = await fetch('https://example.com/...').then((data) =>\n *     data.json()\n *   );\n *\n *   return result;\n * });\n *\n * const promiseActor = createActor(promiseLogic);\n * promiseActor.subscribe((snapshot) => {\n *   console.log(snapshot);\n * });\n * promiseActor.start();\n * // => {\n * //   output: undefined,\n * //   status: 'active'\n * //   ...\n * // }\n *\n * // After promise resolves\n * // => {\n * //   output: { ... },\n * //   status: 'done',\n * //   ...\n * // }\n * ```\n *\n * @param promiseCreator A function which returns a Promise, and accepts an\n *   object with the following properties:\n *\n *   - `input` - Data that was provided to the promise actor\n *   - `self` - The parent actor of the promise actor\n *   - `system` - The actor system to which the promise actor belongs\n *\n * @see {@link https://stately.ai/docs/input | Input docs} for more information about how input is passed\n */\nfunction fromPromise(promiseCreator) {\n  const logic = {\n    config: promiseCreator,\n    transition: (state, event, scope) => {\n      if (state.status !== 'active') {\n        return state;\n      }\n      switch (event.type) {\n        case XSTATE_PROMISE_RESOLVE:\n          {\n            const resolvedValue = event.data;\n            return {\n              ...state,\n              status: 'done',\n              output: resolvedValue,\n              input: undefined\n            };\n          }\n        case XSTATE_PROMISE_REJECT:\n          return {\n            ...state,\n            status: 'error',\n            error: event.data,\n            input: undefined\n          };\n        case XSTATE_STOP:\n          {\n            controllerMap.get(scope.self)?.abort();\n            return {\n              ...state,\n              status: 'stopped',\n              input: undefined\n            };\n          }\n        default:\n          return state;\n      }\n    },\n    start: (state, {\n      self,\n      system,\n      emit\n    }) => {\n      // TODO: determine how to allow customizing this so that promises\n      // can be restarted if necessary\n      if (state.status !== 'active') {\n        return;\n      }\n      const controller = new AbortController();\n      controllerMap.set(self, controller);\n      const resolvedPromise = Promise.resolve(promiseCreator({\n        input: state.input,\n        system,\n        self,\n        signal: controller.signal,\n        emit\n      }));\n      resolvedPromise.then(response => {\n        if (self.getSnapshot().status !== 'active') {\n          return;\n        }\n        controllerMap.delete(self);\n        system._relay(self, self, {\n          type: XSTATE_PROMISE_RESOLVE,\n          data: response\n        });\n      }, errorData => {\n        if (self.getSnapshot().status !== 'active') {\n          return;\n        }\n        controllerMap.delete(self);\n        system._relay(self, self, {\n          type: XSTATE_PROMISE_REJECT,\n          data: errorData\n        });\n      });\n    },\n    getInitialSnapshot: (_, input) => {\n      return {\n        status: 'active',\n        output: undefined,\n        error: undefined,\n        input\n      };\n    },\n    getPersistedSnapshot: snapshot => snapshot,\n    restoreSnapshot: snapshot => snapshot\n  };\n  return logic;\n}\n\nconst emptyLogic = fromTransition(_ => undefined, undefined);\nfunction createEmptyActor() {\n  return createActor(emptyLogic);\n}\n\nexport { createEmptyActor, fromCallback, fromEventObservable, fromObservable, fromPromise, fromTransition };\n","import { T as ProcessingStatus, z as resolveReferencedActor, A as createActor, U as cloneMachineSnapshot, V as XSTATE_ERROR, W as createErrorActorEvent, e as evaluateGuard, M as cancel, O as raise, P as spawnChild, R as stopChild } from './raise-c17ec2bc.esm.js';\n\nfunction createSpawner(actorScope, {\n  machine,\n  context\n}, event, spawnedChildren) {\n  const spawn = (src, options = {}) => {\n    const {\n      systemId,\n      input\n    } = options;\n    if (typeof src === 'string') {\n      const logic = resolveReferencedActor(machine, src);\n      if (!logic) {\n        throw new Error(`Actor logic '${src}' not implemented in machine '${machine.id}'`);\n      }\n      const actorRef = createActor(logic, {\n        id: options.id,\n        parent: actorScope.self,\n        syncSnapshot: options.syncSnapshot,\n        input: typeof input === 'function' ? input({\n          context,\n          event,\n          self: actorScope.self\n        }) : input,\n        src,\n        systemId\n      });\n      spawnedChildren[actorRef.id] = actorRef;\n      return actorRef;\n    } else {\n      const actorRef = createActor(src, {\n        id: options.id,\n        parent: actorScope.self,\n        syncSnapshot: options.syncSnapshot,\n        input: options.input,\n        src,\n        systemId\n      });\n      return actorRef;\n    }\n  };\n  return (src, options) => {\n    const actorRef = spawn(src, options); // TODO: fix types\n    spawnedChildren[actorRef.id] = actorRef;\n    actorScope.defer(() => {\n      if (actorRef._processingStatus === ProcessingStatus.Stopped) {\n        return;\n      }\n      actorRef.start();\n    });\n    return actorRef;\n  };\n}\n\nfunction resolveAssign(actorScope, snapshot, actionArgs, actionParams, {\n  assignment\n}) {\n  if (!snapshot.context) {\n    throw new Error('Cannot assign to undefined `context`. Ensure that `context` is defined in the machine config.');\n  }\n  const spawnedChildren = {};\n  const assignArgs = {\n    context: snapshot.context,\n    event: actionArgs.event,\n    spawn: createSpawner(actorScope, snapshot, actionArgs.event, spawnedChildren),\n    self: actorScope.self,\n    system: actorScope.system\n  };\n  let partialUpdate = {};\n  if (typeof assignment === 'function') {\n    partialUpdate = assignment(assignArgs, actionParams);\n  } else {\n    for (const key of Object.keys(assignment)) {\n      const propAssignment = assignment[key];\n      partialUpdate[key] = typeof propAssignment === 'function' ? propAssignment(assignArgs, actionParams) : propAssignment;\n    }\n  }\n  const updatedContext = Object.assign({}, snapshot.context, partialUpdate);\n  return [cloneMachineSnapshot(snapshot, {\n    context: updatedContext,\n    children: Object.keys(spawnedChildren).length ? {\n      ...snapshot.children,\n      ...spawnedChildren\n    } : snapshot.children\n  }), undefined, undefined];\n}\n/**\n * Updates the current context of the machine.\n *\n * @example\n *\n * ```ts\n * import { createMachine, assign } from 'xstate';\n *\n * const countMachine = createMachine({\n *   context: {\n *     count: 0,\n *     message: ''\n *   },\n *   on: {\n *     inc: {\n *       actions: assign({\n *         count: ({ context }) => context.count + 1\n *       })\n *     },\n *     updateMessage: {\n *       actions: assign(({ context, event }) => {\n *         return {\n *           message: event.message.trim()\n *         };\n *       })\n *     }\n *   }\n * });\n * ```\n *\n * @param assignment An object that represents the partial context to update, or\n *   a function that returns an object that represents the partial context to\n *   update.\n */\nfunction assign(assignment) {\n  function assign(_args, _params) {\n  }\n  assign.type = 'xstate.assign';\n  assign.assignment = assignment;\n  assign.resolve = resolveAssign;\n  return assign;\n}\n\nfunction resolveEmit(_, snapshot, args, actionParams, {\n  event: eventOrExpr\n}) {\n  const resolvedEvent = typeof eventOrExpr === 'function' ? eventOrExpr(args, actionParams) : eventOrExpr;\n  return [snapshot, {\n    event: resolvedEvent\n  }, undefined];\n}\nfunction executeEmit(actorScope, {\n  event\n}) {\n  actorScope.defer(() => actorScope.emit(event));\n}\n/**\n * Emits an event to event handlers registered on the actor via `actor.on(event,\n * handler)`.\n *\n * @example\n *\n * ```ts\n * import { emit } from 'xstate';\n *\n * const machine = createMachine({\n *   // ...\n *   on: {\n *     something: {\n *       actions: emit({\n *         type: 'emitted',\n *         some: 'data'\n *       })\n *     }\n *   }\n *   // ...\n * });\n *\n * const actor = createActor(machine).start();\n *\n * actor.on('emitted', (event) => {\n *   console.log(event);\n * });\n *\n * actor.send({ type: 'something' });\n * // logs:\n * // {\n * //   type: 'emitted',\n * //   some: 'data'\n * // }\n * ```\n */\nfunction emit(/** The event to emit, or an expression that returns an event to emit. */\neventOrExpr) {\n  function emit(_args, _params) {\n  }\n  emit.type = 'xstate.emit';\n  emit.event = eventOrExpr;\n  emit.resolve = resolveEmit;\n  emit.execute = executeEmit;\n  return emit;\n}\n\n/**\n * @remarks\n * `T | unknown` reduces to `unknown` and that can be problematic when it comes\n * to contextual typing. It especially is a problem when the union has a\n * function member, like here:\n *\n * ```ts\n * declare function test(\n *   cbOrVal: ((arg: number) => unknown) | unknown\n * ): void;\n * test((arg) => {}); // oops, implicit any\n * ```\n *\n * This type can be used to avoid this problem. This union represents the same\n * value space as `unknown`.\n */\n\n// https://github.com/microsoft/TypeScript/issues/23182#issuecomment-379091887\n\n// @TODO: Replace with native `NoInfer` when TS issue gets fixed:\n// https://github.com/microsoft/TypeScript/pull/57673\n\n/** @deprecated Use the built-in `NoInfer` type instead */\n\n/** The full definition of an event, with a string `type`. */\n\n/**\n * The string or object representing the state value relative to the parent\n * state node.\n *\n * @remarks\n * - For a child atomic state node, this is a string, e.g., `\"pending\"`.\n * - For complex state nodes, this is an object, e.g., `{ success:\n *   \"someChildState\" }`.\n */\n\n/** @deprecated Use `AnyMachineSnapshot` instead */\n\n// TODO: possibly refactor this somehow, use even a simpler type, and maybe even make `machine.options` private or something\n/** @ignore */\n\nlet SpecialTargets = /*#__PURE__*/function (SpecialTargets) {\n  SpecialTargets[\"Parent\"] = \"#_parent\";\n  SpecialTargets[\"Internal\"] = \"#_internal\";\n  return SpecialTargets;\n}({});\n\n/** @deprecated Use `AnyActor` instead. */\n\n// Based on RxJS types\n\n// TODO: in v6, this should only accept AnyActorLogic, like ActorRefFromLogic\n\n/** @deprecated Use `Actor<T>` instead. */\n\n/**\n * Represents logic which can be used by an actor.\n *\n * @template TSnapshot - The type of the snapshot.\n * @template TEvent - The type of the event object.\n * @template TInput - The type of the input.\n * @template TSystem - The type of the actor system.\n */\n\n/** @deprecated */\n\n// TODO: cover all that can be actually returned\n\nfunction resolveSendTo(actorScope, snapshot, args, actionParams, {\n  to,\n  event: eventOrExpr,\n  id,\n  delay\n}, extra) {\n  const delaysMap = snapshot.machine.implementations.delays;\n  if (typeof eventOrExpr === 'string') {\n    throw new Error(\n    // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n    `Only event objects may be used with sendTo; use sendTo({ type: \"${eventOrExpr}\" }) instead`);\n  }\n  const resolvedEvent = typeof eventOrExpr === 'function' ? eventOrExpr(args, actionParams) : eventOrExpr;\n  let resolvedDelay;\n  if (typeof delay === 'string') {\n    const configDelay = delaysMap && delaysMap[delay];\n    resolvedDelay = typeof configDelay === 'function' ? configDelay(args, actionParams) : configDelay;\n  } else {\n    resolvedDelay = typeof delay === 'function' ? delay(args, actionParams) : delay;\n  }\n  const resolvedTarget = typeof to === 'function' ? to(args, actionParams) : to;\n  let targetActorRef;\n  if (typeof resolvedTarget === 'string') {\n    // eslint-disable-next-line @typescript-eslint/no-unsafe-enum-comparison\n    if (resolvedTarget === SpecialTargets.Parent) {\n      targetActorRef = actorScope.self._parent;\n    }\n    // eslint-disable-next-line @typescript-eslint/no-unsafe-enum-comparison\n    else if (resolvedTarget === SpecialTargets.Internal) {\n      targetActorRef = actorScope.self;\n    } else if (resolvedTarget.startsWith('#_')) {\n      // SCXML compatibility: https://www.w3.org/TR/scxml/#SCXMLEventProcessor\n      // #_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.\n      targetActorRef = snapshot.children[resolvedTarget.slice(2)];\n    } else {\n      targetActorRef = extra.deferredActorIds?.includes(resolvedTarget) ? resolvedTarget : snapshot.children[resolvedTarget];\n    }\n    if (!targetActorRef) {\n      throw new Error(`Unable to send event to actor '${resolvedTarget}' from machine '${snapshot.machine.id}'.`);\n    }\n  } else {\n    targetActorRef = resolvedTarget || actorScope.self;\n  }\n  return [snapshot, {\n    to: targetActorRef,\n    targetId: typeof resolvedTarget === 'string' ? resolvedTarget : undefined,\n    event: resolvedEvent,\n    id,\n    delay: resolvedDelay\n  }, undefined];\n}\nfunction retryResolveSendTo(_, snapshot, params) {\n  if (typeof params.to === 'string') {\n    params.to = snapshot.children[params.to];\n  }\n}\nfunction executeSendTo(actorScope, params) {\n  // this forms an outgoing events queue\n  // thanks to that the recipient actors are able to read the *updated* snapshot value of the sender\n  actorScope.defer(() => {\n    const {\n      to,\n      event,\n      delay,\n      id\n    } = params;\n    if (typeof delay === 'number') {\n      actorScope.system.scheduler.schedule(actorScope.self, to, event, delay, id);\n      return;\n    }\n    actorScope.system._relay(actorScope.self,\n    // at this point, in a deferred task, it should already be mutated by retryResolveSendTo\n    // if it initially started as a string\n    to, event.type === XSTATE_ERROR ? createErrorActorEvent(actorScope.self.id, event.data) : event);\n  });\n}\n/**\n * Sends an event to an actor.\n *\n * @param actor The `ActorRef` to send the event to.\n * @param event The event to send, or an expression that evaluates to the event\n *   to send\n * @param options Send action options\n *\n *   - `id` - The unique send event identifier (used with `cancel()`).\n *   - `delay` - The number of milliseconds to delay the sending of the event.\n */\nfunction sendTo(to, eventOrExpr, options) {\n  function sendTo(_args, _params) {\n  }\n  sendTo.type = 'xstate.sendTo';\n  sendTo.to = to;\n  sendTo.event = eventOrExpr;\n  sendTo.id = options?.id;\n  sendTo.delay = options?.delay;\n  sendTo.resolve = resolveSendTo;\n  sendTo.retryResolve = retryResolveSendTo;\n  sendTo.execute = executeSendTo;\n  return sendTo;\n}\n\n/**\n * Sends an event to this machine's parent.\n *\n * @param event The event to send to the parent machine.\n * @param options Options to pass into the send event.\n */\nfunction sendParent(event, options) {\n  return sendTo(SpecialTargets.Parent, event, options);\n}\n/**\n * Forwards (sends) an event to the `target` actor.\n *\n * @param target The target actor to forward the event to.\n * @param options Options to pass into the send action creator.\n */\nfunction forwardTo(target, options) {\n  return sendTo(target, ({\n    event\n  }) => event, options);\n}\n\nfunction resolveEnqueueActions(actorScope, snapshot, args, actionParams, {\n  collect\n}) {\n  const actions = [];\n  const enqueue = function enqueue(action) {\n    actions.push(action);\n  };\n  enqueue.assign = (...args) => {\n    actions.push(assign(...args));\n  };\n  enqueue.cancel = (...args) => {\n    actions.push(cancel(...args));\n  };\n  enqueue.raise = (...args) => {\n    // for some reason it fails to infer `TDelay` from `...args` here and picks its default (`never`)\n    // then it fails to typecheck that because `...args` use `string` in place of `TDelay`\n    actions.push(raise(...args));\n  };\n  enqueue.sendTo = (...args) => {\n    // for some reason it fails to infer `TDelay` from `...args` here and picks its default (`never`)\n    // then it fails to typecheck that because `...args` use `string` in place of `TDelay\n    actions.push(sendTo(...args));\n  };\n  enqueue.sendParent = (...args) => {\n    actions.push(sendParent(...args));\n  };\n  enqueue.spawnChild = (...args) => {\n    actions.push(spawnChild(...args));\n  };\n  enqueue.stopChild = (...args) => {\n    actions.push(stopChild(...args));\n  };\n  enqueue.emit = (...args) => {\n    actions.push(emit(...args));\n  };\n  collect({\n    context: args.context,\n    event: args.event,\n    enqueue,\n    check: guard => evaluateGuard(guard, snapshot.context, args.event, snapshot),\n    self: actorScope.self,\n    system: actorScope.system\n  }, actionParams);\n  return [snapshot, undefined, actions];\n}\n/**\n * Creates an action object that will execute actions that are queued by the\n * `enqueue(action)` function.\n *\n * @example\n *\n * ```ts\n * import { createMachine, enqueueActions } from 'xstate';\n *\n * const machine = createMachine({\n *   entry: enqueueActions(({ enqueue, check }) => {\n *     enqueue.assign({ count: 0 });\n *\n *     if (check('someGuard')) {\n *       enqueue.assign({ count: 1 });\n *     }\n *\n *     enqueue('someAction');\n *   })\n * });\n * ```\n */\nfunction enqueueActions(collect) {\n  function enqueueActions(_args, _params) {\n  }\n  enqueueActions.type = 'xstate.enqueueActions';\n  enqueueActions.collect = collect;\n  enqueueActions.resolve = resolveEnqueueActions;\n  return enqueueActions;\n}\n\nfunction resolveLog(_, snapshot, actionArgs, actionParams, {\n  value,\n  label\n}) {\n  return [snapshot, {\n    value: typeof value === 'function' ? value(actionArgs, actionParams) : value,\n    label\n  }, undefined];\n}\nfunction executeLog({\n  logger\n}, {\n  value,\n  label\n}) {\n  if (label) {\n    logger(label, value);\n  } else {\n    logger(value);\n  }\n}\n/**\n * @param expr The expression function to evaluate which will be logged. Takes\n *   in 2 arguments:\n *\n *   - `ctx` - the current state context\n *   - `event` - the event that caused this action to be executed.\n *\n * @param label The label to give to the logged expression.\n */\nfunction log(value = ({\n  context,\n  event\n}) => ({\n  context,\n  event\n}), label) {\n  function log(_args, _params) {\n  }\n  log.type = 'xstate.log';\n  log.value = value;\n  log.label = label;\n  log.resolve = resolveLog;\n  log.execute = executeLog;\n  return log;\n}\n\nexport { SpecialTargets as S, assign as a, enqueueActions as b, sendTo as c, emit as e, forwardTo as f, log as l, sendParent as s };\n","// From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis\nfunction getGlobal() {\n  if (typeof globalThis !== 'undefined') {\n    return globalThis;\n  }\n  if (typeof self !== 'undefined') {\n    return self;\n  }\n  if (typeof window !== 'undefined') {\n    return window;\n  }\n  if (typeof global !== 'undefined') {\n    return global;\n  }\n}\nfunction getDevTools() {\n  const w = getGlobal();\n  if (w.__xstate__) {\n    return w.__xstate__;\n  }\n  return undefined;\n}\nfunction registerService(service) {\n  if (typeof window === 'undefined') {\n    return;\n  }\n  const devTools = getDevTools();\n  if (devTools) {\n    devTools.register(service);\n  }\n}\nconst devToolsAdapter = service => {\n  if (typeof window === 'undefined') {\n    return;\n  }\n  const devTools = getDevTools();\n  if (devTools) {\n    devTools.register(service);\n  }\n};\n\nexport { devToolsAdapter, getGlobal, registerService };\n","import { devToolsAdapter } from '../dev/dist/xstate-dev.esm.js';\n\nclass Mailbox {\n  constructor(_process) {\n    this._process = _process;\n    this._active = false;\n    this._current = null;\n    this._last = null;\n  }\n  start() {\n    this._active = true;\n    this.flush();\n  }\n  clear() {\n    // we can't set _current to null because we might be currently processing\n    // and enqueue following clear shouldnt start processing the enqueued item immediately\n    if (this._current) {\n      this._current.next = null;\n      this._last = this._current;\n    }\n  }\n  enqueue(event) {\n    const enqueued = {\n      value: event,\n      next: null\n    };\n    if (this._current) {\n      this._last.next = enqueued;\n      this._last = enqueued;\n      return;\n    }\n    this._current = enqueued;\n    this._last = enqueued;\n    if (this._active) {\n      this.flush();\n    }\n  }\n  flush() {\n    while (this._current) {\n      // atm the given _process is responsible for implementing proper try/catch handling\n      // we assume here that this won't throw in a way that can affect this mailbox\n      const consumed = this._current;\n      this._process(consumed.value);\n      this._current = consumed.next;\n    }\n    this._last = null;\n  }\n}\n\nconst STATE_DELIMITER = '.';\nconst TARGETLESS_KEY = '';\nconst NULL_EVENT = '';\nconst STATE_IDENTIFIER = '#';\nconst WILDCARD = '*';\nconst XSTATE_INIT = 'xstate.init';\nconst XSTATE_ERROR = 'xstate.error';\nconst XSTATE_STOP = 'xstate.stop';\n\n/**\n * Returns an event that represents an implicit event that is sent after the\n * specified `delay`.\n *\n * @param delayRef The delay in milliseconds\n * @param id The state node ID where this event is handled\n */\nfunction createAfterEvent(delayRef, id) {\n  return {\n    type: `xstate.after.${delayRef}.${id}`\n  };\n}\n\n/**\n * Returns an event that represents that a final state node has been reached in\n * the parent state node.\n *\n * @param id The final state node's parent state node `id`\n * @param output The data to pass into the event\n */\nfunction createDoneStateEvent(id, output) {\n  return {\n    type: `xstate.done.state.${id}`,\n    output\n  };\n}\n\n/**\n * Returns an event that represents that an invoked service has terminated.\n *\n * An invoked service is terminated when it has reached a top-level final state\n * node, but not when it is canceled.\n *\n * @param invokeId The invoked service ID\n * @param output The data to pass into the event\n */\nfunction createDoneActorEvent(invokeId, output) {\n  return {\n    type: `xstate.done.actor.${invokeId}`,\n    output,\n    actorId: invokeId\n  };\n}\nfunction createErrorActorEvent(id, error) {\n  return {\n    type: `xstate.error.actor.${id}`,\n    error,\n    actorId: id\n  };\n}\nfunction createInitEvent(input) {\n  return {\n    type: XSTATE_INIT,\n    input\n  };\n}\n\n/**\n * This function makes sure that unhandled errors are thrown in a separate\n * macrotask. It allows those errors to be detected by global error handlers and\n * reported to bug tracking services without interrupting our own stack of\n * execution.\n *\n * @param err Error to be thrown\n */\nfunction reportUnhandledError(err) {\n  setTimeout(() => {\n    throw err;\n  });\n}\n\nconst symbolObservable = (() => typeof Symbol === 'function' && Symbol.observable || '@@observable')();\n\nfunction matchesState(parentStateId, childStateId) {\n  const parentStateValue = toStateValue(parentStateId);\n  const childStateValue = toStateValue(childStateId);\n  if (typeof childStateValue === 'string') {\n    if (typeof parentStateValue === 'string') {\n      return childStateValue === parentStateValue;\n    }\n\n    // Parent more specific than child\n    return false;\n  }\n  if (typeof parentStateValue === 'string') {\n    return parentStateValue in childStateValue;\n  }\n  return Object.keys(parentStateValue).every(key => {\n    if (!(key in childStateValue)) {\n      return false;\n    }\n    return matchesState(parentStateValue[key], childStateValue[key]);\n  });\n}\nfunction toStatePath(stateId) {\n  if (isArray(stateId)) {\n    return stateId;\n  }\n  const result = [];\n  let segment = '';\n  for (let i = 0; i < stateId.length; i++) {\n    const char = stateId.charCodeAt(i);\n    switch (char) {\n      // \\\n      case 92:\n        // consume the next character\n        segment += stateId[i + 1];\n        // and skip over it\n        i++;\n        continue;\n      // .\n      case 46:\n        result.push(segment);\n        segment = '';\n        continue;\n    }\n    segment += stateId[i];\n  }\n  result.push(segment);\n  return result;\n}\nfunction toStateValue(stateValue) {\n  if (isMachineSnapshot(stateValue)) {\n    return stateValue.value;\n  }\n  if (typeof stateValue !== 'string') {\n    return stateValue;\n  }\n  const statePath = toStatePath(stateValue);\n  return pathToStateValue(statePath);\n}\nfunction pathToStateValue(statePath) {\n  if (statePath.length === 1) {\n    return statePath[0];\n  }\n  const value = {};\n  let marker = value;\n  for (let i = 0; i < statePath.length - 1; i++) {\n    if (i === statePath.length - 2) {\n      marker[statePath[i]] = statePath[i + 1];\n    } else {\n      const previous = marker;\n      marker = {};\n      previous[statePath[i]] = marker;\n    }\n  }\n  return value;\n}\nfunction mapValues(collection, iteratee) {\n  const result = {};\n  const collectionKeys = Object.keys(collection);\n  for (let i = 0; i < collectionKeys.length; i++) {\n    const key = collectionKeys[i];\n    result[key] = iteratee(collection[key], key, collection, i);\n  }\n  return result;\n}\nfunction toArrayStrict(value) {\n  if (isArray(value)) {\n    return value;\n  }\n  return [value];\n}\nfunction toArray(value) {\n  if (value === undefined) {\n    return [];\n  }\n  return toArrayStrict(value);\n}\nfunction resolveOutput(mapper, context, event, self) {\n  if (typeof mapper === 'function') {\n    return mapper({\n      context,\n      event,\n      self\n    });\n  }\n  return mapper;\n}\nfunction isArray(value) {\n  return Array.isArray(value);\n}\nfunction isErrorActorEvent(event) {\n  return event.type.startsWith('xstate.error.actor');\n}\nfunction toTransitionConfigArray(configLike) {\n  return toArrayStrict(configLike).map(transitionLike => {\n    if (typeof transitionLike === 'undefined' || typeof transitionLike === 'string') {\n      return {\n        target: transitionLike\n      };\n    }\n    return transitionLike;\n  });\n}\nfunction normalizeTarget(target) {\n  if (target === undefined || target === TARGETLESS_KEY) {\n    return undefined;\n  }\n  return toArray(target);\n}\nfunction toObserver(nextHandler, errorHandler, completionHandler) {\n  const isObserver = typeof nextHandler === 'object';\n  const self = isObserver ? nextHandler : undefined;\n  return {\n    next: (isObserver ? nextHandler.next : nextHandler)?.bind(self),\n    error: (isObserver ? nextHandler.error : errorHandler)?.bind(self),\n    complete: (isObserver ? nextHandler.complete : completionHandler)?.bind(self)\n  };\n}\nfunction createInvokeId(stateNodeId, index) {\n  return `${index}.${stateNodeId}`;\n}\nfunction resolveReferencedActor(machine, src) {\n  const match = src.match(/^xstate\\.invoke\\.(\\d+)\\.(.*)/);\n  if (!match) {\n    return machine.implementations.actors[src];\n  }\n  const [, indexStr, nodeId] = match;\n  const node = machine.getStateNodeById(nodeId);\n  const invokeConfig = node.config.invoke;\n  return (Array.isArray(invokeConfig) ? invokeConfig[indexStr] : invokeConfig).src;\n}\nfunction getAllOwnEventDescriptors(snapshot) {\n  return [...new Set([...snapshot._nodes.flatMap(sn => sn.ownEvents)])];\n}\n\nfunction createScheduledEventId(actorRef, id) {\n  return `${actorRef.sessionId}.${id}`;\n}\nlet idCounter = 0;\nfunction createSystem(rootActor, options) {\n  const children = new Map();\n  const keyedActors = new Map();\n  const reverseKeyedActors = new WeakMap();\n  const inspectionObservers = new Set();\n  const timerMap = {};\n  const {\n    clock,\n    logger\n  } = options;\n  const scheduler = {\n    schedule: (source, target, event, delay, id = Math.random().toString(36).slice(2)) => {\n      const scheduledEvent = {\n        source,\n        target,\n        event,\n        delay,\n        id,\n        startedAt: Date.now()\n      };\n      const scheduledEventId = createScheduledEventId(source, id);\n      system._snapshot._scheduledEvents[scheduledEventId] = scheduledEvent;\n      const timeout = clock.setTimeout(() => {\n        delete timerMap[scheduledEventId];\n        delete system._snapshot._scheduledEvents[scheduledEventId];\n        system._relay(source, target, event);\n      }, delay);\n      timerMap[scheduledEventId] = timeout;\n    },\n    cancel: (source, id) => {\n      const scheduledEventId = createScheduledEventId(source, id);\n      const timeout = timerMap[scheduledEventId];\n      delete timerMap[scheduledEventId];\n      delete system._snapshot._scheduledEvents[scheduledEventId];\n      if (timeout !== undefined) {\n        clock.clearTimeout(timeout);\n      }\n    },\n    cancelAll: actorRef => {\n      for (const scheduledEventId in system._snapshot._scheduledEvents) {\n        const scheduledEvent = system._snapshot._scheduledEvents[scheduledEventId];\n        if (scheduledEvent.source === actorRef) {\n          scheduler.cancel(actorRef, scheduledEvent.id);\n        }\n      }\n    }\n  };\n  const sendInspectionEvent = event => {\n    if (!inspectionObservers.size) {\n      return;\n    }\n    const resolvedInspectionEvent = {\n      ...event,\n      rootId: rootActor.sessionId\n    };\n    inspectionObservers.forEach(observer => observer.next?.(resolvedInspectionEvent));\n  };\n  const system = {\n    _snapshot: {\n      _scheduledEvents: (options?.snapshot && options.snapshot.scheduler) ?? {}\n    },\n    _bookId: () => `x:${idCounter++}`,\n    _register: (sessionId, actorRef) => {\n      children.set(sessionId, actorRef);\n      return sessionId;\n    },\n    _unregister: actorRef => {\n      children.delete(actorRef.sessionId);\n      const systemId = reverseKeyedActors.get(actorRef);\n      if (systemId !== undefined) {\n        keyedActors.delete(systemId);\n        reverseKeyedActors.delete(actorRef);\n      }\n    },\n    get: systemId => {\n      return keyedActors.get(systemId);\n    },\n    _set: (systemId, actorRef) => {\n      const existing = keyedActors.get(systemId);\n      if (existing && existing !== actorRef) {\n        throw new Error(`Actor with system ID '${systemId}' already exists.`);\n      }\n      keyedActors.set(systemId, actorRef);\n      reverseKeyedActors.set(actorRef, systemId);\n    },\n    inspect: observerOrFn => {\n      const observer = toObserver(observerOrFn);\n      inspectionObservers.add(observer);\n      return {\n        unsubscribe() {\n          inspectionObservers.delete(observer);\n        }\n      };\n    },\n    _sendInspectionEvent: sendInspectionEvent,\n    _relay: (source, target, event) => {\n      system._sendInspectionEvent({\n        type: '@xstate.event',\n        sourceRef: source,\n        actorRef: target,\n        event\n      });\n      target._send(event);\n    },\n    scheduler,\n    getSnapshot: () => {\n      return {\n        _scheduledEvents: {\n          ...system._snapshot._scheduledEvents\n        }\n      };\n    },\n    start: () => {\n      const scheduledEvents = system._snapshot._scheduledEvents;\n      system._snapshot._scheduledEvents = {};\n      for (const scheduledId in scheduledEvents) {\n        const {\n          source,\n          target,\n          event,\n          delay,\n          id\n        } = scheduledEvents[scheduledId];\n        scheduler.schedule(source, target, event, delay, id);\n      }\n    },\n    _clock: clock,\n    _logger: logger\n  };\n  return system;\n}\n\nlet executingCustomAction = false;\nconst $$ACTOR_TYPE = 1;\n\n// those values are currently used by @xstate/react directly so it's important to keep the assigned values in sync\nlet ProcessingStatus = /*#__PURE__*/function (ProcessingStatus) {\n  ProcessingStatus[ProcessingStatus[\"NotStarted\"] = 0] = \"NotStarted\";\n  ProcessingStatus[ProcessingStatus[\"Running\"] = 1] = \"Running\";\n  ProcessingStatus[ProcessingStatus[\"Stopped\"] = 2] = \"Stopped\";\n  return ProcessingStatus;\n}({});\nconst defaultOptions = {\n  clock: {\n    setTimeout: (fn, ms) => {\n      return setTimeout(fn, ms);\n    },\n    clearTimeout: id => {\n      return clearTimeout(id);\n    }\n  },\n  logger: console.log.bind(console),\n  devTools: false\n};\n\n/**\n * An Actor is a running process that can receive events, send events and change\n * its behavior based on the events it receives, which can cause effects outside\n * of the actor. When you run a state machine, it becomes an actor.\n */\nclass Actor {\n  /**\n   * Creates a new actor instance for the given logic with the provided options,\n   * if any.\n   *\n   * @param logic The logic to create an actor from\n   * @param options Actor options\n   */\n  constructor(logic, options) {\n    this.logic = logic;\n    /** The current internal state of the actor. */\n    this._snapshot = void 0;\n    /**\n     * The clock that is responsible for setting and clearing timeouts, such as\n     * delayed events and transitions.\n     */\n    this.clock = void 0;\n    this.options = void 0;\n    /** The unique identifier for this actor relative to its parent. */\n    this.id = void 0;\n    this.mailbox = new Mailbox(this._process.bind(this));\n    this.observers = new Set();\n    this.eventListeners = new Map();\n    this.logger = void 0;\n    /** @internal */\n    this._processingStatus = ProcessingStatus.NotStarted;\n    // Actor Ref\n    this._parent = void 0;\n    /** @internal */\n    this._syncSnapshot = void 0;\n    this.ref = void 0;\n    // TODO: add typings for system\n    this._actorScope = void 0;\n    this._systemId = void 0;\n    /** The globally unique process ID for this invocation. */\n    this.sessionId = void 0;\n    /** The system to which this actor belongs. */\n    this.system = void 0;\n    this._doneEvent = void 0;\n    this.src = void 0;\n    // array of functions to defer\n    this._deferred = [];\n    const resolvedOptions = {\n      ...defaultOptions,\n      ...options\n    };\n    const {\n      clock,\n      logger,\n      parent,\n      syncSnapshot,\n      id,\n      systemId,\n      inspect\n    } = resolvedOptions;\n    this.system = parent ? parent.system : createSystem(this, {\n      clock,\n      logger\n    });\n    if (inspect && !parent) {\n      // Always inspect at the system-level\n      this.system.inspect(toObserver(inspect));\n    }\n    this.sessionId = this.system._bookId();\n    this.id = id ?? this.sessionId;\n    this.logger = options?.logger ?? this.system._logger;\n    this.clock = options?.clock ?? this.system._clock;\n    this._parent = parent;\n    this._syncSnapshot = syncSnapshot;\n    this.options = resolvedOptions;\n    this.src = resolvedOptions.src ?? logic;\n    this.ref = this;\n    this._actorScope = {\n      self: this,\n      id: this.id,\n      sessionId: this.sessionId,\n      logger: this.logger,\n      defer: fn => {\n        this._deferred.push(fn);\n      },\n      system: this.system,\n      stopChild: child => {\n        if (child._parent !== this) {\n          throw new Error(`Cannot stop child actor ${child.id} of ${this.id} because it is not a child`);\n        }\n        child._stop();\n      },\n      emit: emittedEvent => {\n        const listeners = this.eventListeners.get(emittedEvent.type);\n        const wildcardListener = this.eventListeners.get('*');\n        if (!listeners && !wildcardListener) {\n          return;\n        }\n        const allListeners = [...(listeners ? listeners.values() : []), ...(wildcardListener ? wildcardListener.values() : [])];\n        for (const handler of allListeners) {\n          handler(emittedEvent);\n        }\n      },\n      actionExecutor: action => {\n        const exec = () => {\n          this._actorScope.system._sendInspectionEvent({\n            type: '@xstate.action',\n            actorRef: this,\n            action: {\n              type: action.type,\n              params: action.params\n            }\n          });\n          if (!action.exec) {\n            return;\n          }\n          const saveExecutingCustomAction = executingCustomAction;\n          try {\n            executingCustomAction = true;\n            action.exec(action.info, action.params);\n          } finally {\n            executingCustomAction = saveExecutingCustomAction;\n          }\n        };\n        if (this._processingStatus === ProcessingStatus.Running) {\n          exec();\n        } else {\n          this._deferred.push(exec);\n        }\n      }\n    };\n\n    // Ensure that the send method is bound to this Actor instance\n    // if destructured\n    this.send = this.send.bind(this);\n    this.system._sendInspectionEvent({\n      type: '@xstate.actor',\n      actorRef: this\n    });\n    if (systemId) {\n      this._systemId = systemId;\n      this.system._set(systemId, this);\n    }\n    this._initState(options?.snapshot ?? options?.state);\n    if (systemId && this._snapshot.status !== 'active') {\n      this.system._unregister(this);\n    }\n  }\n  _initState(persistedState) {\n    try {\n      this._snapshot = persistedState ? this.logic.restoreSnapshot ? this.logic.restoreSnapshot(persistedState, this._actorScope) : persistedState : this.logic.getInitialSnapshot(this._actorScope, this.options?.input);\n    } catch (err) {\n      // if we get here then it means that we assign a value to this._snapshot that is not of the correct type\n      // we can't get the true `TSnapshot & { status: 'error'; }`, it's impossible\n      // so right now this is a lie of sorts\n      this._snapshot = {\n        status: 'error',\n        output: undefined,\n        error: err\n      };\n    }\n  }\n  update(snapshot, event) {\n    // Update state\n    this._snapshot = snapshot;\n\n    // Execute deferred effects\n    let deferredFn;\n    while (deferredFn = this._deferred.shift()) {\n      try {\n        deferredFn();\n      } catch (err) {\n        // this error can only be caught when executing *initial* actions\n        // it's the only time when we call actions provided by the user through those deferreds\n        // when the actor is already running we always execute them synchronously while transitioning\n        // no \"builtin deferred\" should actually throw an error since they are either safe\n        // or the control flow is passed through the mailbox and errors should be caught by the `_process` used by the mailbox\n        this._deferred.length = 0;\n        this._snapshot = {\n          ...snapshot,\n          status: 'error',\n          error: err\n        };\n      }\n    }\n    switch (this._snapshot.status) {\n      case 'active':\n        for (const observer of this.observers) {\n          try {\n            observer.next?.(snapshot);\n          } catch (err) {\n            reportUnhandledError(err);\n          }\n        }\n        break;\n      case 'done':\n        // next observers are meant to be notified about done snapshots\n        // this can be seen as something that is different from how observable work\n        // but with observables `complete` callback is called without any arguments\n        // it's more ergonomic for XState to treat a done snapshot as a \"next\" value\n        // and the completion event as something that is separate,\n        // something that merely follows emitting that done snapshot\n        for (const observer of this.observers) {\n          try {\n            observer.next?.(snapshot);\n          } catch (err) {\n            reportUnhandledError(err);\n          }\n        }\n        this._stopProcedure();\n        this._complete();\n        this._doneEvent = createDoneActorEvent(this.id, this._snapshot.output);\n        if (this._parent) {\n          this.system._relay(this, this._parent, this._doneEvent);\n        }\n        break;\n      case 'error':\n        this._error(this._snapshot.error);\n        break;\n    }\n    this.system._sendInspectionEvent({\n      type: '@xstate.snapshot',\n      actorRef: this,\n      event,\n      snapshot\n    });\n  }\n\n  /**\n   * Subscribe an observer to an actor’s snapshot values.\n   *\n   * @remarks\n   * The observer will receive the actor’s snapshot value when it is emitted.\n   * The observer can be:\n   *\n   * - A plain function that receives the latest snapshot, or\n   * - An observer object whose `.next(snapshot)` method receives the latest\n   *   snapshot\n   *\n   * @example\n   *\n   * ```ts\n   * // Observer as a plain function\n   * const subscription = actor.subscribe((snapshot) => {\n   *   console.log(snapshot);\n   * });\n   * ```\n   *\n   * @example\n   *\n   * ```ts\n   * // Observer as an object\n   * const subscription = actor.subscribe({\n   *   next(snapshot) {\n   *     console.log(snapshot);\n   *   },\n   *   error(err) {\n   *     // ...\n   *   },\n   *   complete() {\n   *     // ...\n   *   }\n   * });\n   * ```\n   *\n   * The return value of `actor.subscribe(observer)` is a subscription object\n   * that has an `.unsubscribe()` method. You can call\n   * `subscription.unsubscribe()` to unsubscribe the observer:\n   *\n   * @example\n   *\n   * ```ts\n   * const subscription = actor.subscribe((snapshot) => {\n   *   // ...\n   * });\n   *\n   * // Unsubscribe the observer\n   * subscription.unsubscribe();\n   * ```\n   *\n   * When the actor is stopped, all of its observers will automatically be\n   * unsubscribed.\n   *\n   * @param observer - Either a plain function that receives the latest\n   *   snapshot, or an observer object whose `.next(snapshot)` method receives\n   *   the latest snapshot\n   */\n\n  subscribe(nextListenerOrObserver, errorListener, completeListener) {\n    const observer = toObserver(nextListenerOrObserver, errorListener, completeListener);\n    if (this._processingStatus !== ProcessingStatus.Stopped) {\n      this.observers.add(observer);\n    } else {\n      switch (this._snapshot.status) {\n        case 'done':\n          try {\n            observer.complete?.();\n          } catch (err) {\n            reportUnhandledError(err);\n          }\n          break;\n        case 'error':\n          {\n            const err = this._snapshot.error;\n            if (!observer.error) {\n              reportUnhandledError(err);\n            } else {\n              try {\n                observer.error(err);\n              } catch (err) {\n                reportUnhandledError(err);\n              }\n            }\n            break;\n          }\n      }\n    }\n    return {\n      unsubscribe: () => {\n        this.observers.delete(observer);\n      }\n    };\n  }\n  on(type, handler) {\n    let listeners = this.eventListeners.get(type);\n    if (!listeners) {\n      listeners = new Set();\n      this.eventListeners.set(type, listeners);\n    }\n    const wrappedHandler = handler.bind(undefined);\n    listeners.add(wrappedHandler);\n    return {\n      unsubscribe: () => {\n        listeners.delete(wrappedHandler);\n      }\n    };\n  }\n\n  /** Starts the Actor from the initial state */\n  start() {\n    if (this._processingStatus === ProcessingStatus.Running) {\n      // Do not restart the service if it is already started\n      return this;\n    }\n    if (this._syncSnapshot) {\n      this.subscribe({\n        next: snapshot => {\n          if (snapshot.status === 'active') {\n            this.system._relay(this, this._parent, {\n              type: `xstate.snapshot.${this.id}`,\n              snapshot\n            });\n          }\n        },\n        error: () => {}\n      });\n    }\n    this.system._register(this.sessionId, this);\n    if (this._systemId) {\n      this.system._set(this._systemId, this);\n    }\n    this._processingStatus = ProcessingStatus.Running;\n\n    // TODO: this isn't correct when rehydrating\n    const initEvent = createInitEvent(this.options.input);\n    this.system._sendInspectionEvent({\n      type: '@xstate.event',\n      sourceRef: this._parent,\n      actorRef: this,\n      event: initEvent\n    });\n    const status = this._snapshot.status;\n    switch (status) {\n      case 'done':\n        // a state machine can be \"done\" upon initialization (it could reach a final state using initial microsteps)\n        // we still need to complete observers, flush deferreds etc\n        this.update(this._snapshot, initEvent);\n        // TODO: rethink cleanup of observers, mailbox, etc\n        return this;\n      case 'error':\n        this._error(this._snapshot.error);\n        return this;\n    }\n    if (!this._parent) {\n      this.system.start();\n    }\n    if (this.logic.start) {\n      try {\n        this.logic.start(this._snapshot, this._actorScope);\n      } catch (err) {\n        this._snapshot = {\n          ...this._snapshot,\n          status: 'error',\n          error: err\n        };\n        this._error(err);\n        return this;\n      }\n    }\n\n    // TODO: this notifies all subscribers but usually this is redundant\n    // there is no real change happening here\n    // we need to rethink if this needs to be refactored\n    this.update(this._snapshot, initEvent);\n    if (this.options.devTools) {\n      this.attachDevTools();\n    }\n    this.mailbox.start();\n    return this;\n  }\n  _process(event) {\n    let nextState;\n    let caughtError;\n    try {\n      nextState = this.logic.transition(this._snapshot, event, this._actorScope);\n    } catch (err) {\n      // we wrap it in a box so we can rethrow it later even if falsy value gets caught here\n      caughtError = {\n        err\n      };\n    }\n    if (caughtError) {\n      const {\n        err\n      } = caughtError;\n      this._snapshot = {\n        ...this._snapshot,\n        status: 'error',\n        error: err\n      };\n      this._error(err);\n      return;\n    }\n    this.update(nextState, event);\n    if (event.type === XSTATE_STOP) {\n      this._stopProcedure();\n      this._complete();\n    }\n  }\n  _stop() {\n    if (this._processingStatus === ProcessingStatus.Stopped) {\n      return this;\n    }\n    this.mailbox.clear();\n    if (this._processingStatus === ProcessingStatus.NotStarted) {\n      this._processingStatus = ProcessingStatus.Stopped;\n      return this;\n    }\n    this.mailbox.enqueue({\n      type: XSTATE_STOP\n    });\n    return this;\n  }\n\n  /** Stops the Actor and unsubscribe all listeners. */\n  stop() {\n    if (this._parent) {\n      throw new Error('A non-root actor cannot be stopped directly.');\n    }\n    return this._stop();\n  }\n  _complete() {\n    for (const observer of this.observers) {\n      try {\n        observer.complete?.();\n      } catch (err) {\n        reportUnhandledError(err);\n      }\n    }\n    this.observers.clear();\n  }\n  _reportError(err) {\n    if (!this.observers.size) {\n      if (!this._parent) {\n        reportUnhandledError(err);\n      }\n      return;\n    }\n    let reportError = false;\n    for (const observer of this.observers) {\n      const errorListener = observer.error;\n      reportError ||= !errorListener;\n      try {\n        errorListener?.(err);\n      } catch (err2) {\n        reportUnhandledError(err2);\n      }\n    }\n    this.observers.clear();\n    if (reportError) {\n      reportUnhandledError(err);\n    }\n  }\n  _error(err) {\n    this._stopProcedure();\n    this._reportError(err);\n    if (this._parent) {\n      this.system._relay(this, this._parent, createErrorActorEvent(this.id, err));\n    }\n  }\n  // TODO: atm children don't belong entirely to the actor so\n  // in a way - it's not even super aware of them\n  // so we can't stop them from here but we really should!\n  // right now, they are being stopped within the machine's transition\n  // but that could throw and leave us with \"orphaned\" active actors\n  _stopProcedure() {\n    if (this._processingStatus !== ProcessingStatus.Running) {\n      // Actor already stopped; do nothing\n      return this;\n    }\n\n    // Cancel all delayed events\n    this.system.scheduler.cancelAll(this);\n\n    // TODO: mailbox.reset\n    this.mailbox.clear();\n    // TODO: after `stop` we must prepare ourselves for receiving events again\n    // events sent *after* stop signal must be queued\n    // it seems like this should be the common behavior for all of our consumers\n    // so perhaps this should be unified somehow for all of them\n    this.mailbox = new Mailbox(this._process.bind(this));\n    this._processingStatus = ProcessingStatus.Stopped;\n    this.system._unregister(this);\n    return this;\n  }\n\n  /** @internal */\n  _send(event) {\n    if (this._processingStatus === ProcessingStatus.Stopped) {\n      return;\n    }\n    this.mailbox.enqueue(event);\n  }\n\n  /**\n   * Sends an event to the running Actor to trigger a transition.\n   *\n   * @param event The event to send\n   */\n  send(event) {\n    this.system._relay(undefined, this, event);\n  }\n  attachDevTools() {\n    const {\n      devTools\n    } = this.options;\n    if (devTools) {\n      const resolvedDevToolsAdapter = typeof devTools === 'function' ? devTools : devToolsAdapter;\n      resolvedDevToolsAdapter(this);\n    }\n  }\n  toJSON() {\n    return {\n      xstate$$type: $$ACTOR_TYPE,\n      id: this.id\n    };\n  }\n\n  /**\n   * Obtain the internal state of the actor, which can be persisted.\n   *\n   * @remarks\n   * The internal state can be persisted from any actor, not only machines.\n   *\n   * Note that the persisted state is not the same as the snapshot from\n   * {@link Actor.getSnapshot}. Persisted state represents the internal state of\n   * the actor, while snapshots represent the actor's last emitted value.\n   *\n   * Can be restored with {@link ActorOptions.state}\n   * @see https://stately.ai/docs/persistence\n   */\n\n  getPersistedSnapshot(options) {\n    return this.logic.getPersistedSnapshot(this._snapshot, options);\n  }\n  [symbolObservable]() {\n    return this;\n  }\n\n  /**\n   * Read an actor’s snapshot synchronously.\n   *\n   * @remarks\n   * The snapshot represent an actor's last emitted value.\n   *\n   * When an actor receives an event, its internal state may change. An actor\n   * may emit a snapshot when a state transition occurs.\n   *\n   * Note that some actors, such as callback actors generated with\n   * `fromCallback`, will not emit snapshots.\n   * @see {@link Actor.subscribe} to subscribe to an actor’s snapshot values.\n   * @see {@link Actor.getPersistedSnapshot} to persist the internal state of an actor (which is more than just a snapshot).\n   */\n  getSnapshot() {\n    return this._snapshot;\n  }\n}\n/**\n * Creates a new actor instance for the given actor logic with the provided\n * options, if any.\n *\n * @remarks\n * When you create an actor from actor logic via `createActor(logic)`, you\n * implicitly create an actor system where the created actor is the root actor.\n * Any actors spawned from this root actor and its descendants are part of that\n * actor system.\n * @example\n *\n * ```ts\n * import { createActor } from 'xstate';\n * import { someActorLogic } from './someActorLogic.ts';\n *\n * // Creating the actor, which implicitly creates an actor system with itself as the root actor\n * const actor = createActor(someActorLogic);\n *\n * actor.subscribe((snapshot) => {\n *   console.log(snapshot);\n * });\n *\n * // Actors must be started by calling `actor.start()`, which will also start the actor system.\n * actor.start();\n *\n * // Actors can receive events\n * actor.send({ type: 'someEvent' });\n *\n * // You can stop root actors by calling `actor.stop()`, which will also stop the actor system and all actors in that system.\n * actor.stop();\n * ```\n *\n * @param logic - The actor logic to create an actor from. For a state machine\n *   actor logic creator, see {@link createMachine}. Other actor logic creators\n *   include {@link fromCallback}, {@link fromEventObservable},\n *   {@link fromObservable}, {@link fromPromise}, and {@link fromTransition}.\n * @param options - Actor options\n */\nfunction createActor(logic, ...[options]) {\n  return new Actor(logic, options);\n}\n\n/**\n * Creates a new Interpreter instance for the given machine with the provided\n * options, if any.\n *\n * @deprecated Use `createActor` instead\n * @alias\n */\nconst interpret = createActor;\n\n/**\n * @deprecated Use `Actor` instead.\n * @alias\n */\n\nfunction resolveCancel(_, snapshot, actionArgs, actionParams, {\n  sendId\n}) {\n  const resolvedSendId = typeof sendId === 'function' ? sendId(actionArgs, actionParams) : sendId;\n  return [snapshot, {\n    sendId: resolvedSendId\n  }, undefined];\n}\nfunction executeCancel(actorScope, params) {\n  actorScope.defer(() => {\n    actorScope.system.scheduler.cancel(actorScope.self, params.sendId);\n  });\n}\n/**\n * Cancels a delayed `sendTo(...)` action that is waiting to be executed. The\n * canceled `sendTo(...)` action will not send its event or execute, unless the\n * `delay` has already elapsed before `cancel(...)` is called.\n *\n * @example\n *\n * ```ts\n * import { createMachine, sendTo, cancel } from 'xstate';\n *\n * const machine = createMachine({\n *   // ...\n *   on: {\n *     sendEvent: {\n *       actions: sendTo(\n *         'some-actor',\n *         { type: 'someEvent' },\n *         {\n *           id: 'some-id',\n *           delay: 1000\n *         }\n *       )\n *     },\n *     cancelEvent: {\n *       actions: cancel('some-id')\n *     }\n *   }\n * });\n * ```\n *\n * @param sendId The `id` of the `sendTo(...)` action to cancel.\n */\nfunction cancel(sendId) {\n  function cancel(_args, _params) {\n  }\n  cancel.type = 'xstate.cancel';\n  cancel.sendId = sendId;\n  cancel.resolve = resolveCancel;\n  cancel.execute = executeCancel;\n  return cancel;\n}\n\nfunction resolveSpawn(actorScope, snapshot, actionArgs, _actionParams, {\n  id,\n  systemId,\n  src,\n  input,\n  syncSnapshot\n}) {\n  const logic = typeof src === 'string' ? resolveReferencedActor(snapshot.machine, src) : src;\n  const resolvedId = typeof id === 'function' ? id(actionArgs) : id;\n  let actorRef;\n  let resolvedInput = undefined;\n  if (logic) {\n    resolvedInput = typeof input === 'function' ? input({\n      context: snapshot.context,\n      event: actionArgs.event,\n      self: actorScope.self\n    }) : input;\n    actorRef = createActor(logic, {\n      id: resolvedId,\n      src,\n      parent: actorScope.self,\n      syncSnapshot,\n      systemId,\n      input: resolvedInput\n    });\n  }\n  return [cloneMachineSnapshot(snapshot, {\n    children: {\n      ...snapshot.children,\n      [resolvedId]: actorRef\n    }\n  }), {\n    id,\n    systemId,\n    actorRef,\n    src,\n    input: resolvedInput\n  }, undefined];\n}\nfunction executeSpawn(actorScope, {\n  actorRef\n}) {\n  if (!actorRef) {\n    return;\n  }\n  actorScope.defer(() => {\n    if (actorRef._processingStatus === ProcessingStatus.Stopped) {\n      return;\n    }\n    actorRef.start();\n  });\n}\nfunction spawnChild(...[src, {\n  id,\n  systemId,\n  input,\n  syncSnapshot = false\n} = {}]) {\n  function spawnChild(_args, _params) {\n  }\n  spawnChild.type = 'xstate.spawnChild';\n  spawnChild.id = id;\n  spawnChild.systemId = systemId;\n  spawnChild.src = src;\n  spawnChild.input = input;\n  spawnChild.syncSnapshot = syncSnapshot;\n  spawnChild.resolve = resolveSpawn;\n  spawnChild.execute = executeSpawn;\n  return spawnChild;\n}\n\nfunction resolveStop(_, snapshot, args, actionParams, {\n  actorRef\n}) {\n  const actorRefOrString = typeof actorRef === 'function' ? actorRef(args, actionParams) : actorRef;\n  const resolvedActorRef = typeof actorRefOrString === 'string' ? snapshot.children[actorRefOrString] : actorRefOrString;\n  let children = snapshot.children;\n  if (resolvedActorRef) {\n    children = {\n      ...children\n    };\n    delete children[resolvedActorRef.id];\n  }\n  return [cloneMachineSnapshot(snapshot, {\n    children\n  }), resolvedActorRef, undefined];\n}\nfunction executeStop(actorScope, actorRef) {\n  if (!actorRef) {\n    return;\n  }\n\n  // we need to eagerly unregister it here so a new actor with the same systemId can be registered immediately\n  // since we defer actual stopping of the actor but we don't defer actor creations (and we can't do that)\n  // this could throw on `systemId` collision, for example, when dealing with reentering transitions\n  actorScope.system._unregister(actorRef);\n\n  // this allows us to prevent an actor from being started if it gets stopped within the same macrostep\n  // this can happen, for example, when the invoking state is being exited immediately by an always transition\n  if (actorRef._processingStatus !== ProcessingStatus.Running) {\n    actorScope.stopChild(actorRef);\n    return;\n  }\n  // stopping a child enqueues a stop event in the child actor's mailbox\n  // we need for all of the already enqueued events to be processed before we stop the child\n  // the parent itself might want to send some events to a child (for example from exit actions on the invoking state)\n  // and we don't want to ignore those events\n  actorScope.defer(() => {\n    actorScope.stopChild(actorRef);\n  });\n}\n/**\n * Stops a child actor.\n *\n * @param actorRef The actor to stop.\n */\nfunction stopChild(actorRef) {\n  function stop(_args, _params) {\n  }\n  stop.type = 'xstate.stopChild';\n  stop.actorRef = actorRef;\n  stop.resolve = resolveStop;\n  stop.execute = executeStop;\n  return stop;\n}\n\n/**\n * Stops a child actor.\n *\n * @deprecated Use `stopChild(...)` instead\n * @alias\n */\nconst stop = stopChild;\n\nfunction checkStateIn(snapshot, _, {\n  stateValue\n}) {\n  if (typeof stateValue === 'string' && isStateId(stateValue)) {\n    const target = snapshot.machine.getStateNodeById(stateValue);\n    return snapshot._nodes.some(sn => sn === target);\n  }\n  return snapshot.matches(stateValue);\n}\nfunction stateIn(stateValue) {\n  function stateIn() {\n    return false;\n  }\n  stateIn.check = checkStateIn;\n  stateIn.stateValue = stateValue;\n  return stateIn;\n}\nfunction checkNot(snapshot, {\n  context,\n  event\n}, {\n  guards\n}) {\n  return !evaluateGuard(guards[0], context, event, snapshot);\n}\n\n/**\n * Higher-order guard that evaluates to `true` if the `guard` passed to it\n * evaluates to `false`.\n *\n * @category Guards\n * @example\n *\n * ```ts\n * import { setup, not } from 'xstate';\n *\n * const machine = setup({\n *   guards: {\n *     someNamedGuard: () => false\n *   }\n * }).createMachine({\n *   on: {\n *     someEvent: {\n *       guard: not('someNamedGuard'),\n *       actions: () => {\n *         // will be executed if guard in `not(...)`\n *         // evaluates to `false`\n *       }\n *     }\n *   }\n * });\n * ```\n *\n * @returns A guard\n */\nfunction not(guard) {\n  function not(_args, _params) {\n    return false;\n  }\n  not.check = checkNot;\n  not.guards = [guard];\n  return not;\n}\nfunction checkAnd(snapshot, {\n  context,\n  event\n}, {\n  guards\n}) {\n  return guards.every(guard => evaluateGuard(guard, context, event, snapshot));\n}\n\n/**\n * Higher-order guard that evaluates to `true` if all `guards` passed to it\n * evaluate to `true`.\n *\n * @category Guards\n * @example\n *\n * ```ts\n * import { setup, and } from 'xstate';\n *\n * const machine = setup({\n *   guards: {\n *     someNamedGuard: () => true\n *   }\n * }).createMachine({\n *   on: {\n *     someEvent: {\n *       guard: and([({ context }) => context.value > 0, 'someNamedGuard']),\n *       actions: () => {\n *         // will be executed if all guards in `and(...)`\n *         // evaluate to true\n *       }\n *     }\n *   }\n * });\n * ```\n *\n * @returns A guard action object\n */\nfunction and(guards) {\n  function and(_args, _params) {\n    return false;\n  }\n  and.check = checkAnd;\n  and.guards = guards;\n  return and;\n}\nfunction checkOr(snapshot, {\n  context,\n  event\n}, {\n  guards\n}) {\n  return guards.some(guard => evaluateGuard(guard, context, event, snapshot));\n}\n\n/**\n * Higher-order guard that evaluates to `true` if any of the `guards` passed to\n * it evaluate to `true`.\n *\n * @category Guards\n * @example\n *\n * ```ts\n * import { setup, or } from 'xstate';\n *\n * const machine = setup({\n *   guards: {\n *     someNamedGuard: () => true\n *   }\n * }).createMachine({\n *   on: {\n *     someEvent: {\n *       guard: or([({ context }) => context.value > 0, 'someNamedGuard']),\n *       actions: () => {\n *         // will be executed if any of the guards in `or(...)`\n *         // evaluate to true\n *       }\n *     }\n *   }\n * });\n * ```\n *\n * @returns A guard action object\n */\nfunction or(guards) {\n  function or(_args, _params) {\n    return false;\n  }\n  or.check = checkOr;\n  or.guards = guards;\n  return or;\n}\n\n// TODO: throw on cycles (depth check should be enough)\nfunction evaluateGuard(guard, context, event, snapshot) {\n  const {\n    machine\n  } = snapshot;\n  const isInline = typeof guard === 'function';\n  const resolved = isInline ? guard : machine.implementations.guards[typeof guard === 'string' ? guard : guard.type];\n  if (!isInline && !resolved) {\n    throw new Error(`Guard '${typeof guard === 'string' ? guard : guard.type}' is not implemented.'.`);\n  }\n  if (typeof resolved !== 'function') {\n    return evaluateGuard(resolved, context, event, snapshot);\n  }\n  const guardArgs = {\n    context,\n    event\n  };\n  const guardParams = isInline || typeof guard === 'string' ? undefined : 'params' in guard ? typeof guard.params === 'function' ? guard.params({\n    context,\n    event\n  }) : guard.params : undefined;\n  if (!('check' in resolved)) {\n    // the existing type of `.guards` assumes non-nullable `TExpressionGuard`\n    // inline guards expect `TExpressionGuard` to be set to `undefined`\n    // it's fine to cast this here, our logic makes sure that we call those 2 \"variants\" correctly\n    return resolved(guardArgs, guardParams);\n  }\n  const builtinGuard = resolved;\n  return builtinGuard.check(snapshot, guardArgs, resolved // this holds all params\n  );\n}\n\nconst isAtomicStateNode = stateNode => stateNode.type === 'atomic' || stateNode.type === 'final';\nfunction getChildren(stateNode) {\n  return Object.values(stateNode.states).filter(sn => sn.type !== 'history');\n}\nfunction getProperAncestors(stateNode, toStateNode) {\n  const ancestors = [];\n  if (toStateNode === stateNode) {\n    return ancestors;\n  }\n\n  // add all ancestors\n  let m = stateNode.parent;\n  while (m && m !== toStateNode) {\n    ancestors.push(m);\n    m = m.parent;\n  }\n  return ancestors;\n}\nfunction getAllStateNodes(stateNodes) {\n  const nodeSet = new Set(stateNodes);\n  const adjList = getAdjList(nodeSet);\n\n  // add descendants\n  for (const s of nodeSet) {\n    // if previously active, add existing child nodes\n    if (s.type === 'compound' && (!adjList.get(s) || !adjList.get(s).length)) {\n      getInitialStateNodesWithTheirAncestors(s).forEach(sn => nodeSet.add(sn));\n    } else {\n      if (s.type === 'parallel') {\n        for (const child of getChildren(s)) {\n          if (child.type === 'history') {\n            continue;\n          }\n          if (!nodeSet.has(child)) {\n            const initialStates = getInitialStateNodesWithTheirAncestors(child);\n            for (const initialStateNode of initialStates) {\n              nodeSet.add(initialStateNode);\n            }\n          }\n        }\n      }\n    }\n  }\n\n  // add all ancestors\n  for (const s of nodeSet) {\n    let m = s.parent;\n    while (m) {\n      nodeSet.add(m);\n      m = m.parent;\n    }\n  }\n  return nodeSet;\n}\nfunction getValueFromAdj(baseNode, adjList) {\n  const childStateNodes = adjList.get(baseNode);\n  if (!childStateNodes) {\n    return {}; // todo: fix?\n  }\n  if (baseNode.type === 'compound') {\n    const childStateNode = childStateNodes[0];\n    if (childStateNode) {\n      if (isAtomicStateNode(childStateNode)) {\n        return childStateNode.key;\n      }\n    } else {\n      return {};\n    }\n  }\n  const stateValue = {};\n  for (const childStateNode of childStateNodes) {\n    stateValue[childStateNode.key] = getValueFromAdj(childStateNode, adjList);\n  }\n  return stateValue;\n}\nfunction getAdjList(stateNodes) {\n  const adjList = new Map();\n  for (const s of stateNodes) {\n    if (!adjList.has(s)) {\n      adjList.set(s, []);\n    }\n    if (s.parent) {\n      if (!adjList.has(s.parent)) {\n        adjList.set(s.parent, []);\n      }\n      adjList.get(s.parent).push(s);\n    }\n  }\n  return adjList;\n}\nfunction getStateValue(rootNode, stateNodes) {\n  const config = getAllStateNodes(stateNodes);\n  return getValueFromAdj(rootNode, getAdjList(config));\n}\nfunction isInFinalState(stateNodeSet, stateNode) {\n  if (stateNode.type === 'compound') {\n    return getChildren(stateNode).some(s => s.type === 'final' && stateNodeSet.has(s));\n  }\n  if (stateNode.type === 'parallel') {\n    return getChildren(stateNode).every(sn => isInFinalState(stateNodeSet, sn));\n  }\n  return stateNode.type === 'final';\n}\nconst isStateId = str => str[0] === STATE_IDENTIFIER;\nfunction getCandidates(stateNode, receivedEventType) {\n  const candidates = stateNode.transitions.get(receivedEventType) || [...stateNode.transitions.keys()].filter(eventDescriptor => {\n    // check if transition is a wildcard transition,\n    // which matches any non-transient events\n    if (eventDescriptor === WILDCARD) {\n      return true;\n    }\n    if (!eventDescriptor.endsWith('.*')) {\n      return false;\n    }\n    const partialEventTokens = eventDescriptor.split('.');\n    const eventTokens = receivedEventType.split('.');\n    for (let tokenIndex = 0; tokenIndex < partialEventTokens.length; tokenIndex++) {\n      const partialEventToken = partialEventTokens[tokenIndex];\n      const eventToken = eventTokens[tokenIndex];\n      if (partialEventToken === '*') {\n        const isLastToken = tokenIndex === partialEventTokens.length - 1;\n        return isLastToken;\n      }\n      if (partialEventToken !== eventToken) {\n        return false;\n      }\n    }\n    return true;\n  }).sort((a, b) => b.length - a.length).flatMap(key => stateNode.transitions.get(key));\n  return candidates;\n}\n\n/** All delayed transitions from the config. */\nfunction getDelayedTransitions(stateNode) {\n  const afterConfig = stateNode.config.after;\n  if (!afterConfig) {\n    return [];\n  }\n  const mutateEntryExit = delay => {\n    const afterEvent = createAfterEvent(delay, stateNode.id);\n    const eventType = afterEvent.type;\n    stateNode.entry.push(raise(afterEvent, {\n      id: eventType,\n      delay\n    }));\n    stateNode.exit.push(cancel(eventType));\n    return eventType;\n  };\n  const delayedTransitions = Object.keys(afterConfig).flatMap(delay => {\n    const configTransition = afterConfig[delay];\n    const resolvedTransition = typeof configTransition === 'string' ? {\n      target: configTransition\n    } : configTransition;\n    const resolvedDelay = Number.isNaN(+delay) ? delay : +delay;\n    const eventType = mutateEntryExit(resolvedDelay);\n    return toArray(resolvedTransition).map(transition => ({\n      ...transition,\n      event: eventType,\n      delay: resolvedDelay\n    }));\n  });\n  return delayedTransitions.map(delayedTransition => {\n    const {\n      delay\n    } = delayedTransition;\n    return {\n      ...formatTransition(stateNode, delayedTransition.event, delayedTransition),\n      delay\n    };\n  });\n}\nfunction formatTransition(stateNode, descriptor, transitionConfig) {\n  const normalizedTarget = normalizeTarget(transitionConfig.target);\n  const reenter = transitionConfig.reenter ?? false;\n  const target = resolveTarget(stateNode, normalizedTarget);\n  const transition = {\n    ...transitionConfig,\n    actions: toArray(transitionConfig.actions),\n    guard: transitionConfig.guard,\n    target,\n    source: stateNode,\n    reenter,\n    eventType: descriptor,\n    toJSON: () => ({\n      ...transition,\n      source: `#${stateNode.id}`,\n      target: target ? target.map(t => `#${t.id}`) : undefined\n    })\n  };\n  return transition;\n}\nfunction formatTransitions(stateNode) {\n  const transitions = new Map();\n  if (stateNode.config.on) {\n    for (const descriptor of Object.keys(stateNode.config.on)) {\n      if (descriptor === NULL_EVENT) {\n        throw new Error('Null events (\"\") cannot be specified as a transition key. Use `always: { ... }` instead.');\n      }\n      const transitionsConfig = stateNode.config.on[descriptor];\n      transitions.set(descriptor, toTransitionConfigArray(transitionsConfig).map(t => formatTransition(stateNode, descriptor, t)));\n    }\n  }\n  if (stateNode.config.onDone) {\n    const descriptor = `xstate.done.state.${stateNode.id}`;\n    transitions.set(descriptor, toTransitionConfigArray(stateNode.config.onDone).map(t => formatTransition(stateNode, descriptor, t)));\n  }\n  for (const invokeDef of stateNode.invoke) {\n    if (invokeDef.onDone) {\n      const descriptor = `xstate.done.actor.${invokeDef.id}`;\n      transitions.set(descriptor, toTransitionConfigArray(invokeDef.onDone).map(t => formatTransition(stateNode, descriptor, t)));\n    }\n    if (invokeDef.onError) {\n      const descriptor = `xstate.error.actor.${invokeDef.id}`;\n      transitions.set(descriptor, toTransitionConfigArray(invokeDef.onError).map(t => formatTransition(stateNode, descriptor, t)));\n    }\n    if (invokeDef.onSnapshot) {\n      const descriptor = `xstate.snapshot.${invokeDef.id}`;\n      transitions.set(descriptor, toTransitionConfigArray(invokeDef.onSnapshot).map(t => formatTransition(stateNode, descriptor, t)));\n    }\n  }\n  for (const delayedTransition of stateNode.after) {\n    let existing = transitions.get(delayedTransition.eventType);\n    if (!existing) {\n      existing = [];\n      transitions.set(delayedTransition.eventType, existing);\n    }\n    existing.push(delayedTransition);\n  }\n  return transitions;\n}\nfunction formatInitialTransition(stateNode, _target) {\n  const resolvedTarget = typeof _target === 'string' ? stateNode.states[_target] : _target ? stateNode.states[_target.target] : undefined;\n  if (!resolvedTarget && _target) {\n    throw new Error(\n    // eslint-disable-next-line @typescript-eslint/restrict-template-expressions, @typescript-eslint/no-base-to-string\n    `Initial state node \"${_target}\" not found on parent state node #${stateNode.id}`);\n  }\n  const transition = {\n    source: stateNode,\n    actions: !_target || typeof _target === 'string' ? [] : toArray(_target.actions),\n    eventType: null,\n    reenter: false,\n    target: resolvedTarget ? [resolvedTarget] : [],\n    toJSON: () => ({\n      ...transition,\n      source: `#${stateNode.id}`,\n      target: resolvedTarget ? [`#${resolvedTarget.id}`] : []\n    })\n  };\n  return transition;\n}\nfunction resolveTarget(stateNode, targets) {\n  if (targets === undefined) {\n    // an undefined target signals that the state node should not transition from that state when receiving that event\n    return undefined;\n  }\n  return targets.map(target => {\n    if (typeof target !== 'string') {\n      return target;\n    }\n    if (isStateId(target)) {\n      return stateNode.machine.getStateNodeById(target);\n    }\n    const isInternalTarget = target[0] === STATE_DELIMITER;\n    // If internal target is defined on machine,\n    // do not include machine key on target\n    if (isInternalTarget && !stateNode.parent) {\n      return getStateNodeByPath(stateNode, target.slice(1));\n    }\n    const resolvedTarget = isInternalTarget ? stateNode.key + target : target;\n    if (stateNode.parent) {\n      try {\n        const targetStateNode = getStateNodeByPath(stateNode.parent, resolvedTarget);\n        return targetStateNode;\n      } catch (err) {\n        throw new Error(`Invalid transition definition for state node '${stateNode.id}':\\n${err.message}`);\n      }\n    } else {\n      throw new Error(`Invalid target: \"${target}\" is not a valid target from the root node. Did you mean \".${target}\"?`);\n    }\n  });\n}\nfunction resolveHistoryDefaultTransition(stateNode) {\n  const normalizedTarget = normalizeTarget(stateNode.config.target);\n  if (!normalizedTarget) {\n    return stateNode.parent.initial;\n  }\n  return {\n    target: normalizedTarget.map(t => typeof t === 'string' ? getStateNodeByPath(stateNode.parent, t) : t)\n  };\n}\nfunction isHistoryNode(stateNode) {\n  return stateNode.type === 'history';\n}\nfunction getInitialStateNodesWithTheirAncestors(stateNode) {\n  const states = getInitialStateNodes(stateNode);\n  for (const initialState of states) {\n    for (const ancestor of getProperAncestors(initialState, stateNode)) {\n      states.add(ancestor);\n    }\n  }\n  return states;\n}\nfunction getInitialStateNodes(stateNode) {\n  const set = new Set();\n  function iter(descStateNode) {\n    if (set.has(descStateNode)) {\n      return;\n    }\n    set.add(descStateNode);\n    if (descStateNode.type === 'compound') {\n      iter(descStateNode.initial.target[0]);\n    } else if (descStateNode.type === 'parallel') {\n      for (const child of getChildren(descStateNode)) {\n        iter(child);\n      }\n    }\n  }\n  iter(stateNode);\n  return set;\n}\n/** Returns the child state node from its relative `stateKey`, or throws. */\nfunction getStateNode(stateNode, stateKey) {\n  if (isStateId(stateKey)) {\n    return stateNode.machine.getStateNodeById(stateKey);\n  }\n  if (!stateNode.states) {\n    throw new Error(`Unable to retrieve child state '${stateKey}' from '${stateNode.id}'; no child states exist.`);\n  }\n  const result = stateNode.states[stateKey];\n  if (!result) {\n    throw new Error(`Child state '${stateKey}' does not exist on '${stateNode.id}'`);\n  }\n  return result;\n}\n\n/**\n * Returns the relative state node from the given `statePath`, or throws.\n *\n * @param statePath The string or string array relative path to the state node.\n */\nfunction getStateNodeByPath(stateNode, statePath) {\n  if (typeof statePath === 'string' && isStateId(statePath)) {\n    try {\n      return stateNode.machine.getStateNodeById(statePath);\n    } catch {\n      // try individual paths\n      // throw e;\n    }\n  }\n  const arrayStatePath = toStatePath(statePath).slice();\n  let currentStateNode = stateNode;\n  while (arrayStatePath.length) {\n    const key = arrayStatePath.shift();\n    if (!key.length) {\n      break;\n    }\n    currentStateNode = getStateNode(currentStateNode, key);\n  }\n  return currentStateNode;\n}\n\n/**\n * Returns the state nodes represented by the current state value.\n *\n * @param stateValue The state value or State instance\n */\nfunction getStateNodes(stateNode, stateValue) {\n  if (typeof stateValue === 'string') {\n    const childStateNode = stateNode.states[stateValue];\n    if (!childStateNode) {\n      throw new Error(`State '${stateValue}' does not exist on '${stateNode.id}'`);\n    }\n    return [stateNode, childStateNode];\n  }\n  const childStateKeys = Object.keys(stateValue);\n  const childStateNodes = childStateKeys.map(subStateKey => getStateNode(stateNode, subStateKey)).filter(Boolean);\n  return [stateNode.machine.root, stateNode].concat(childStateNodes, childStateKeys.reduce((allSubStateNodes, subStateKey) => {\n    const subStateNode = getStateNode(stateNode, subStateKey);\n    if (!subStateNode) {\n      return allSubStateNodes;\n    }\n    const subStateNodes = getStateNodes(subStateNode, stateValue[subStateKey]);\n    return allSubStateNodes.concat(subStateNodes);\n  }, []));\n}\nfunction transitionAtomicNode(stateNode, stateValue, snapshot, event) {\n  const childStateNode = getStateNode(stateNode, stateValue);\n  const next = childStateNode.next(snapshot, event);\n  if (!next || !next.length) {\n    return stateNode.next(snapshot, event);\n  }\n  return next;\n}\nfunction transitionCompoundNode(stateNode, stateValue, snapshot, event) {\n  const subStateKeys = Object.keys(stateValue);\n  const childStateNode = getStateNode(stateNode, subStateKeys[0]);\n  const next = transitionNode(childStateNode, stateValue[subStateKeys[0]], snapshot, event);\n  if (!next || !next.length) {\n    return stateNode.next(snapshot, event);\n  }\n  return next;\n}\nfunction transitionParallelNode(stateNode, stateValue, snapshot, event) {\n  const allInnerTransitions = [];\n  for (const subStateKey of Object.keys(stateValue)) {\n    const subStateValue = stateValue[subStateKey];\n    if (!subStateValue) {\n      continue;\n    }\n    const subStateNode = getStateNode(stateNode, subStateKey);\n    const innerTransitions = transitionNode(subStateNode, subStateValue, snapshot, event);\n    if (innerTransitions) {\n      allInnerTransitions.push(...innerTransitions);\n    }\n  }\n  if (!allInnerTransitions.length) {\n    return stateNode.next(snapshot, event);\n  }\n  return allInnerTransitions;\n}\nfunction transitionNode(stateNode, stateValue, snapshot, event) {\n  // leaf node\n  if (typeof stateValue === 'string') {\n    return transitionAtomicNode(stateNode, stateValue, snapshot, event);\n  }\n\n  // compound node\n  if (Object.keys(stateValue).length === 1) {\n    return transitionCompoundNode(stateNode, stateValue, snapshot, event);\n  }\n\n  // parallel node\n  return transitionParallelNode(stateNode, stateValue, snapshot, event);\n}\nfunction getHistoryNodes(stateNode) {\n  return Object.keys(stateNode.states).map(key => stateNode.states[key]).filter(sn => sn.type === 'history');\n}\nfunction isDescendant(childStateNode, parentStateNode) {\n  let marker = childStateNode;\n  while (marker.parent && marker.parent !== parentStateNode) {\n    marker = marker.parent;\n  }\n  return marker.parent === parentStateNode;\n}\nfunction hasIntersection(s1, s2) {\n  const set1 = new Set(s1);\n  const set2 = new Set(s2);\n  for (const item of set1) {\n    if (set2.has(item)) {\n      return true;\n    }\n  }\n  for (const item of set2) {\n    if (set1.has(item)) {\n      return true;\n    }\n  }\n  return false;\n}\nfunction removeConflictingTransitions(enabledTransitions, stateNodeSet, historyValue) {\n  const filteredTransitions = new Set();\n  for (const t1 of enabledTransitions) {\n    let t1Preempted = false;\n    const transitionsToRemove = new Set();\n    for (const t2 of filteredTransitions) {\n      if (hasIntersection(computeExitSet([t1], stateNodeSet, historyValue), computeExitSet([t2], stateNodeSet, historyValue))) {\n        if (isDescendant(t1.source, t2.source)) {\n          transitionsToRemove.add(t2);\n        } else {\n          t1Preempted = true;\n          break;\n        }\n      }\n    }\n    if (!t1Preempted) {\n      for (const t3 of transitionsToRemove) {\n        filteredTransitions.delete(t3);\n      }\n      filteredTransitions.add(t1);\n    }\n  }\n  return Array.from(filteredTransitions);\n}\nfunction findLeastCommonAncestor(stateNodes) {\n  const [head, ...tail] = stateNodes;\n  for (const ancestor of getProperAncestors(head, undefined)) {\n    if (tail.every(sn => isDescendant(sn, ancestor))) {\n      return ancestor;\n    }\n  }\n}\nfunction getEffectiveTargetStates(transition, historyValue) {\n  if (!transition.target) {\n    return [];\n  }\n  const targets = new Set();\n  for (const targetNode of transition.target) {\n    if (isHistoryNode(targetNode)) {\n      if (historyValue[targetNode.id]) {\n        for (const node of historyValue[targetNode.id]) {\n          targets.add(node);\n        }\n      } else {\n        for (const node of getEffectiveTargetStates(resolveHistoryDefaultTransition(targetNode), historyValue)) {\n          targets.add(node);\n        }\n      }\n    } else {\n      targets.add(targetNode);\n    }\n  }\n  return [...targets];\n}\nfunction getTransitionDomain(transition, historyValue) {\n  const targetStates = getEffectiveTargetStates(transition, historyValue);\n  if (!targetStates) {\n    return;\n  }\n  if (!transition.reenter && targetStates.every(target => target === transition.source || isDescendant(target, transition.source))) {\n    return transition.source;\n  }\n  const lca = findLeastCommonAncestor(targetStates.concat(transition.source));\n  if (lca) {\n    return lca;\n  }\n\n  // at this point we know that it's a root transition since LCA couldn't be found\n  if (transition.reenter) {\n    return;\n  }\n  return transition.source.machine.root;\n}\nfunction computeExitSet(transitions, stateNodeSet, historyValue) {\n  const statesToExit = new Set();\n  for (const t of transitions) {\n    if (t.target?.length) {\n      const domain = getTransitionDomain(t, historyValue);\n      if (t.reenter && t.source === domain) {\n        statesToExit.add(domain);\n      }\n      for (const stateNode of stateNodeSet) {\n        if (isDescendant(stateNode, domain)) {\n          statesToExit.add(stateNode);\n        }\n      }\n    }\n  }\n  return [...statesToExit];\n}\nfunction areStateNodeCollectionsEqual(prevStateNodes, nextStateNodeSet) {\n  if (prevStateNodes.length !== nextStateNodeSet.size) {\n    return false;\n  }\n  for (const node of prevStateNodes) {\n    if (!nextStateNodeSet.has(node)) {\n      return false;\n    }\n  }\n  return true;\n}\n\n/** https://www.w3.org/TR/scxml/#microstepProcedure */\nfunction microstep(transitions, currentSnapshot, actorScope, event, isInitial, internalQueue) {\n  if (!transitions.length) {\n    return currentSnapshot;\n  }\n  const mutStateNodeSet = new Set(currentSnapshot._nodes);\n  let historyValue = currentSnapshot.historyValue;\n  const filteredTransitions = removeConflictingTransitions(transitions, mutStateNodeSet, historyValue);\n  let nextState = currentSnapshot;\n\n  // Exit states\n  if (!isInitial) {\n    [nextState, historyValue] = exitStates(nextState, event, actorScope, filteredTransitions, mutStateNodeSet, historyValue, internalQueue, actorScope.actionExecutor);\n  }\n\n  // Execute transition content\n  nextState = resolveActionsAndContext(nextState, event, actorScope, filteredTransitions.flatMap(t => t.actions), internalQueue, undefined);\n\n  // Enter states\n  nextState = enterStates(nextState, event, actorScope, filteredTransitions, mutStateNodeSet, internalQueue, historyValue, isInitial);\n  const nextStateNodes = [...mutStateNodeSet];\n  if (nextState.status === 'done') {\n    nextState = resolveActionsAndContext(nextState, event, actorScope, nextStateNodes.sort((a, b) => b.order - a.order).flatMap(state => state.exit), internalQueue, undefined);\n  }\n\n  // eslint-disable-next-line no-useless-catch\n  try {\n    if (historyValue === currentSnapshot.historyValue && areStateNodeCollectionsEqual(currentSnapshot._nodes, mutStateNodeSet)) {\n      return nextState;\n    }\n    return cloneMachineSnapshot(nextState, {\n      _nodes: nextStateNodes,\n      historyValue\n    });\n  } catch (e) {\n    // TODO: Refactor this once proper error handling is implemented.\n    // See https://github.com/statelyai/rfcs/pull/4\n    throw e;\n  }\n}\nfunction getMachineOutput(snapshot, event, actorScope, rootNode, rootCompletionNode) {\n  if (rootNode.output === undefined) {\n    return;\n  }\n  const doneStateEvent = createDoneStateEvent(rootCompletionNode.id, rootCompletionNode.output !== undefined && rootCompletionNode.parent ? resolveOutput(rootCompletionNode.output, snapshot.context, event, actorScope.self) : undefined);\n  return resolveOutput(rootNode.output, snapshot.context, doneStateEvent, actorScope.self);\n}\nfunction enterStates(currentSnapshot, event, actorScope, filteredTransitions, mutStateNodeSet, internalQueue, historyValue, isInitial) {\n  let nextSnapshot = currentSnapshot;\n  const statesToEnter = new Set();\n  // those are states that were directly targeted or indirectly targeted by the explicit target\n  // in other words, those are states for which initial actions should be executed\n  // when we target `#deep_child` initial actions of its ancestors shouldn't be executed\n  const statesForDefaultEntry = new Set();\n  computeEntrySet(filteredTransitions, historyValue, statesForDefaultEntry, statesToEnter);\n\n  // In the initial state, the root state node is \"entered\".\n  if (isInitial) {\n    statesForDefaultEntry.add(currentSnapshot.machine.root);\n  }\n  const completedNodes = new Set();\n  for (const stateNodeToEnter of [...statesToEnter].sort((a, b) => a.order - b.order)) {\n    mutStateNodeSet.add(stateNodeToEnter);\n    const actions = [];\n\n    // Add entry actions\n    actions.push(...stateNodeToEnter.entry);\n    for (const invokeDef of stateNodeToEnter.invoke) {\n      actions.push(spawnChild(invokeDef.src, {\n        ...invokeDef,\n        syncSnapshot: !!invokeDef.onSnapshot\n      }));\n    }\n    if (statesForDefaultEntry.has(stateNodeToEnter)) {\n      const initialActions = stateNodeToEnter.initial.actions;\n      actions.push(...initialActions);\n    }\n    nextSnapshot = resolveActionsAndContext(nextSnapshot, event, actorScope, actions, internalQueue, stateNodeToEnter.invoke.map(invokeDef => invokeDef.id));\n    if (stateNodeToEnter.type === 'final') {\n      const parent = stateNodeToEnter.parent;\n      let ancestorMarker = parent?.type === 'parallel' ? parent : parent?.parent;\n      let rootCompletionNode = ancestorMarker || stateNodeToEnter;\n      if (parent?.type === 'compound') {\n        internalQueue.push(createDoneStateEvent(parent.id, stateNodeToEnter.output !== undefined ? resolveOutput(stateNodeToEnter.output, nextSnapshot.context, event, actorScope.self) : undefined));\n      }\n      while (ancestorMarker?.type === 'parallel' && !completedNodes.has(ancestorMarker) && isInFinalState(mutStateNodeSet, ancestorMarker)) {\n        completedNodes.add(ancestorMarker);\n        internalQueue.push(createDoneStateEvent(ancestorMarker.id));\n        rootCompletionNode = ancestorMarker;\n        ancestorMarker = ancestorMarker.parent;\n      }\n      if (ancestorMarker) {\n        continue;\n      }\n      nextSnapshot = cloneMachineSnapshot(nextSnapshot, {\n        status: 'done',\n        output: getMachineOutput(nextSnapshot, event, actorScope, nextSnapshot.machine.root, rootCompletionNode)\n      });\n    }\n  }\n  return nextSnapshot;\n}\nfunction computeEntrySet(transitions, historyValue, statesForDefaultEntry, statesToEnter) {\n  for (const t of transitions) {\n    const domain = getTransitionDomain(t, historyValue);\n    for (const s of t.target || []) {\n      if (!isHistoryNode(s) && (\n      // if the target is different than the source then it will *definitely* be entered\n      t.source !== s ||\n      // we know that the domain can't lie within the source\n      // if it's different than the source then it's outside of it and it means that the target has to be entered as well\n      t.source !== domain ||\n      // reentering transitions always enter the target, even if it's the source itself\n      t.reenter)) {\n        statesToEnter.add(s);\n        statesForDefaultEntry.add(s);\n      }\n      addDescendantStatesToEnter(s, historyValue, statesForDefaultEntry, statesToEnter);\n    }\n    const targetStates = getEffectiveTargetStates(t, historyValue);\n    for (const s of targetStates) {\n      const ancestors = getProperAncestors(s, domain);\n      if (domain?.type === 'parallel') {\n        ancestors.push(domain);\n      }\n      addAncestorStatesToEnter(statesToEnter, historyValue, statesForDefaultEntry, ancestors, !t.source.parent && t.reenter ? undefined : domain);\n    }\n  }\n}\nfunction addDescendantStatesToEnter(stateNode, historyValue, statesForDefaultEntry, statesToEnter) {\n  if (isHistoryNode(stateNode)) {\n    if (historyValue[stateNode.id]) {\n      const historyStateNodes = historyValue[stateNode.id];\n      for (const s of historyStateNodes) {\n        statesToEnter.add(s);\n        addDescendantStatesToEnter(s, historyValue, statesForDefaultEntry, statesToEnter);\n      }\n      for (const s of historyStateNodes) {\n        addProperAncestorStatesToEnter(s, stateNode.parent, statesToEnter, historyValue, statesForDefaultEntry);\n      }\n    } else {\n      const historyDefaultTransition = resolveHistoryDefaultTransition(stateNode);\n      for (const s of historyDefaultTransition.target) {\n        statesToEnter.add(s);\n        if (historyDefaultTransition === stateNode.parent?.initial) {\n          statesForDefaultEntry.add(stateNode.parent);\n        }\n        addDescendantStatesToEnter(s, historyValue, statesForDefaultEntry, statesToEnter);\n      }\n      for (const s of historyDefaultTransition.target) {\n        addProperAncestorStatesToEnter(s, stateNode.parent, statesToEnter, historyValue, statesForDefaultEntry);\n      }\n    }\n  } else {\n    if (stateNode.type === 'compound') {\n      const [initialState] = stateNode.initial.target;\n      if (!isHistoryNode(initialState)) {\n        statesToEnter.add(initialState);\n        statesForDefaultEntry.add(initialState);\n      }\n      addDescendantStatesToEnter(initialState, historyValue, statesForDefaultEntry, statesToEnter);\n      addProperAncestorStatesToEnter(initialState, stateNode, statesToEnter, historyValue, statesForDefaultEntry);\n    } else {\n      if (stateNode.type === 'parallel') {\n        for (const child of getChildren(stateNode).filter(sn => !isHistoryNode(sn))) {\n          if (![...statesToEnter].some(s => isDescendant(s, child))) {\n            if (!isHistoryNode(child)) {\n              statesToEnter.add(child);\n              statesForDefaultEntry.add(child);\n            }\n            addDescendantStatesToEnter(child, historyValue, statesForDefaultEntry, statesToEnter);\n          }\n        }\n      }\n    }\n  }\n}\nfunction addAncestorStatesToEnter(statesToEnter, historyValue, statesForDefaultEntry, ancestors, reentrancyDomain) {\n  for (const anc of ancestors) {\n    if (!reentrancyDomain || isDescendant(anc, reentrancyDomain)) {\n      statesToEnter.add(anc);\n    }\n    if (anc.type === 'parallel') {\n      for (const child of getChildren(anc).filter(sn => !isHistoryNode(sn))) {\n        if (![...statesToEnter].some(s => isDescendant(s, child))) {\n          statesToEnter.add(child);\n          addDescendantStatesToEnter(child, historyValue, statesForDefaultEntry, statesToEnter);\n        }\n      }\n    }\n  }\n}\nfunction addProperAncestorStatesToEnter(stateNode, toStateNode, statesToEnter, historyValue, statesForDefaultEntry) {\n  addAncestorStatesToEnter(statesToEnter, historyValue, statesForDefaultEntry, getProperAncestors(stateNode, toStateNode));\n}\nfunction exitStates(currentSnapshot, event, actorScope, transitions, mutStateNodeSet, historyValue, internalQueue, _actionExecutor) {\n  let nextSnapshot = currentSnapshot;\n  const statesToExit = computeExitSet(transitions, mutStateNodeSet, historyValue);\n  statesToExit.sort((a, b) => b.order - a.order);\n  let changedHistory;\n\n  // From SCXML algorithm: https://www.w3.org/TR/scxml/#exitStates\n  for (const exitStateNode of statesToExit) {\n    for (const historyNode of getHistoryNodes(exitStateNode)) {\n      let predicate;\n      if (historyNode.history === 'deep') {\n        predicate = sn => isAtomicStateNode(sn) && isDescendant(sn, exitStateNode);\n      } else {\n        predicate = sn => {\n          return sn.parent === exitStateNode;\n        };\n      }\n      changedHistory ??= {\n        ...historyValue\n      };\n      changedHistory[historyNode.id] = Array.from(mutStateNodeSet).filter(predicate);\n    }\n  }\n  for (const s of statesToExit) {\n    nextSnapshot = resolveActionsAndContext(nextSnapshot, event, actorScope, [...s.exit, ...s.invoke.map(def => stopChild(def.id))], internalQueue, undefined);\n    mutStateNodeSet.delete(s);\n  }\n  return [nextSnapshot, changedHistory || historyValue];\n}\nfunction getAction(machine, actionType) {\n  return machine.implementations.actions[actionType];\n}\nfunction resolveAndExecuteActionsWithContext(currentSnapshot, event, actorScope, actions, extra, retries) {\n  const {\n    machine\n  } = currentSnapshot;\n  let intermediateSnapshot = currentSnapshot;\n  for (const action of actions) {\n    const isInline = typeof action === 'function';\n    const resolvedAction = isInline ? action :\n    // the existing type of `.actions` assumes non-nullable `TExpressionAction`\n    // it's fine to cast this here to get a common type and lack of errors in the rest of the code\n    // our logic below makes sure that we call those 2 \"variants\" correctly\n\n    getAction(machine, typeof action === 'string' ? action : action.type);\n    const actionArgs = {\n      context: intermediateSnapshot.context,\n      event,\n      self: actorScope.self,\n      system: actorScope.system\n    };\n    const actionParams = isInline || typeof action === 'string' ? undefined : 'params' in action ? typeof action.params === 'function' ? action.params({\n      context: intermediateSnapshot.context,\n      event\n    }) : action.params : undefined;\n    if (!resolvedAction || !('resolve' in resolvedAction)) {\n      actorScope.actionExecutor({\n        type: typeof action === 'string' ? action : typeof action === 'object' ? action.type : action.name || '(anonymous)',\n        info: actionArgs,\n        params: actionParams,\n        exec: resolvedAction\n      });\n      continue;\n    }\n    const builtinAction = resolvedAction;\n    const [nextState, params, actions] = builtinAction.resolve(actorScope, intermediateSnapshot, actionArgs, actionParams, resolvedAction,\n    // this holds all params\n    extra);\n    intermediateSnapshot = nextState;\n    if ('retryResolve' in builtinAction) {\n      retries?.push([builtinAction, params]);\n    }\n    if ('execute' in builtinAction) {\n      actorScope.actionExecutor({\n        type: builtinAction.type,\n        info: actionArgs,\n        params,\n        exec: builtinAction.execute.bind(null, actorScope, params)\n      });\n    }\n    if (actions) {\n      intermediateSnapshot = resolveAndExecuteActionsWithContext(intermediateSnapshot, event, actorScope, actions, extra, retries);\n    }\n  }\n  return intermediateSnapshot;\n}\nfunction resolveActionsAndContext(currentSnapshot, event, actorScope, actions, internalQueue, deferredActorIds) {\n  const retries = deferredActorIds ? [] : undefined;\n  const nextState = resolveAndExecuteActionsWithContext(currentSnapshot, event, actorScope, actions, {\n    internalQueue,\n    deferredActorIds\n  }, retries);\n  retries?.forEach(([builtinAction, params]) => {\n    builtinAction.retryResolve(actorScope, nextState, params);\n  });\n  return nextState;\n}\nfunction macrostep(snapshot, event, actorScope, internalQueue) {\n  let nextSnapshot = snapshot;\n  const microstates = [];\n  function addMicrostate(microstate, event, transitions) {\n    actorScope.system._sendInspectionEvent({\n      type: '@xstate.microstep',\n      actorRef: actorScope.self,\n      event,\n      snapshot: microstate,\n      _transitions: transitions\n    });\n    microstates.push(microstate);\n  }\n\n  // Handle stop event\n  if (event.type === XSTATE_STOP) {\n    nextSnapshot = cloneMachineSnapshot(stopChildren(nextSnapshot, event, actorScope), {\n      status: 'stopped'\n    });\n    addMicrostate(nextSnapshot, event, []);\n    return {\n      snapshot: nextSnapshot,\n      microstates\n    };\n  }\n  let nextEvent = event;\n\n  // Assume the state is at rest (no raised events)\n  // Determine the next state based on the next microstep\n  if (nextEvent.type !== XSTATE_INIT) {\n    const currentEvent = nextEvent;\n    const isErr = isErrorActorEvent(currentEvent);\n    const transitions = selectTransitions(currentEvent, nextSnapshot);\n    if (isErr && !transitions.length) {\n      // TODO: we should likely only allow transitions selected by very explicit descriptors\n      // `*` shouldn't be matched, likely `xstate.error.*` shouldnt be either\n      // similarly `xstate.error.actor.*` and `xstate.error.actor.todo.*` have to be considered too\n      nextSnapshot = cloneMachineSnapshot(snapshot, {\n        status: 'error',\n        error: currentEvent.error\n      });\n      addMicrostate(nextSnapshot, currentEvent, []);\n      return {\n        snapshot: nextSnapshot,\n        microstates\n      };\n    }\n    nextSnapshot = microstep(transitions, snapshot, actorScope, nextEvent, false,\n    // isInitial\n    internalQueue);\n    addMicrostate(nextSnapshot, currentEvent, transitions);\n  }\n  let shouldSelectEventlessTransitions = true;\n  while (nextSnapshot.status === 'active') {\n    let enabledTransitions = shouldSelectEventlessTransitions ? selectEventlessTransitions(nextSnapshot, nextEvent) : [];\n\n    // eventless transitions should always be selected after selecting *regular* transitions\n    // by assigning `undefined` to `previousState` we ensure that `shouldSelectEventlessTransitions` gets always computed to true in such a case\n    const previousState = enabledTransitions.length ? nextSnapshot : undefined;\n    if (!enabledTransitions.length) {\n      if (!internalQueue.length) {\n        break;\n      }\n      nextEvent = internalQueue.shift();\n      enabledTransitions = selectTransitions(nextEvent, nextSnapshot);\n    }\n    nextSnapshot = microstep(enabledTransitions, nextSnapshot, actorScope, nextEvent, false, internalQueue);\n    shouldSelectEventlessTransitions = nextSnapshot !== previousState;\n    addMicrostate(nextSnapshot, nextEvent, enabledTransitions);\n  }\n  if (nextSnapshot.status !== 'active') {\n    stopChildren(nextSnapshot, nextEvent, actorScope);\n  }\n  return {\n    snapshot: nextSnapshot,\n    microstates\n  };\n}\nfunction stopChildren(nextState, event, actorScope) {\n  return resolveActionsAndContext(nextState, event, actorScope, Object.values(nextState.children).map(child => stopChild(child)), [], undefined);\n}\nfunction selectTransitions(event, nextState) {\n  return nextState.machine.getTransitionData(nextState, event);\n}\nfunction selectEventlessTransitions(nextState, event) {\n  const enabledTransitionSet = new Set();\n  const atomicStates = nextState._nodes.filter(isAtomicStateNode);\n  for (const stateNode of atomicStates) {\n    loop: for (const s of [stateNode].concat(getProperAncestors(stateNode, undefined))) {\n      if (!s.always) {\n        continue;\n      }\n      for (const transition of s.always) {\n        if (transition.guard === undefined || evaluateGuard(transition.guard, nextState.context, event, nextState)) {\n          enabledTransitionSet.add(transition);\n          break loop;\n        }\n      }\n    }\n  }\n  return removeConflictingTransitions(Array.from(enabledTransitionSet), new Set(nextState._nodes), nextState.historyValue);\n}\n\n/**\n * Resolves a partial state value with its full representation in the state\n * node's machine.\n *\n * @param stateValue The partial state value to resolve.\n */\nfunction resolveStateValue(rootNode, stateValue) {\n  const allStateNodes = getAllStateNodes(getStateNodes(rootNode, stateValue));\n  return getStateValue(rootNode, [...allStateNodes]);\n}\n\nfunction isMachineSnapshot(value) {\n  return !!value && typeof value === 'object' && 'machine' in value && 'value' in value;\n}\nconst machineSnapshotMatches = function matches(testValue) {\n  return matchesState(testValue, this.value);\n};\nconst machineSnapshotHasTag = function hasTag(tag) {\n  return this.tags.has(tag);\n};\nconst machineSnapshotCan = function can(event) {\n  const transitionData = this.machine.getTransitionData(this, event);\n  return !!transitionData?.length &&\n  // Check that at least one transition is not forbidden\n  transitionData.some(t => t.target !== undefined || t.actions.length);\n};\nconst machineSnapshotToJSON = function toJSON() {\n  const {\n    _nodes: nodes,\n    tags,\n    machine,\n    getMeta,\n    toJSON,\n    can,\n    hasTag,\n    matches,\n    ...jsonValues\n  } = this;\n  return {\n    ...jsonValues,\n    tags: Array.from(tags)\n  };\n};\nconst machineSnapshotGetMeta = function getMeta() {\n  return this._nodes.reduce((acc, stateNode) => {\n    if (stateNode.meta !== undefined) {\n      acc[stateNode.id] = stateNode.meta;\n    }\n    return acc;\n  }, {});\n};\nfunction createMachineSnapshot(config, machine) {\n  return {\n    status: config.status,\n    output: config.output,\n    error: config.error,\n    machine,\n    context: config.context,\n    _nodes: config._nodes,\n    value: getStateValue(machine.root, config._nodes),\n    tags: new Set(config._nodes.flatMap(sn => sn.tags)),\n    children: config.children,\n    historyValue: config.historyValue || {},\n    matches: machineSnapshotMatches,\n    hasTag: machineSnapshotHasTag,\n    can: machineSnapshotCan,\n    getMeta: machineSnapshotGetMeta,\n    toJSON: machineSnapshotToJSON\n  };\n}\nfunction cloneMachineSnapshot(snapshot, config = {}) {\n  return createMachineSnapshot({\n    ...snapshot,\n    ...config\n  }, snapshot.machine);\n}\nfunction getPersistedSnapshot(snapshot, options) {\n  const {\n    _nodes: nodes,\n    tags,\n    machine,\n    children,\n    context,\n    can,\n    hasTag,\n    matches,\n    getMeta,\n    toJSON,\n    ...jsonValues\n  } = snapshot;\n  const childrenJson = {};\n  for (const id in children) {\n    const child = children[id];\n    childrenJson[id] = {\n      snapshot: child.getPersistedSnapshot(options),\n      src: child.src,\n      systemId: child._systemId,\n      syncSnapshot: child._syncSnapshot\n    };\n  }\n  const persisted = {\n    ...jsonValues,\n    context: persistContext(context),\n    children: childrenJson\n  };\n  return persisted;\n}\nfunction persistContext(contextPart) {\n  let copy;\n  for (const key in contextPart) {\n    const value = contextPart[key];\n    if (value && typeof value === 'object') {\n      if ('sessionId' in value && 'send' in value && 'ref' in value) {\n        copy ??= Array.isArray(contextPart) ? contextPart.slice() : {\n          ...contextPart\n        };\n        copy[key] = {\n          xstate$$type: $$ACTOR_TYPE,\n          id: value.id\n        };\n      } else {\n        const result = persistContext(value);\n        if (result !== value) {\n          copy ??= Array.isArray(contextPart) ? contextPart.slice() : {\n            ...contextPart\n          };\n          copy[key] = result;\n        }\n      }\n    }\n  }\n  return copy ?? contextPart;\n}\n\nfunction resolveRaise(_, snapshot, args, actionParams, {\n  event: eventOrExpr,\n  id,\n  delay\n}, {\n  internalQueue\n}) {\n  const delaysMap = snapshot.machine.implementations.delays;\n  if (typeof eventOrExpr === 'string') {\n    throw new Error(\n    // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n    `Only event objects may be used with raise; use raise({ type: \"${eventOrExpr}\" }) instead`);\n  }\n  const resolvedEvent = typeof eventOrExpr === 'function' ? eventOrExpr(args, actionParams) : eventOrExpr;\n  let resolvedDelay;\n  if (typeof delay === 'string') {\n    const configDelay = delaysMap && delaysMap[delay];\n    resolvedDelay = typeof configDelay === 'function' ? configDelay(args, actionParams) : configDelay;\n  } else {\n    resolvedDelay = typeof delay === 'function' ? delay(args, actionParams) : delay;\n  }\n  if (typeof resolvedDelay !== 'number') {\n    internalQueue.push(resolvedEvent);\n  }\n  return [snapshot, {\n    event: resolvedEvent,\n    id,\n    delay: resolvedDelay\n  }, undefined];\n}\nfunction executeRaise(actorScope, params) {\n  const {\n    event,\n    delay,\n    id\n  } = params;\n  if (typeof delay === 'number') {\n    actorScope.defer(() => {\n      const self = actorScope.self;\n      actorScope.system.scheduler.schedule(self, self, event, delay, id);\n    });\n    return;\n  }\n}\n/**\n * Raises an event. This places the event in the internal event queue, so that\n * the event is immediately consumed by the machine in the current step.\n *\n * @param eventType The event to raise.\n */\nfunction raise(eventOrExpr, options) {\n  function raise(_args, _params) {\n  }\n  raise.type = 'xstate.raise';\n  raise.event = eventOrExpr;\n  raise.id = options?.id;\n  raise.delay = options?.delay;\n  raise.resolve = resolveRaise;\n  raise.execute = executeRaise;\n  return raise;\n}\n\nexport { $$ACTOR_TYPE as $, createActor as A, Actor as B, interpret as C, and as D, not as E, or as F, stateIn as G, isMachineSnapshot as H, getAllOwnEventDescriptors as I, matchesState as J, pathToStateValue as K, toObserver as L, cancel as M, NULL_EVENT as N, raise as O, spawnChild as P, stop as Q, stopChild as R, STATE_DELIMITER as S, ProcessingStatus as T, cloneMachineSnapshot as U, XSTATE_ERROR as V, createErrorActorEvent as W, XSTATE_STOP as X, toTransitionConfigArray as a, formatTransition as b, createInvokeId as c, formatInitialTransition as d, evaluateGuard as e, formatTransitions as f, getDelayedTransitions as g, getCandidates as h, getAllStateNodes as i, getStateNodes as j, createMachineSnapshot as k, isInFinalState as l, mapValues as m, macrostep as n, transitionNode as o, resolveActionsAndContext as p, createInitEvent as q, resolveStateValue as r, microstep as s, toArray as t, getInitialStateNodes as u, toStatePath as v, isStateId as w, getStateNodeByPath as x, getPersistedSnapshot as y, resolveReferencedActor as z };\n","export { createEmptyActor, fromCallback, fromEventObservable, fromObservable, fromPromise, fromTransition } from '../actors/dist/xstate-actors.esm.js';\nimport { t as toArray, S as STATE_DELIMITER, m as mapValues, f as formatTransitions, a as toTransitionConfigArray, b as formatTransition, N as NULL_EVENT, e as evaluateGuard, c as createInvokeId, g as getDelayedTransitions, d as formatInitialTransition, h as getCandidates, r as resolveStateValue, i as getAllStateNodes, j as getStateNodes, k as createMachineSnapshot, l as isInFinalState, n as macrostep, o as transitionNode, p as resolveActionsAndContext, q as createInitEvent, s as microstep, u as getInitialStateNodes, v as toStatePath, w as isStateId, x as getStateNodeByPath, y as getPersistedSnapshot, z as resolveReferencedActor, A as createActor, $ as $$ACTOR_TYPE } from './raise-c17ec2bc.esm.js';\nexport { B as Actor, I as __unsafe_getAllOwnEventDescriptors, D as and, M as cancel, A as createActor, j as getStateNodes, C as interpret, H as isMachineSnapshot, J as matchesState, E as not, F as or, K as pathToStateValue, O as raise, P as spawnChild, G as stateIn, Q as stop, R as stopChild, L as toObserver } from './raise-c17ec2bc.esm.js';\nimport { a as assign } from './log-2a773d37.esm.js';\nexport { S as SpecialTargets, a as assign, e as emit, b as enqueueActions, f as forwardTo, l as log, s as sendParent, c as sendTo } from './log-2a773d37.esm.js';\nimport '../dev/dist/xstate-dev.esm.js';\n\n/**\n * Asserts that the given event object is of the specified type or types. Throws\n * an error if the event object is not of the specified types.\n *\n * @example\n *\n * ```ts\n * // ...\n * entry: ({ event }) => {\n *   assertEvent(event, 'doNothing');\n *   // event is { type: 'doNothing' }\n * },\n * // ...\n * exit: ({ event }) => {\n *   assertEvent(event, 'greet');\n *   // event is { type: 'greet'; message: string }\n *\n *   assertEvent(event, ['greet', 'notify']);\n *   // event is { type: 'greet'; message: string }\n *   // or { type: 'notify'; message: string; level: 'info' | 'error' }\n * },\n * ```\n */\nfunction assertEvent(event, type) {\n  const types = toArray(type);\n  if (!types.includes(event.type)) {\n    const typesText = types.length === 1 ? `type \"${types[0]}\"` : `one of types \"${types.join('\", \"')}\"`;\n    throw new Error(`Expected event ${JSON.stringify(event)} to have ${typesText}`);\n  }\n}\n\nconst cache = new WeakMap();\nfunction memo(object, key, fn) {\n  let memoizedData = cache.get(object);\n  if (!memoizedData) {\n    memoizedData = {\n      [key]: fn()\n    };\n    cache.set(object, memoizedData);\n  } else if (!(key in memoizedData)) {\n    memoizedData[key] = fn();\n  }\n  return memoizedData[key];\n}\n\nconst EMPTY_OBJECT = {};\nconst toSerializableAction = action => {\n  if (typeof action === 'string') {\n    return {\n      type: action\n    };\n  }\n  if (typeof action === 'function') {\n    if ('resolve' in action) {\n      return {\n        type: action.type\n      };\n    }\n    return {\n      type: action.name\n    };\n  }\n  return action;\n};\nclass StateNode {\n  constructor(/** The raw config used to create the machine. */\n  config, options) {\n    this.config = config;\n    /**\n     * The relative key of the state node, which represents its location in the\n     * overall state value.\n     */\n    this.key = void 0;\n    /** The unique ID of the state node. */\n    this.id = void 0;\n    /**\n     * The type of this state node:\n     *\n     * - `'atomic'` - no child state nodes\n     * - `'compound'` - nested child state nodes (XOR)\n     * - `'parallel'` - orthogonal nested child state nodes (AND)\n     * - `'history'` - history state node\n     * - `'final'` - final state node\n     */\n    this.type = void 0;\n    /** The string path from the root machine node to this node. */\n    this.path = void 0;\n    /** The child state nodes. */\n    this.states = void 0;\n    /**\n     * The type of history on this state node. Can be:\n     *\n     * - `'shallow'` - recalls only top-level historical state value\n     * - `'deep'` - recalls historical state value at all levels\n     */\n    this.history = void 0;\n    /** The action(s) to be executed upon entering the state node. */\n    this.entry = void 0;\n    /** The action(s) to be executed upon exiting the state node. */\n    this.exit = void 0;\n    /** The parent state node. */\n    this.parent = void 0;\n    /** The root machine node. */\n    this.machine = void 0;\n    /**\n     * The meta data associated with this state node, which will be returned in\n     * State instances.\n     */\n    this.meta = void 0;\n    /**\n     * The output data sent with the \"xstate.done.state._id_\" event if this is a\n     * final state node.\n     */\n    this.output = void 0;\n    /**\n     * The order this state node appears. Corresponds to the implicit document\n     * order.\n     */\n    this.order = -1;\n    this.description = void 0;\n    this.tags = [];\n    this.transitions = void 0;\n    this.always = void 0;\n    this.parent = options._parent;\n    this.key = options._key;\n    this.machine = options._machine;\n    this.path = this.parent ? this.parent.path.concat(this.key) : [];\n    this.id = this.config.id || [this.machine.id, ...this.path].join(STATE_DELIMITER);\n    this.type = this.config.type || (this.config.states && Object.keys(this.config.states).length ? 'compound' : this.config.history ? 'history' : 'atomic');\n    this.description = this.config.description;\n    this.order = this.machine.idMap.size;\n    this.machine.idMap.set(this.id, this);\n    this.states = this.config.states ? mapValues(this.config.states, (stateConfig, key) => {\n      const stateNode = new StateNode(stateConfig, {\n        _parent: this,\n        _key: key,\n        _machine: this.machine\n      });\n      return stateNode;\n    }) : EMPTY_OBJECT;\n    if (this.type === 'compound' && !this.config.initial) {\n      throw new Error(`No initial state specified for compound state node \"#${this.id}\". Try adding { initial: \"${Object.keys(this.states)[0]}\" } to the state config.`);\n    }\n\n    // History config\n    this.history = this.config.history === true ? 'shallow' : this.config.history || false;\n    this.entry = toArray(this.config.entry).slice();\n    this.exit = toArray(this.config.exit).slice();\n    this.meta = this.config.meta;\n    this.output = this.type === 'final' || !this.parent ? this.config.output : undefined;\n    this.tags = toArray(config.tags).slice();\n  }\n\n  /** @internal */\n  _initialize() {\n    this.transitions = formatTransitions(this);\n    if (this.config.always) {\n      this.always = toTransitionConfigArray(this.config.always).map(t => formatTransition(this, NULL_EVENT, t));\n    }\n    Object.keys(this.states).forEach(key => {\n      this.states[key]._initialize();\n    });\n  }\n\n  /** The well-structured state node definition. */\n  get definition() {\n    return {\n      id: this.id,\n      key: this.key,\n      version: this.machine.version,\n      type: this.type,\n      initial: this.initial ? {\n        target: this.initial.target,\n        source: this,\n        actions: this.initial.actions.map(toSerializableAction),\n        eventType: null,\n        reenter: false,\n        toJSON: () => ({\n          target: this.initial.target.map(t => `#${t.id}`),\n          source: `#${this.id}`,\n          actions: this.initial.actions.map(toSerializableAction),\n          eventType: null\n        })\n      } : undefined,\n      history: this.history,\n      states: mapValues(this.states, state => {\n        return state.definition;\n      }),\n      on: this.on,\n      transitions: [...this.transitions.values()].flat().map(t => ({\n        ...t,\n        actions: t.actions.map(toSerializableAction)\n      })),\n      entry: this.entry.map(toSerializableAction),\n      exit: this.exit.map(toSerializableAction),\n      meta: this.meta,\n      order: this.order || -1,\n      output: this.output,\n      invoke: this.invoke,\n      description: this.description,\n      tags: this.tags\n    };\n  }\n\n  /** @internal */\n  toJSON() {\n    return this.definition;\n  }\n\n  /** The logic invoked as actors by this state node. */\n  get invoke() {\n    return memo(this, 'invoke', () => toArray(this.config.invoke).map((invokeConfig, i) => {\n      const {\n        src,\n        systemId\n      } = invokeConfig;\n      const resolvedId = invokeConfig.id ?? createInvokeId(this.id, i);\n      const sourceName = typeof src === 'string' ? src : `xstate.invoke.${createInvokeId(this.id, i)}`;\n      return {\n        ...invokeConfig,\n        src: sourceName,\n        id: resolvedId,\n        systemId: systemId,\n        toJSON() {\n          const {\n            onDone,\n            onError,\n            ...invokeDefValues\n          } = invokeConfig;\n          return {\n            ...invokeDefValues,\n            type: 'xstate.invoke',\n            src: sourceName,\n            id: resolvedId\n          };\n        }\n      };\n    }));\n  }\n\n  /** The mapping of events to transitions. */\n  get on() {\n    return memo(this, 'on', () => {\n      const transitions = this.transitions;\n      return [...transitions].flatMap(([descriptor, t]) => t.map(t => [descriptor, t])).reduce((map, [descriptor, transition]) => {\n        map[descriptor] = map[descriptor] || [];\n        map[descriptor].push(transition);\n        return map;\n      }, {});\n    });\n  }\n  get after() {\n    return memo(this, 'delayedTransitions', () => getDelayedTransitions(this));\n  }\n  get initial() {\n    return memo(this, 'initial', () => formatInitialTransition(this, this.config.initial));\n  }\n\n  /** @internal */\n  next(snapshot, event) {\n    const eventType = event.type;\n    const actions = [];\n    let selectedTransition;\n    const candidates = memo(this, `candidates-${eventType}`, () => getCandidates(this, eventType));\n    for (const candidate of candidates) {\n      const {\n        guard\n      } = candidate;\n      const resolvedContext = snapshot.context;\n      let guardPassed = false;\n      try {\n        guardPassed = !guard || evaluateGuard(guard, resolvedContext, event, snapshot);\n      } catch (err) {\n        const guardType = typeof guard === 'string' ? guard : typeof guard === 'object' ? guard.type : undefined;\n        throw new Error(`Unable to evaluate guard ${guardType ? `'${guardType}' ` : ''}in transition for event '${eventType}' in state node '${this.id}':\\n${err.message}`);\n      }\n      if (guardPassed) {\n        actions.push(...candidate.actions);\n        selectedTransition = candidate;\n        break;\n      }\n    }\n    return selectedTransition ? [selectedTransition] : undefined;\n  }\n\n  /** All the event types accepted by this state node and its descendants. */\n  get events() {\n    return memo(this, 'events', () => {\n      const {\n        states\n      } = this;\n      const events = new Set(this.ownEvents);\n      if (states) {\n        for (const stateId of Object.keys(states)) {\n          const state = states[stateId];\n          if (state.states) {\n            for (const event of state.events) {\n              events.add(`${event}`);\n            }\n          }\n        }\n      }\n      return Array.from(events);\n    });\n  }\n\n  /**\n   * All the events that have transitions directly from this state node.\n   *\n   * Excludes any inert events.\n   */\n  get ownEvents() {\n    const events = new Set([...this.transitions.keys()].filter(descriptor => {\n      return this.transitions.get(descriptor).some(transition => !(!transition.target && !transition.actions.length && !transition.reenter));\n    }));\n    return Array.from(events);\n  }\n}\n\nconst STATE_IDENTIFIER = '#';\nclass StateMachine {\n  constructor(/** The raw config used to create the machine. */\n  config, implementations) {\n    this.config = config;\n    /** The machine's own version. */\n    this.version = void 0;\n    this.schemas = void 0;\n    this.implementations = void 0;\n    /** @internal */\n    this.__xstatenode = true;\n    /** @internal */\n    this.idMap = new Map();\n    this.root = void 0;\n    this.id = void 0;\n    this.states = void 0;\n    this.events = void 0;\n    this.id = config.id || '(machine)';\n    this.implementations = {\n      actors: implementations?.actors ?? {},\n      actions: implementations?.actions ?? {},\n      delays: implementations?.delays ?? {},\n      guards: implementations?.guards ?? {}\n    };\n    this.version = this.config.version;\n    this.schemas = this.config.schemas;\n    this.transition = this.transition.bind(this);\n    this.getInitialSnapshot = this.getInitialSnapshot.bind(this);\n    this.getPersistedSnapshot = this.getPersistedSnapshot.bind(this);\n    this.restoreSnapshot = this.restoreSnapshot.bind(this);\n    this.start = this.start.bind(this);\n    this.root = new StateNode(config, {\n      _key: this.id,\n      _machine: this\n    });\n    this.root._initialize();\n    this.states = this.root.states; // TODO: remove!\n    this.events = this.root.events;\n  }\n\n  /**\n   * Clones this state machine with the provided implementations and merges the\n   * `context` (if provided).\n   *\n   * @param implementations Options (`actions`, `guards`, `actors`, `delays`,\n   *   `context`) to recursively merge with the existing options.\n   * @returns A new `StateMachine` instance with the provided implementations.\n   */\n  provide(implementations) {\n    const {\n      actions,\n      guards,\n      actors,\n      delays\n    } = this.implementations;\n    return new StateMachine(this.config, {\n      actions: {\n        ...actions,\n        ...implementations.actions\n      },\n      guards: {\n        ...guards,\n        ...implementations.guards\n      },\n      actors: {\n        ...actors,\n        ...implementations.actors\n      },\n      delays: {\n        ...delays,\n        ...implementations.delays\n      }\n    });\n  }\n  resolveState(config) {\n    const resolvedStateValue = resolveStateValue(this.root, config.value);\n    const nodeSet = getAllStateNodes(getStateNodes(this.root, resolvedStateValue));\n    return createMachineSnapshot({\n      _nodes: [...nodeSet],\n      context: config.context || {},\n      children: {},\n      status: isInFinalState(nodeSet, this.root) ? 'done' : config.status || 'active',\n      output: config.output,\n      error: config.error,\n      historyValue: config.historyValue\n    }, this);\n  }\n\n  /**\n   * Determines the next snapshot given the current `snapshot` and received\n   * `event`. Calculates a full macrostep from all microsteps.\n   *\n   * @param snapshot The current snapshot\n   * @param event The received event\n   */\n  transition(snapshot, event, actorScope) {\n    return macrostep(snapshot, event, actorScope, []).snapshot;\n  }\n\n  /**\n   * Determines the next state given the current `state` and `event`. Calculates\n   * a microstep.\n   *\n   * @param state The current state\n   * @param event The received event\n   */\n  microstep(snapshot, event, actorScope) {\n    return macrostep(snapshot, event, actorScope, []).microstates;\n  }\n  getTransitionData(snapshot, event) {\n    return transitionNode(this.root, snapshot.value, snapshot, event) || [];\n  }\n\n  /**\n   * The initial state _before_ evaluating any microsteps. This \"pre-initial\"\n   * state is provided to initial actions executed in the initial state.\n   */\n  getPreInitialState(actorScope, initEvent, internalQueue) {\n    const {\n      context\n    } = this.config;\n    const preInitial = createMachineSnapshot({\n      context: typeof context !== 'function' && context ? context : {},\n      _nodes: [this.root],\n      children: {},\n      status: 'active'\n    }, this);\n    if (typeof context === 'function') {\n      const assignment = ({\n        spawn,\n        event,\n        self\n      }) => context({\n        spawn,\n        input: event.input,\n        self\n      });\n      return resolveActionsAndContext(preInitial, initEvent, actorScope, [assign(assignment)], internalQueue, undefined);\n    }\n    return preInitial;\n  }\n\n  /**\n   * Returns the initial `State` instance, with reference to `self` as an\n   * `ActorRef`.\n   */\n  getInitialSnapshot(actorScope, input) {\n    const initEvent = createInitEvent(input); // TODO: fix;\n    const internalQueue = [];\n    const preInitialState = this.getPreInitialState(actorScope, initEvent, internalQueue);\n    const nextState = microstep([{\n      target: [...getInitialStateNodes(this.root)],\n      source: this.root,\n      reenter: true,\n      actions: [],\n      eventType: null,\n      toJSON: null // TODO: fix\n    }], preInitialState, actorScope, initEvent, true, internalQueue);\n    const {\n      snapshot: macroState\n    } = macrostep(nextState, initEvent, actorScope, internalQueue);\n    return macroState;\n  }\n  start(snapshot) {\n    Object.values(snapshot.children).forEach(child => {\n      if (child.getSnapshot().status === 'active') {\n        child.start();\n      }\n    });\n  }\n  getStateNodeById(stateId) {\n    const fullPath = toStatePath(stateId);\n    const relativePath = fullPath.slice(1);\n    const resolvedStateId = isStateId(fullPath[0]) ? fullPath[0].slice(STATE_IDENTIFIER.length) : fullPath[0];\n    const stateNode = this.idMap.get(resolvedStateId);\n    if (!stateNode) {\n      throw new Error(`Child state node '#${resolvedStateId}' does not exist on machine '${this.id}'`);\n    }\n    return getStateNodeByPath(stateNode, relativePath);\n  }\n  get definition() {\n    return this.root.definition;\n  }\n  toJSON() {\n    return this.definition;\n  }\n  getPersistedSnapshot(snapshot, options) {\n    return getPersistedSnapshot(snapshot, options);\n  }\n  restoreSnapshot(snapshot, _actorScope) {\n    const children = {};\n    const snapshotChildren = snapshot.children;\n    Object.keys(snapshotChildren).forEach(actorId => {\n      const actorData = snapshotChildren[actorId];\n      const childState = actorData.snapshot;\n      const src = actorData.src;\n      const logic = typeof src === 'string' ? resolveReferencedActor(this, src) : src;\n      if (!logic) {\n        return;\n      }\n      const actorRef = createActor(logic, {\n        id: actorId,\n        parent: _actorScope.self,\n        syncSnapshot: actorData.syncSnapshot,\n        snapshot: childState,\n        src,\n        systemId: actorData.systemId\n      });\n      children[actorId] = actorRef;\n    });\n    const restoredSnapshot = createMachineSnapshot({\n      ...snapshot,\n      children,\n      _nodes: Array.from(getAllStateNodes(getStateNodes(this.root, snapshot.value)))\n    }, this);\n    const seen = new Set();\n    function reviveContext(contextPart, children) {\n      if (seen.has(contextPart)) {\n        return;\n      }\n      seen.add(contextPart);\n      for (const key in contextPart) {\n        const value = contextPart[key];\n        if (value && typeof value === 'object') {\n          if ('xstate$$type' in value && value.xstate$$type === $$ACTOR_TYPE) {\n            contextPart[key] = children[value.id];\n            continue;\n          }\n          reviveContext(value, children);\n        }\n      }\n    }\n    reviveContext(restoredSnapshot.context, children);\n    return restoredSnapshot;\n  }\n}\n\n/**\n * Creates a state machine (statechart) with the given configuration.\n *\n * The state machine represents the pure logic of a state machine actor.\n *\n * @example\n *\n * ```ts\n * import { createMachine } from 'xstate';\n *\n * const lightMachine = createMachine({\n *   id: 'light',\n *   initial: 'green',\n *   states: {\n *     green: {\n *       on: {\n *         TIMER: { target: 'yellow' }\n *       }\n *     },\n *     yellow: {\n *       on: {\n *         TIMER: { target: 'red' }\n *       }\n *     },\n *     red: {\n *       on: {\n *         TIMER: { target: 'green' }\n *       }\n *     }\n *   }\n * });\n *\n * const lightActor = createActor(lightMachine);\n * lightActor.start();\n *\n * lightActor.send({ type: 'TIMER' });\n * ```\n *\n * @param config The state machine configuration.\n * @param options DEPRECATED: use `setup({ ... })` or `machine.provide({ ... })`\n *   to provide machine implementations instead.\n */\nfunction createMachine(config, implementations) {\n  return new StateMachine(config, implementations);\n}\n\n/** @internal */\nfunction createInertActorScope(actorLogic) {\n  const self = createActor(actorLogic);\n  const inertActorScope = {\n    self,\n    defer: () => {},\n    id: '',\n    logger: () => {},\n    sessionId: '',\n    stopChild: () => {},\n    system: self.system,\n    emit: () => {},\n    actionExecutor: () => {}\n  };\n  return inertActorScope;\n}\n\n/** @deprecated Use `initialTransition(…)` instead. */\nfunction getInitialSnapshot(actorLogic, ...[input]) {\n  const actorScope = createInertActorScope(actorLogic);\n  return actorLogic.getInitialSnapshot(actorScope, input);\n}\n\n/**\n * Determines the next snapshot for the given `actorLogic` based on the given\n * `snapshot` and `event`.\n *\n * If the `snapshot` is `undefined`, the initial snapshot of the `actorLogic` is\n * used.\n *\n * @deprecated Use `transition(…)` instead.\n * @example\n *\n * ```ts\n * import { getNextSnapshot } from 'xstate';\n * import { trafficLightMachine } from './trafficLightMachine.ts';\n *\n * const nextSnapshot = getNextSnapshot(\n *   trafficLightMachine, // actor logic\n *   undefined, // snapshot (or initial state if undefined)\n *   { type: 'TIMER' }\n * ); // event object\n *\n * console.log(nextSnapshot.value);\n * // => 'yellow'\n *\n * const nextSnapshot2 = getNextSnapshot(\n *   trafficLightMachine, // actor logic\n *   nextSnapshot, // snapshot\n *   { type: 'TIMER' }\n * ); // event object\n *\n * console.log(nextSnapshot2.value);\n * // =>'red'\n * ```\n */\nfunction getNextSnapshot(actorLogic, snapshot, event) {\n  const inertActorScope = createInertActorScope(actorLogic);\n  inertActorScope.self._snapshot = snapshot;\n  return actorLogic.transition(snapshot, event, inertActorScope);\n}\n\n// at the moment we allow extra actors - ones that are not specified by `children`\n// this could be reconsidered in the future\n\nfunction setup({\n  schemas,\n  actors,\n  actions,\n  guards,\n  delays\n}) {\n  return {\n    createMachine: config => createMachine({\n      ...config,\n      schemas\n    }, {\n      actors,\n      actions,\n      guards,\n      delays\n    })\n  };\n}\n\n// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging\n\n// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging\nclass SimulatedClock {\n  constructor() {\n    this.timeouts = new Map();\n    this._now = 0;\n    this._id = 0;\n    this._flushing = false;\n    this._flushingInvalidated = false;\n  }\n  now() {\n    return this._now;\n  }\n  getId() {\n    return this._id++;\n  }\n  setTimeout(fn, timeout) {\n    this._flushingInvalidated = this._flushing;\n    const id = this.getId();\n    this.timeouts.set(id, {\n      start: this.now(),\n      timeout,\n      fn\n    });\n    return id;\n  }\n  clearTimeout(id) {\n    this._flushingInvalidated = this._flushing;\n    this.timeouts.delete(id);\n  }\n  set(time) {\n    if (this._now > time) {\n      throw new Error('Unable to travel back in time');\n    }\n    this._now = time;\n    this.flushTimeouts();\n  }\n  flushTimeouts() {\n    if (this._flushing) {\n      this._flushingInvalidated = true;\n      return;\n    }\n    this._flushing = true;\n    const sorted = [...this.timeouts].sort(([_idA, timeoutA], [_idB, timeoutB]) => {\n      const endA = timeoutA.start + timeoutA.timeout;\n      const endB = timeoutB.start + timeoutB.timeout;\n      return endB > endA ? -1 : 1;\n    });\n    for (const [id, timeout] of sorted) {\n      if (this._flushingInvalidated) {\n        this._flushingInvalidated = false;\n        this._flushing = false;\n        this.flushTimeouts();\n        return;\n      }\n      if (this.now() - timeout.start >= timeout.timeout) {\n        this.timeouts.delete(id);\n        timeout.fn.call(null);\n      }\n    }\n    this._flushing = false;\n  }\n  increment(ms) {\n    this._now += ms;\n    this.flushTimeouts();\n  }\n}\n\n/**\n * Returns a promise that resolves to the `output` of the actor when it is done.\n *\n * @example\n *\n * ```ts\n * const machine = createMachine({\n *   // ...\n *   output: {\n *     count: 42\n *   }\n * });\n *\n * const actor = createActor(machine);\n *\n * actor.start();\n *\n * const output = await toPromise(actor);\n *\n * console.log(output);\n * // logs { count: 42 }\n * ```\n */\nfunction toPromise(actor) {\n  return new Promise((resolve, reject) => {\n    actor.subscribe({\n      complete: () => {\n        resolve(actor.getSnapshot().output);\n      },\n      error: reject\n    });\n  });\n}\n\n/**\n * Given actor `logic`, a `snapshot`, and an `event`, returns a tuple of the\n * `nextSnapshot` and `actions` to execute.\n *\n * This is a pure function that does not execute `actions`.\n */\nfunction transition(logic, snapshot, event) {\n  const executableActions = [];\n  const actorScope = createInertActorScope(logic);\n  actorScope.actionExecutor = action => {\n    executableActions.push(action);\n  };\n  const nextSnapshot = logic.transition(snapshot, event, actorScope);\n  return [nextSnapshot, executableActions];\n}\n\n/**\n * Given actor `logic` and optional `input`, returns a tuple of the\n * `nextSnapshot` and `actions` to execute from the initial transition (no\n * previous state).\n *\n * This is a pure function that does not execute `actions`.\n */\nfunction initialTransition(logic, ...[input]) {\n  const executableActions = [];\n  const actorScope = createInertActorScope(logic);\n  actorScope.actionExecutor = action => {\n    executableActions.push(action);\n  };\n  const nextSnapshot = logic.getInitialSnapshot(actorScope, input);\n  return [nextSnapshot, executableActions];\n}\n\nconst defaultWaitForOptions = {\n  timeout: Infinity // much more than 10 seconds\n};\n\n/**\n * Subscribes to an actor ref and waits for its emitted value to satisfy a\n * predicate, and then resolves with that value. Will throw if the desired state\n * is not reached after an optional timeout. (defaults to Infinity).\n *\n * @example\n *\n * ```js\n * const state = await waitFor(someService, (state) => {\n *   return state.hasTag('loaded');\n * });\n *\n * state.hasTag('loaded'); // true\n * ```\n *\n * @param actorRef The actor ref to subscribe to\n * @param predicate Determines if a value matches the condition to wait for\n * @param options\n * @returns A promise that eventually resolves to the emitted value that matches\n *   the condition\n */\nfunction waitFor(actorRef, predicate, options) {\n  const resolvedOptions = {\n    ...defaultWaitForOptions,\n    ...options\n  };\n  return new Promise((res, rej) => {\n    const {\n      signal\n    } = resolvedOptions;\n    if (signal?.aborted) {\n      // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors\n      rej(signal.reason);\n      return;\n    }\n    let done = false;\n    const handle = resolvedOptions.timeout === Infinity ? undefined : setTimeout(() => {\n      dispose();\n      rej(new Error(`Timeout of ${resolvedOptions.timeout} ms exceeded`));\n    }, resolvedOptions.timeout);\n    const dispose = () => {\n      clearTimeout(handle);\n      done = true;\n      sub?.unsubscribe();\n      if (abortListener) {\n        signal.removeEventListener('abort', abortListener);\n      }\n    };\n    function checkEmitted(emitted) {\n      if (predicate(emitted)) {\n        dispose();\n        res(emitted);\n      }\n    }\n\n    /**\n     * If the `signal` option is provided, this will be the listener for its\n     * `abort` event\n     */\n    let abortListener;\n    // eslint-disable-next-line prefer-const\n    let sub; // avoid TDZ when disposing synchronously\n\n    // See if the current snapshot already matches the predicate\n    checkEmitted(actorRef.getSnapshot());\n    if (done) {\n      return;\n    }\n\n    // only define the `abortListener` if the `signal` option is provided\n    if (signal) {\n      abortListener = () => {\n        dispose();\n        // XState does not \"own\" the signal, so we should reject with its reason (if any)\n        // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors\n        rej(signal.reason);\n      };\n      signal.addEventListener('abort', abortListener);\n    }\n    sub = actorRef.subscribe({\n      next: checkEmitted,\n      error: err => {\n        dispose();\n        // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors\n        rej(err);\n      },\n      complete: () => {\n        dispose();\n        rej(new Error(`Actor terminated without satisfying predicate`));\n      }\n    });\n    if (done) {\n      sub.unsubscribe();\n    }\n  });\n}\n\nexport { SimulatedClock, StateMachine, StateNode, assertEvent, createMachine, getInitialSnapshot, getNextSnapshot, initialTransition, setup, toPromise, transition, waitFor };\n"],"names":["useLayoutEffect","forEachActor","actorRef","callback","children","getSnapshot","Object","values","forEach","child","stopRootWithRehydration","persistedSnapshots","ref","push","observers","Set","systemSnapshot","system","stop","_snapshot","snapshot","_processingStatus","useIdleActorRef","logic","options","currentConfig","setCurrent","useState","config","newActorRef","getPersistedSnapshot","__unsafeAllowInlineActors","implementations","defaultCompare","a","b","createActorContext","actorLogic","actorOptions","ReactContext","OriginalProvider","Provider","providedLogic","machine","providedOptions","Error","actor","observerOrListener","useEffect","sub","subscribe","unsubscribe","start","useActorRef","value","useContext","displayName","useSelector","selector","compare","useCallback","handleStoreChange","boundGetSnapshot","useSyncExternalStoreWithSelector","useMachine","actorSnapshot","useSyncExternalStore","send","useActor","e","k","is","l","m","n","p","useDebugValue","r","d","f","u","window","document","createElement","inst","c","g","exports","h","q","t","useRef","v","useMemo","w","current","hasValue","module","XSTATE_OBSERVABLE_NEXT","XSTATE_OBSERVABLE_ERROR","XSTATE_OBSERVABLE_COMPLETE","fromObservable","observableCreator","transition","event","status","type","context","data","error","input","undefined","_subscription","X","getInitialSnapshot","_","output","state","self","emit","next","_relay","err","complete","restoreSnapshot","XSTATE_PROMISE_RESOLVE","XSTATE_PROMISE_REJECT","controllerMap","WeakMap","fromPromise","promiseCreator","scope","resolvedValue","get","abort","controller","AbortController","set","Promise","resolve","signal","then","response","delete","errorData","initialContext","createSpawner","actorScope","spawnedChildren","src","systemId","id","parent","syncSnapshot","spawn","defer","Stopped","resolveAssign","actionArgs","actionParams","assignment","assignArgs","partialUpdate","key","keys","propAssignment","updatedContext","assign","length","_args","_params","resolveEmit","args","eventOrExpr","executeEmit","execute","SpecialTargets","resolveSendTo","to","delay","extra","delaysMap","delays","resolvedEvent","resolvedDelay","configDelay","resolvedTarget","targetActorRef","Parent","_parent","Internal","startsWith","slice","deferredActorIds","includes","targetId","retryResolveSendTo","params","executeSendTo","scheduler","schedule","sendTo","retryResolve","resolveEnqueueActions","collect","actions","enqueue","action","cancel","raise","sendParent","spawnChild","stopChild","check","guard","enqueueActions","getDevTools","globalThis","__xstate__","devToolsAdapter","service","devTools","register","Mailbox","constructor","_process","this","_active","_current","_last","flush","clear","enqueued","consumed","STATE_DELIMITER","TARGETLESS_KEY","NULL_EVENT","WILDCARD","XSTATE_INIT","XSTATE_ERROR","XSTATE_STOP","createDoneStateEvent","createErrorActorEvent","actorId","createInitEvent","reportUnhandledError","setTimeout","symbolObservable","Symbol","observable","matchesState","parentStateId","childStateId","parentStateValue","toStateValue","childStateValue","every","toStatePath","stateId","isArray","result","segment","i","charCodeAt","stateValue","statePath","marker","previous","pathToStateValue","mapValues","collection","iteratee","collectionKeys","toArrayStrict","toArray","resolveOutput","mapper","Array","toTransitionConfigArray","configLike","map","transitionLike","target","normalizeTarget","toObserver","nextHandler","errorHandler","completionHandler","isObserver","bind","createInvokeId","stateNodeId","index","resolveReferencedActor","match","actors","indexStr","nodeId","invokeConfig","getStateNodeById","invoke","createScheduledEventId","sessionId","idCounter","executingCustomAction","$$ACTOR_TYPE","ProcessingStatus","defaultOptions","clock","fn","ms","clearTimeout","logger","console","log","Actor","mailbox","eventListeners","Map","NotStarted","_syncSnapshot","_actorScope","_systemId","_doneEvent","_deferred","resolvedOptions","inspect","rootActor","keyedActors","reverseKeyedActors","inspectionObservers","timerMap","source","Math","random","toString","scheduledEvent","startedAt","Date","now","scheduledEventId","_scheduledEvents","timeout","cancelAll","_bookId","_register","_unregister","_set","existing","observerOrFn","observer","add","_sendInspectionEvent","size","resolvedInspectionEvent","rootId","sourceRef","_send","scheduledEvents","scheduledId","_clock","_logger","createSystem","_stop","emittedEvent","listeners","wildcardListener","allListeners","handler","actionExecutor","exec","saveExecutingCustomAction","info","Running","_initState","persistedState","update","deferredFn","shift","_stopProcedure","_complete","invokeId","_error","nextListenerOrObserver","errorListener","completeListener","on","wrappedHandler","initEvent","attachDevTools","nextState","caughtError","_reportError","reportError","err2","toJSON","xstate$$type","createActor","resolveCancel","sendId","executeCancel","resolveSpawn","_actionParams","resolvedId","resolvedInput","cloneMachineSnapshot","executeSpawn","resolveStop","actorRefOrString","resolvedActorRef","executeStop","checkStateIn","isStateId","_nodes","some","sn","matches","stateIn","checkAnd","guards","evaluateGuard","and","checkOr","or","isInline","resolved","guardArgs","guardParams","isAtomicStateNode","stateNode","getChildren","states","filter","getProperAncestors","toStateNode","ancestors","getAllStateNodes","stateNodes","nodeSet","adjList","getAdjList","s","has","initialStates","getInitialStateNodesWithTheirAncestors","initialStateNode","getValueFromAdj","baseNode","childStateNodes","childStateNode","getStateValue","rootNode","isInFinalState","stateNodeSet","str","getCandidates","receivedEventType","transitions","eventDescriptor","endsWith","partialEventTokens","split","eventTokens","tokenIndex","partialEventToken","eventToken","sort","flatMap","getDelayedTransitions","afterConfig","after","configTransition","resolvedTransition","Number","isNaN","eventType","afterEvent","delayRef","entry","exit","mutateEntryExit","delayedTransition","formatTransition","descriptor","transitionConfig","normalizedTarget","reenter","targets","isInternalTarget","getStateNodeByPath","message","resolveTarget","formatTransitions","transitionsConfig","onDone","invokeDef","onError","onSnapshot","formatInitialTransition","_target","resolveHistoryDefaultTransition","initial","isHistoryNode","getInitialStateNodes","initialState","ancestor","iter","descStateNode","getStateNode","stateKey","arrayStatePath","currentStateNode","getStateNodes","childStateKeys","subStateKey","Boolean","root","concat","reduce","allSubStateNodes","subStateNode","subStateNodes","transitionNode","transitionAtomicNode","subStateKeys","transitionCompoundNode","allInnerTransitions","subStateValue","innerTransitions","transitionParallelNode","getHistoryNodes","isDescendant","parentStateNode","hasIntersection","s1","s2","set1","set2","item","removeConflictingTransitions","enabledTransitions","historyValue","filteredTransitions","t1","t1Preempted","transitionsToRemove","t2","computeExitSet","t3","from","getEffectiveTargetStates","targetNode","node","getTransitionDomain","targetStates","lca","head","tail","findLeastCommonAncestor","statesToExit","domain","microstep","currentSnapshot","isInitial","internalQueue","mutStateNodeSet","nextSnapshot","changedHistory","order","exitStateNode","historyNode","predicate","history","resolveActionsAndContext","def","exitStates","statesToEnter","statesForDefaultEntry","addDescendantStatesToEnter","addAncestorStatesToEnter","computeEntrySet","completedNodes","stateNodeToEnter","initialActions","ancestorMarker","rootCompletionNode","getMachineOutput","enterStates","nextStateNodes","prevStateNodes","nextStateNodeSet","areStateNodeCollectionsEqual","doneStateEvent","historyStateNodes","addProperAncestorStatesToEnter","historyDefaultTransition","reentrancyDomain","anc","getAction","actionType","resolveAndExecuteActionsWithContext","retries","intermediateSnapshot","resolvedAction","name","builtinAction","macrostep","microstates","addMicrostate","microstate","_transitions","stopChildren","nextEvent","currentEvent","isErr","isErrorActorEvent","selectTransitions","shouldSelectEventlessTransitions","selectEventlessTransitions","previousState","getTransitionData","enabledTransitionSet","atomicStates","loop","always","resolveStateValue","machineSnapshotMatches","testValue","machineSnapshotHasTag","tag","tags","machineSnapshotCan","transitionData","machineSnapshotToJSON","nodes","getMeta","can","hasTag","jsonValues","machineSnapshotGetMeta","acc","meta","createMachineSnapshot","childrenJson","persistContext","contextPart","copy","resolveRaise","executeRaise","cache","memo","object","memoizedData","EMPTY_OBJECT","toSerializableAction","StateNode","path","description","_key","_machine","join","S","idMap","stateConfig","_initialize","N","definition","version","flat","sourceName","invokeDefValues","selectedTransition","candidates","candidate","resolvedContext","guardPassed","guardType","events","ownEvents","StateMachine","schemas","__xstatenode","provide","resolveState","resolvedStateValue","getPreInitialState","preInitial","preInitialState","macroState","fullPath","relativePath","resolvedStateId","STATE_IDENTIFIER","snapshotChildren","actorData","childState","restoredSnapshot","seen","reviveContext","$","createMachine","setup"],"sourceRoot":""}