xstate 5.0.0-beta.8 → 5.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (127) hide show
  1. package/README.md +10 -8
  2. package/actions/dist/xstate-actions.cjs.d.mts +2 -0
  3. package/actions/dist/xstate-actions.cjs.d.mts.map +1 -0
  4. package/actions/dist/xstate-actions.cjs.d.ts +1 -0
  5. package/actions/dist/xstate-actions.cjs.d.ts.map +1 -0
  6. package/actions/dist/xstate-actions.cjs.js +19 -5
  7. package/actions/dist/xstate-actions.cjs.mjs +13 -0
  8. package/actions/dist/xstate-actions.development.cjs.js +21 -0
  9. package/actions/dist/xstate-actions.development.cjs.mjs +13 -0
  10. package/actions/dist/xstate-actions.development.esm.js +3 -0
  11. package/actions/dist/xstate-actions.esm.js +3 -2
  12. package/actions/dist/xstate-actions.umd.min.js +1 -1
  13. package/actions/dist/xstate-actions.umd.min.js.map +1 -1
  14. package/actors/dist/xstate-actors.cjs.d.mts +2 -0
  15. package/actors/dist/xstate-actors.cjs.d.mts.map +1 -0
  16. package/actors/dist/xstate-actors.cjs.d.ts +1 -0
  17. package/actors/dist/xstate-actors.cjs.d.ts.map +1 -0
  18. package/actors/dist/xstate-actors.cjs.js +621 -4
  19. package/actors/dist/xstate-actors.cjs.mjs +8 -0
  20. package/actors/dist/xstate-actors.development.cjs.js +624 -0
  21. package/actors/dist/xstate-actors.development.cjs.mjs +8 -0
  22. package/actors/dist/xstate-actors.development.esm.js +615 -0
  23. package/actors/dist/xstate-actors.esm.js +615 -2
  24. package/actors/dist/xstate-actors.umd.min.js +1 -1
  25. package/actors/dist/xstate-actors.umd.min.js.map +1 -1
  26. package/dev/dist/xstate-dev.cjs.d.mts +2 -0
  27. package/dev/dist/xstate-dev.cjs.d.mts.map +1 -0
  28. package/dev/dist/xstate-dev.cjs.d.ts +1 -0
  29. package/dev/dist/xstate-dev.cjs.d.ts.map +1 -0
  30. package/dev/dist/xstate-dev.cjs.js +45 -4
  31. package/dev/dist/xstate-dev.cjs.mjs +5 -0
  32. package/{dist/index-ebaab3c9.cjs.dev.js → dev/dist/xstate-dev.development.cjs.js} +6 -7
  33. package/dev/dist/xstate-dev.development.cjs.mjs +5 -0
  34. package/{dist/index-50bd0aff.esm.js → dev/dist/xstate-dev.development.esm.js} +6 -8
  35. package/dev/dist/xstate-dev.esm.js +42 -1
  36. package/dev/dist/xstate-dev.umd.min.js +1 -1
  37. package/dev/dist/xstate-dev.umd.min.js.map +1 -1
  38. package/dist/declarations/src/SimulatedClock.d.ts +1 -1
  39. package/dist/declarations/src/State.d.ts +47 -73
  40. package/dist/declarations/src/StateMachine.d.ts +29 -57
  41. package/dist/declarations/src/StateNode.d.ts +36 -33
  42. package/dist/declarations/src/actions/assign.d.ts +11 -2
  43. package/dist/declarations/src/actions/cancel.d.ts +7 -3
  44. package/dist/declarations/src/actions/enqueueActions.d.ts +32 -0
  45. package/dist/declarations/src/actions/log.d.ts +7 -3
  46. package/dist/declarations/src/actions/raise.d.ts +7 -2
  47. package/dist/declarations/src/actions/send.d.ts +14 -36
  48. package/dist/declarations/src/actions/spawnChild.d.ts +29 -0
  49. package/dist/declarations/src/actions/stopChild.d.ts +18 -0
  50. package/dist/declarations/src/actions.d.ts +8 -48
  51. package/dist/declarations/src/actors/callback.d.ts +91 -8
  52. package/dist/declarations/src/actors/index.d.ts +6 -28
  53. package/dist/declarations/src/actors/observable.d.ts +101 -18
  54. package/dist/declarations/src/actors/promise.d.ts +80 -10
  55. package/dist/declarations/src/actors/transition.d.ts +64 -9
  56. package/dist/declarations/src/constants.d.ts +3 -0
  57. package/dist/declarations/src/createMachine.d.ts +20 -0
  58. package/dist/declarations/src/dev/index.d.ts +6 -6
  59. package/dist/declarations/src/guards.d.ts +41 -8
  60. package/dist/declarations/src/index.d.ts +18 -23
  61. package/dist/declarations/src/interpreter.d.ts +150 -41
  62. package/dist/declarations/src/setup.d.ts +51 -0
  63. package/dist/declarations/src/spawn.d.ts +23 -2
  64. package/dist/declarations/src/stateUtils.d.ts +30 -45
  65. package/dist/declarations/src/system.d.ts +26 -2
  66. package/dist/declarations/src/typegenTypes.d.ts +40 -22
  67. package/dist/declarations/src/types.d.ts +528 -669
  68. package/dist/declarations/src/utils.d.ts +15 -52
  69. package/dist/declarations/src/waitFor.d.ts +2 -2
  70. package/dist/log-22e678c5.esm.js +364 -0
  71. package/dist/log-5e226275.cjs.js +372 -0
  72. package/dist/log-641cd926.development.cjs.js +394 -0
  73. package/dist/log-f196f85f.development.esm.js +386 -0
  74. package/dist/raise-34e25c2c.cjs.js +2368 -0
  75. package/dist/raise-62704519.development.cjs.js +2422 -0
  76. package/dist/raise-89c581c4.development.esm.js +2371 -0
  77. package/dist/raise-8bc422d1.esm.js +2317 -0
  78. package/dist/xstate.cjs.d.mts +2 -0
  79. package/dist/xstate.cjs.d.mts.map +1 -0
  80. package/dist/xstate.cjs.d.ts +1 -0
  81. package/dist/xstate.cjs.d.ts.map +1 -0
  82. package/dist/xstate.cjs.js +728 -4
  83. package/dist/xstate.cjs.mjs +39 -0
  84. package/dist/xstate.development.cjs.js +737 -0
  85. package/dist/xstate.development.cjs.mjs +39 -0
  86. package/dist/xstate.development.esm.js +699 -0
  87. package/dist/xstate.esm.js +561 -770
  88. package/dist/xstate.umd.min.js +1 -1
  89. package/dist/xstate.umd.min.js.map +1 -1
  90. package/guards/dist/xstate-guards.cjs.d.mts +2 -0
  91. package/guards/dist/xstate-guards.cjs.d.mts.map +1 -0
  92. package/guards/dist/xstate-guards.cjs.d.ts +1 -0
  93. package/guards/dist/xstate-guards.cjs.d.ts.map +1 -0
  94. package/guards/dist/xstate-guards.cjs.js +12 -5
  95. package/guards/dist/xstate-guards.cjs.mjs +7 -0
  96. package/guards/dist/xstate-guards.development.cjs.js +14 -0
  97. package/guards/dist/xstate-guards.development.cjs.mjs +7 -0
  98. package/guards/dist/xstate-guards.development.esm.js +2 -0
  99. package/guards/dist/xstate-guards.esm.js +2 -2
  100. package/guards/dist/xstate-guards.umd.min.js +1 -1
  101. package/guards/dist/xstate-guards.umd.min.js.map +1 -1
  102. package/package.json +59 -1
  103. package/actions/dist/xstate-actions.cjs.dev.js +0 -32
  104. package/actions/dist/xstate-actions.cjs.prod.js +0 -32
  105. package/actions/dynamicAction.ts +0 -42
  106. package/actors/dist/xstate-actors.cjs.dev.js +0 -22
  107. package/actors/dist/xstate-actors.cjs.prod.js +0 -22
  108. package/dev/dist/xstate-dev.cjs.dev.js +0 -11
  109. package/dev/dist/xstate-dev.cjs.prod.js +0 -48
  110. package/dist/actions-900f9761.cjs.prod.js +0 -4349
  111. package/dist/actions-c8d7df32.esm.js +0 -4332
  112. package/dist/actions-d06ca158.cjs.dev.js +0 -4387
  113. package/dist/declarations/actions/dynamicAction.d.ts +0 -5
  114. package/dist/declarations/src/Machine.d.ts +0 -4
  115. package/dist/declarations/src/Mailbox.d.ts +0 -12
  116. package/dist/declarations/src/actionTypes.d.ts +0 -16
  117. package/dist/declarations/src/actions/choose.d.ts +0 -3
  118. package/dist/declarations/src/actions/invoke.d.ts +0 -3
  119. package/dist/declarations/src/actions/pure.d.ts +0 -6
  120. package/dist/declarations/src/actions/stop.d.ts +0 -7
  121. package/dist/declarations/src/environment.d.ts +0 -1
  122. package/dist/declarations/src/mapState.d.ts +0 -3
  123. package/dist/declarations/src/memo.d.ts +0 -2
  124. package/dist/xstate.cjs.dev.js +0 -956
  125. package/dist/xstate.cjs.prod.js +0 -953
  126. package/guards/dist/xstate-guards.cjs.dev.js +0 -15
  127. package/guards/dist/xstate-guards.cjs.prod.js +0 -15
@@ -0,0 +1,2 @@
1
+ export * from "../../dist/declarations/src/guards.js";
2
+ //# sourceMappingURL=xstate-guards.cjs.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"xstate-guards.cjs.d.mts","sourceRoot":"","sources":["../../dist/declarations/src/guards.d.ts"],"names":[],"mappings":"AAAA"}
@@ -1 +1,2 @@
1
1
  export * from "../../dist/declarations/src/guards";
2
+ //# sourceMappingURL=xstate-guards.cjs.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"xstate-guards.cjs.d.ts","sourceRoot":"","sources":["../../dist/declarations/src/guards.d.ts"],"names":[],"mappings":"AAAA"}
@@ -1,7 +1,14 @@
1
1
  'use strict';
2
2
 
3
- if (process.env.NODE_ENV === "production") {
4
- module.exports = require("./xstate-guards.cjs.prod.js");
5
- } else {
6
- module.exports = require("./xstate-guards.cjs.dev.js");
7
- }
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var guards_dist_xstateGuards = require('../../dist/raise-34e25c2c.cjs.js');
6
+ require('../../dev/dist/xstate-dev.cjs.js');
7
+
8
+
9
+
10
+ exports.and = guards_dist_xstateGuards.and;
11
+ exports.evaluateGuard = guards_dist_xstateGuards.evaluateGuard;
12
+ exports.not = guards_dist_xstateGuards.not;
13
+ exports.or = guards_dist_xstateGuards.or;
14
+ exports.stateIn = guards_dist_xstateGuards.stateIn;
@@ -0,0 +1,7 @@
1
+ export {
2
+ and,
3
+ evaluateGuard,
4
+ not,
5
+ or,
6
+ stateIn
7
+ } from "./xstate-guards.cjs.js";
@@ -0,0 +1,14 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var guards_dist_xstateGuards = require('../../dist/raise-62704519.development.cjs.js');
6
+ require('../../dev/dist/xstate-dev.development.cjs.js');
7
+
8
+
9
+
10
+ exports.and = guards_dist_xstateGuards.and;
11
+ exports.evaluateGuard = guards_dist_xstateGuards.evaluateGuard;
12
+ exports.not = guards_dist_xstateGuards.not;
13
+ exports.or = guards_dist_xstateGuards.or;
14
+ exports.stateIn = guards_dist_xstateGuards.stateIn;
@@ -0,0 +1,7 @@
1
+ export {
2
+ and,
3
+ evaluateGuard,
4
+ not,
5
+ or,
6
+ stateIn
7
+ } from "./xstate-guards.development.cjs.js";
@@ -0,0 +1,2 @@
1
+ export { H as and, e as evaluateGuard, I as not, J as or, K as stateIn } from '../../dist/raise-89c581c4.development.esm.js';
2
+ import '../../dev/dist/xstate-dev.development.esm.js';
@@ -1,2 +1,2 @@
1
- export { ag as and, e as evaluateGuard, af as not, ah as or, ae as stateIn, as as toGuardDefinition } from '../../dist/actions-c8d7df32.esm.js';
2
- import '../../dist/index-50bd0aff.esm.js';
1
+ export { H as and, e as evaluateGuard, I as not, J as or, K as stateIn } from '../../dist/raise-8bc422d1.esm.js';
2
+ import '../../dev/dist/xstate-dev.esm.js';
@@ -1,2 +1,2 @@
1
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).XStateGuards={})}(this,(function(e){"use strict";function t(e){return"string"==typeof e}function n(e,r){var a;return t(e)?{type:e,predicate:(null==r?void 0:r(e))||void 0,params:{type:e}}:"function"==typeof e?{type:e.name,predicate:e,params:{type:e.name,name:e.name}}:{type:e.type,params:e.params||e,children:null===(a=e.children)||void 0===a?void 0:a.map((function(e){return n(e,r)})),predicate:(null==r?void 0:r(e.type))||e.predicate}}e.and=function(e){return{type:"xstate.boolean",params:{op:"and"},children:e.map((function(e){return n(e)})),predicate:function(e){var t=e.evaluate,n=e.guard,r=e.context,a=e._event,o=e.state;return n.children.every((function(e){return t(e,r,a,o)}))}}},e.evaluateGuard=function e(t,n,r,a){var o,i,u,d=a.machine,c=null!==(o=null==d||null===(i=d.options)||void 0===i||null===(u=i.guards)||void 0===u?void 0:u[t.type])&&void 0!==o?o:t.predicate;if(!c)throw new Error("Guard '".concat(t.type,"' is not implemented.'."));return c({context:n,event:r.data,state:a,guard:t,_event:r,evaluate:e})},e.not=function(e){return{type:"xstate.boolean",params:{op:"not"},children:[n(e)],predicate:function(e){var t=e.evaluate,n=e.guard,r=e.context,a=e._event,o=e.state;return!t(n.children[0],r,a,o)}}},e.or=function(e){return{type:"xstate.boolean",params:{op:"or"},children:e.map((function(e){return n(e)})),predicate:function(e){var t=e.evaluate,n=e.guard,r=e.context,a=e._event,o=e.state;return n.children.some((function(e){return t(e,r,a,o)}))}}},e.stateIn=function(e){return{type:"xstate.guard:in",params:{stateValue:e},predicate:function(n){var r=n.state;return t(e)&&"#"===e[0]?r.configuration.some((function(t){return t.id===e.slice(1)})):r.matches(e)}}},e.toGuardDefinition=n,Object.defineProperty(e,"__esModule",{value:!0})}));
1
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).XStateGuards={})}(this,(function(e){"use strict";const t=e=>"#"===e[0];function n(e,n,{stateValue:r}){if("string"==typeof r&&t(r)){const t=e.machine.getStateNodeById(r);return e._nodes.some((e=>e===t))}return e.matches(r)}function r(e,{context:t,event:n},{guards:r}){return!i(r[0],t,n,e)}function o(e,{context:t,event:n},{guards:r}){return r.every((r=>i(r,t,n,e)))}function u(e,{context:t,event:n},{guards:r}){return r.some((r=>i(r,t,n,e)))}function i(e,t,n,r){const{machine:o}=r,u="function"==typeof e,c=u?e:o.implementations.guards["string"==typeof e?e:e.type];if(!u&&!c)throw new Error(`Guard '${"string"==typeof e?e:e.type}' is not implemented.'.`);if("function"!=typeof c)return i(c,t,n,r);const f={context:t,event:n},s=u||"string"==typeof e?void 0:"params"in e?"function"==typeof e.params?e.params({context:t,event:n}):e.params:void 0;if(!("check"in c))return c(f,s);return c.check(r,f,c)}e.and=function(e){function t(e,t){return!1}return t.check=o,t.guards=e,t},e.evaluateGuard=i,e.not=function(e){function t(e,t){return!1}return t.check=r,t.guards=[e],t},e.or=function(e){function t(e,t){return!1}return t.check=u,t.guards=e,t},e.stateIn=function(e){function t(e,t){return!1}return t.check=n,t.stateValue=e,t},Object.defineProperty(e,"__esModule",{value:!0})}));
2
2
  //# sourceMappingURL=xstate-guards.umd.min.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"xstate-guards.umd.min.js","sources":["../../src/utils.ts","../../src/guards.ts","../../src/constants.ts","../../src/stateUtils.ts"],"sourcesContent":["import { AnyActorBehavior, AnyState } from './index.ts';\nimport { errorExecution, errorPlatform } from './actionTypes.ts';\nimport { NULL_EVENT, STATE_DELIMITER, TARGETLESS_KEY } from './constants.ts';\nimport { IS_PRODUCTION } from './environment.ts';\nimport type { StateNode } from './StateNode.ts';\nimport type {\n ActorBehavior,\n EventObject,\n EventType,\n InvokeConfig,\n MachineContext,\n Mapper,\n Observer,\n PropertyMapper,\n SCXML,\n SCXMLErrorEvent,\n SingleOrArray,\n StateLike,\n StateValue,\n Subscribable,\n TransitionConfig,\n TransitionConfigTarget\n} from './types.ts';\n\nexport function keys<T extends object>(value: T): Array<keyof T & string> {\n return Object.keys(value) as Array<keyof T & string>;\n}\n\nexport function matchesState(\n parentStateId: StateValue,\n childStateId: StateValue,\n delimiter: string = STATE_DELIMITER\n): boolean {\n const parentStateValue = toStateValue(parentStateId, delimiter);\n const childStateValue = toStateValue(childStateId, delimiter);\n\n if (isString(childStateValue)) {\n if (isString(parentStateValue)) {\n return childStateValue === parentStateValue;\n }\n\n // Parent more specific than child\n return false;\n }\n\n if (isString(parentStateValue)) {\n return parentStateValue in childStateValue;\n }\n\n return Object.keys(parentStateValue).every((key) => {\n if (!(key in childStateValue)) {\n return false;\n }\n\n return matchesState(parentStateValue[key], childStateValue[key]);\n });\n}\n\nexport function toStatePath(\n stateId: string | string[],\n delimiter: string\n): string[] {\n try {\n if (isArray(stateId)) {\n return stateId;\n }\n\n return stateId.toString().split(delimiter);\n } catch (e) {\n throw new Error(`'${stateId}' is not a valid state path.`);\n }\n}\n\nexport function isStateLike(state: any): state is AnyState {\n return (\n typeof state === 'object' &&\n 'value' in state &&\n 'context' in state &&\n 'event' in state &&\n '_event' in state\n );\n}\n\nexport function toStateValue(\n stateValue: StateLike<any> | StateValue | string[],\n delimiter: string\n): StateValue {\n if (isStateLike(stateValue)) {\n return stateValue.value;\n }\n\n if (isArray(stateValue)) {\n return pathToStateValue(stateValue);\n }\n\n if (typeof stateValue !== 'string') {\n return stateValue as StateValue;\n }\n\n const statePath = toStatePath(stateValue as string, delimiter);\n\n return pathToStateValue(statePath);\n}\n\nexport function pathToStateValue(statePath: string[]): StateValue {\n if (statePath.length === 1) {\n return statePath[0];\n }\n\n const value = {};\n let marker = value;\n\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 marker[statePath[i]] = {};\n marker = marker[statePath[i]];\n }\n }\n\n return value;\n}\n\nexport function mapValues<P, O extends Record<string, unknown>>(\n collection: O,\n iteratee: (item: O[keyof O], key: keyof O, collection: O, i: number) => P\n): { [key in keyof O]: P };\nexport function mapValues(\n collection: Record<string, unknown>,\n iteratee: (\n item: unknown,\n key: string,\n collection: Record<string, unknown>,\n i: number\n ) => unknown\n) {\n const result: Record<string, unknown> = {};\n\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\n return result;\n}\n\nexport function mapFilterValues<T, P>(\n collection: { [key: string]: T },\n iteratee: (item: T, key: string, collection: { [key: string]: T }) => P,\n predicate: (item: T) => boolean\n): { [key: string]: P } {\n const result: { [key: string]: P } = {};\n\n for (const key of Object.keys(collection)) {\n const item = collection[key];\n\n if (!predicate(item)) {\n continue;\n }\n\n result[key] = iteratee(item, key, collection);\n }\n\n return result;\n}\n\n/**\n * Retrieves a value at the given path.\n * @param props The deep path to the prop of the desired value\n */\nexport function path<T extends Record<string, any>>(props: string[]): any {\n return (object: T): any => {\n let result: T = object;\n\n for (const prop of props) {\n result = result[prop as keyof typeof result];\n }\n\n return result;\n };\n}\n\nexport function toStatePaths(stateValue: StateValue | undefined): string[][] {\n if (!stateValue) {\n return [[]];\n }\n\n if (isString(stateValue)) {\n return [[stateValue]];\n }\n\n const result = flatten(\n Object.keys(stateValue).map((key) => {\n const subStateValue = stateValue[key];\n\n if (\n typeof subStateValue !== 'string' &&\n (!subStateValue || !Object.keys(subStateValue).length)\n ) {\n return [[key]];\n }\n\n return toStatePaths(stateValue[key]).map((subPath) => {\n return [key].concat(subPath);\n });\n })\n );\n\n return result;\n}\n\nexport function flatten<T>(array: Array<T | T[]>): T[] {\n return ([] as T[]).concat(...array);\n}\n\nexport function toArrayStrict<T>(value: T[] | T): T[] {\n if (isArray(value)) {\n return value;\n }\n return [value];\n}\n\nexport function toArray<T>(value: T[] | T | undefined): T[] {\n if (value === undefined) {\n return [];\n }\n return toArrayStrict(value);\n}\n\nexport function mapContext<\n TContext extends MachineContext,\n TEvent extends EventObject\n>(\n mapper: Mapper<TContext, TEvent, any> | PropertyMapper<TContext, TEvent, any>,\n context: TContext,\n _event: SCXML.Event<TEvent>\n): any {\n if (isFunction(mapper)) {\n return mapper({ context, event: _event.data });\n }\n\n const result = {} as any;\n const args = { context, event: _event.data };\n\n for (const key of Object.keys(mapper)) {\n const subMapper = mapper[key];\n\n if (isFunction(subMapper)) {\n result[key] = subMapper(args);\n } else {\n result[key] = subMapper;\n }\n }\n\n return result;\n}\n\nexport function isBuiltInEvent(eventType: EventType): boolean {\n return /^(done|error)\\./.test(eventType);\n}\n\nexport function isPromiseLike(value: any): value is PromiseLike<any> {\n if (value instanceof Promise) {\n return true;\n }\n // Check if shape matches the Promise/A+ specification for a \"thenable\".\n if (\n value !== null &&\n (isFunction(value) || typeof value === 'object') &&\n isFunction(value.then)\n ) {\n return true;\n }\n return false;\n}\n\nexport function isBehavior(value: any): value is ActorBehavior<any, any> {\n return (\n value !== null &&\n typeof value === 'object' &&\n 'transition' in value &&\n typeof value.transition === 'function'\n );\n}\n\nexport function partition<T, A extends T, B extends T>(\n items: T[],\n predicate: (item: T) => item is A\n): [A[], B[]] {\n const [truthy, falsy] = [[], []] as [A[], B[]];\n\n for (const item of items) {\n if (predicate(item)) {\n truthy.push(item);\n } else {\n falsy.push(item as B);\n }\n }\n\n return [truthy, falsy];\n}\n\n// tslint:disable-next-line:no-empty\nexport let warn: (\n condition: boolean | Error,\n message: string\n) => void = () => {};\n\nif (!IS_PRODUCTION) {\n warn = (condition: boolean | Error, message: string) => {\n const error = condition instanceof Error ? condition : undefined;\n if (!error && condition) {\n return;\n }\n\n if (console !== undefined) {\n const args: [string, ...any[]] = [`Warning: ${message}`];\n if (error) {\n args.push(error);\n }\n // tslint:disable-next-line:no-console\n console.warn.apply(console, args);\n }\n };\n}\n\nexport function isArray(value: any): value is any[] {\n return Array.isArray(value);\n}\n\n// tslint:disable-next-line:ban-types\nexport function isFunction(value: any): value is Function {\n return typeof value === 'function';\n}\n\nexport function isString(value: any): value is string {\n return typeof value === 'string';\n}\n\nexport function isObservable<T>(value: any): value is Subscribable<T> {\n try {\n return 'subscribe' in value && isFunction(value.subscribe);\n } catch (e) {\n return false;\n }\n}\n\nexport const uniqueId = (() => {\n let currentId = 0;\n\n return () => {\n currentId++;\n return currentId.toString(16);\n };\n})();\n\nexport function isSCXMLEvent<TEvent extends EventObject>(\n event: TEvent | SCXML.Event<TEvent>\n): event is SCXML.Event<TEvent> {\n return '$$type' in event && event.$$type === 'scxml';\n}\n\nexport function isSCXMLErrorEvent(\n event: SCXML.Event<any>\n): event is SCXMLErrorEvent {\n return (\n typeof event.name === 'string' &&\n (event.name === errorExecution || event.name.startsWith(errorPlatform))\n );\n}\n\nexport function toSCXMLEvent<TEvent extends EventObject>(\n event: TEvent | SCXML.Event<TEvent>,\n scxmlEvent?: Partial<SCXML.Event<TEvent>>\n): SCXML.Event<TEvent> {\n if (isSCXMLEvent(event)) {\n return event as SCXML.Event<TEvent>;\n }\n\n return {\n name: event.type,\n data: event,\n $$type: 'scxml',\n type: 'external',\n ...scxmlEvent\n };\n}\n\nexport function toTransitionConfigArray<\n TContext extends MachineContext,\n TEvent extends EventObject\n>(\n event: TEvent['type'] | typeof NULL_EVENT | '*',\n configLike: SingleOrArray<\n TransitionConfig<TContext, TEvent> | TransitionConfigTarget\n >\n): Array<\n TransitionConfig<TContext, TEvent> & {\n event: TEvent['type'] | typeof NULL_EVENT | '*';\n }\n> {\n const transitions = toArrayStrict(configLike).map((transitionLike) => {\n if (\n typeof transitionLike === 'undefined' ||\n typeof transitionLike === 'string'\n ) {\n return { target: transitionLike, event };\n }\n\n return { ...transitionLike, event };\n }) as Array<\n TransitionConfig<TContext, TEvent> & {\n event: TEvent['type'] | typeof NULL_EVENT | '*';\n } // TODO: fix 'as' (remove)\n >;\n\n return transitions;\n}\n\nexport function normalizeTarget<\n TContext extends MachineContext,\n TEvent extends EventObject\n>(\n target: SingleOrArray<string | StateNode<TContext, TEvent>> | undefined\n): Array<string | StateNode<TContext, TEvent>> | undefined {\n if (target === undefined || target === TARGETLESS_KEY) {\n return undefined;\n }\n return toArray(target);\n}\n\nexport function reportUnhandledExceptionOnInvocation(\n originalError: any,\n currentError: any,\n id: string\n) {\n if (!IS_PRODUCTION) {\n const originalStackTrace = originalError.stack\n ? ` Stacktrace was '${originalError.stack}'`\n : '';\n if (originalError === currentError) {\n // tslint:disable-next-line:no-console\n console.error(\n `Missing onError handler for invocation '${id}', error was '${originalError}'.${originalStackTrace}`\n );\n } else {\n const stackTrace = currentError.stack\n ? ` Stacktrace was '${currentError.stack}'`\n : '';\n // tslint:disable-next-line:no-console\n console.error(\n `Missing onError handler and/or unhandled exception/promise rejection for invocation '${id}'. ` +\n `Original error: '${originalError}'. ${originalStackTrace} Current error is '${currentError}'.${stackTrace}`\n );\n }\n }\n}\n\nexport function toInvokeConfig<\n TContext extends MachineContext,\n TEvent extends EventObject\n>(\n invocable: InvokeConfig<TContext, TEvent> | string | ActorBehavior<any, any>,\n id: string\n): InvokeConfig<TContext, TEvent> {\n if (typeof invocable === 'object') {\n if ('src' in invocable) {\n return invocable;\n }\n\n if ('transition' in invocable) {\n return {\n id,\n src: invocable\n };\n }\n }\n\n return {\n id,\n src: invocable\n };\n}\n\nexport function toObserver<T>(\n nextHandler?: Observer<T> | ((value: T) => void),\n errorHandler?: (error: any) => void,\n completionHandler?: () => void\n): Observer<T> {\n const noop = () => {};\n const isObserver = typeof nextHandler === 'object';\n const self = isObserver ? nextHandler : null;\n\n return {\n next: ((isObserver ? nextHandler.next : nextHandler) || noop).bind(self),\n error: ((isObserver ? nextHandler.error : errorHandler) || noop).bind(self),\n complete: (\n (isObserver ? nextHandler.complete : completionHandler) || noop\n ).bind(self)\n };\n}\n\nexport function createInvokeId(stateNodeId: string, index: number): string {\n return `${stateNodeId}:invocation[${index}]`;\n}\n\nexport function resolveReferencedActor(\n referenced:\n | AnyActorBehavior\n | { src: AnyActorBehavior; input: Mapper<any, any, any> | any }\n | undefined\n) {\n return referenced\n ? 'transition' in referenced\n ? { src: referenced, input: undefined }\n : referenced\n : undefined;\n}\n","import type {\n EventObject,\n StateValue,\n BooleanGuardDefinition,\n GuardConfig,\n GuardDefinition,\n SCXML,\n GuardPredicate,\n MachineContext\n} from './types.ts';\nimport { isStateId } from './stateUtils.ts';\nimport { isFunction, isString } from './utils.ts';\nimport type { State } from './State.ts';\n\nexport function stateIn<\n TContext extends MachineContext,\n TEvent extends EventObject\n>(stateValue: StateValue): GuardDefinition<TContext, TEvent> {\n return {\n type: 'xstate.guard:in',\n params: { stateValue },\n predicate: ({ state }) => {\n if (isString(stateValue) && isStateId(stateValue)) {\n return state.configuration.some((sn) => sn.id === stateValue.slice(1));\n }\n\n return state.matches(stateValue);\n }\n };\n}\n\nexport function not<\n TContext extends MachineContext,\n TEvent extends EventObject\n>(\n guard: GuardConfig<TContext, TEvent>\n): BooleanGuardDefinition<TContext, TEvent> {\n return {\n type: 'xstate.boolean',\n params: { op: 'not' },\n children: [toGuardDefinition(guard)],\n predicate: ({ evaluate, guard, context, _event, state }) => {\n return !evaluate(guard.children![0], context, _event, state);\n }\n };\n}\n\nexport function and<\n TContext extends MachineContext,\n TEvent extends EventObject\n>(\n guards: Array<GuardConfig<TContext, TEvent>>\n): BooleanGuardDefinition<TContext, TEvent> {\n return {\n type: 'xstate.boolean',\n params: { op: 'and' },\n children: guards.map((guard) => toGuardDefinition(guard)),\n predicate: ({ evaluate, guard, context, _event, state }) => {\n return guard.children!.every((childGuard) => {\n return evaluate(childGuard, context, _event, state);\n });\n }\n };\n}\n\nexport function or<TContext extends MachineContext, TEvent extends EventObject>(\n guards: Array<GuardConfig<TContext, TEvent>>\n): BooleanGuardDefinition<TContext, TEvent> {\n return {\n type: 'xstate.boolean',\n params: { op: 'or' },\n children: guards.map((guard) => toGuardDefinition(guard)),\n predicate: ({ evaluate, guard, context, _event, state }) => {\n return guard.children!.some((childGuard) => {\n return evaluate(childGuard, context, _event, state);\n });\n }\n };\n}\n\nexport function evaluateGuard<\n TContext extends MachineContext,\n TEvent extends EventObject\n>(\n guard: GuardDefinition<TContext, TEvent>,\n context: TContext,\n _event: SCXML.Event<TEvent>,\n state: State<TContext, TEvent>\n): boolean {\n const { machine } = state;\n\n const predicate = machine?.options?.guards?.[guard.type] ?? guard.predicate;\n\n if (!predicate) {\n throw new Error(`Guard '${guard.type}' is not implemented.'.`);\n }\n\n return predicate({\n context,\n event: _event.data,\n state,\n guard,\n _event,\n evaluate: evaluateGuard\n });\n}\n\nexport function toGuardDefinition<\n TContext extends MachineContext,\n TEvent extends EventObject\n>(\n guardConfig: GuardConfig<TContext, TEvent>,\n getPredicate?: (guardType: string) => GuardPredicate<TContext, TEvent>\n): GuardDefinition<TContext, TEvent> {\n if (isString(guardConfig)) {\n return {\n type: guardConfig,\n predicate: getPredicate?.(guardConfig) || undefined,\n params: { type: guardConfig }\n };\n }\n\n if (isFunction(guardConfig)) {\n return {\n type: guardConfig.name,\n predicate: guardConfig,\n params: {\n type: guardConfig.name,\n name: guardConfig.name\n }\n };\n }\n\n return {\n type: guardConfig.type,\n params: guardConfig.params || guardConfig,\n children: (\n guardConfig.children as Array<GuardConfig<TContext, TEvent>>\n )?.map((childGuard) => toGuardDefinition(childGuard, getPredicate)),\n predicate:\n getPredicate?.(guardConfig.type) || (guardConfig as any).predicate\n };\n}\n","export const STATE_DELIMITER = '.';\nexport const TARGETLESS_KEY = '';\nexport const NULL_EVENT = '';\nexport const STATE_IDENTIFIER = '#';\nexport const WILDCARD = '*';\n","import {\n toStatePath,\n toArray,\n warn,\n isArray,\n isFunction,\n isString,\n toTransitionConfigArray,\n normalizeTarget,\n toStateValue,\n mapContext,\n toSCXMLEvent\n} from './utils.ts';\nimport {\n BaseActionObject,\n EventObject,\n InvokeActionObject,\n StopActionObject,\n StateValue,\n TransitionConfig,\n TransitionDefinition,\n SingleOrArray,\n DelayExpr,\n SCXML,\n StateValueMap,\n RaiseActionObject,\n InitialTransitionConfig,\n MachineContext\n} from './types.ts';\nimport { cloneState, State } from './State.ts';\nimport {\n after,\n done,\n toActionObjects,\n actionTypes,\n resolveActionObject,\n raise\n} from './actions.ts';\nimport { cancel } from './actions/cancel.ts';\nimport { invoke } from './actions/invoke.ts';\nimport { stop } from './actions/stop.ts';\nimport { IS_PRODUCTION } from './environment.ts';\nimport { STATE_IDENTIFIER, NULL_EVENT, WILDCARD } from './constants.ts';\nimport { evaluateGuard, toGuardDefinition } from './guards.ts';\nimport type { StateNode } from './StateNode.ts';\nimport { isDynamicAction } from '../actions/dynamicAction.ts';\nimport {\n AnyActorContext,\n AnyEventObject,\n AnyHistoryValue,\n AnyState,\n AnyStateMachine,\n AnyStateNode,\n AnyTransitionDefinition,\n DelayedTransitionDefinition,\n HistoryValue,\n InitialTransitionDefinition,\n SendActionObject,\n StateFromMachine\n} from '.';\nimport { stopSignalType } from './actors/index.ts';\nimport { ActorStatus } from './interpreter.ts';\n\ntype Configuration<\n TContext extends MachineContext,\n TE extends EventObject\n> = Iterable<StateNode<TContext, TE>>;\ntype AnyConfiguration = Configuration<any, any>;\n\ntype AdjList = Map<AnyStateNode, Array<AnyStateNode>>;\n\nfunction getOutput<TContext extends MachineContext, TEvent extends EventObject>(\n configuration: StateNode<TContext, TEvent>[],\n context: TContext,\n _event: SCXML.Event<TEvent>\n) {\n const machine = configuration[0].machine;\n const finalChildStateNode = configuration.find(\n (stateNode) =>\n stateNode.type === 'final' && stateNode.parent === machine.root\n );\n\n return finalChildStateNode && finalChildStateNode.output\n ? mapContext(finalChildStateNode.output, context, _event)\n : undefined;\n}\n\nconst isAtomicStateNode = (stateNode: StateNode<any, any>) =>\n stateNode.type === 'atomic' || stateNode.type === 'final';\n\nfunction getChildren<TContext extends MachineContext, TE extends EventObject>(\n stateNode: StateNode<TContext, TE>\n): Array<StateNode<TContext, TE>> {\n return Object.values(stateNode.states).filter((sn) => sn.type !== 'history');\n}\n\nfunction getProperAncestors(\n stateNode: AnyStateNode,\n toStateNode: AnyStateNode | null\n): Array<typeof stateNode> {\n const ancestors: Array<typeof stateNode> = [];\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\n return ancestors;\n}\n\nexport function getConfiguration(\n stateNodes: Iterable<AnyStateNode>\n): Set<AnyStateNode> {\n const configuration = new Set(stateNodes);\n const configurationSet = new Set(stateNodes);\n\n const adjList = getAdjList(configurationSet);\n\n // add descendants\n for (const s of configuration) {\n // if previously active, add existing child nodes\n if (s.type === 'compound' && (!adjList.get(s) || !adjList.get(s)!.length)) {\n getInitialStateNodes(s).forEach((sn) => configurationSet.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\n if (!configurationSet.has(child)) {\n for (const initialStateNode of getInitialStateNodes(child)) {\n configurationSet.add(initialStateNode);\n }\n }\n }\n }\n }\n }\n\n // add all ancestors\n for (const s of configurationSet) {\n let m = s.parent;\n\n while (m) {\n configurationSet.add(m);\n m = m.parent;\n }\n }\n\n return configurationSet;\n}\n\nfunction getValueFromAdj(baseNode: AnyStateNode, adjList: AdjList): StateValue {\n const childStateNodes = adjList.get(baseNode);\n\n if (!childStateNodes) {\n return {}; // todo: fix?\n }\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\n const stateValue = {};\n for (const childStateNode of childStateNodes) {\n stateValue[childStateNode.key] = getValueFromAdj(childStateNode, adjList);\n }\n\n return stateValue;\n}\n\nexport function getAdjList<\n TContext extends MachineContext,\n TE extends EventObject\n>(configuration: Configuration<TContext, TE>): AdjList {\n const adjList: AdjList = new Map();\n\n for (const s of configuration) {\n if (!adjList.has(s)) {\n adjList.set(s, []);\n }\n\n if (s.parent) {\n if (!adjList.has(s.parent)) {\n adjList.set(s.parent, []);\n }\n\n adjList.get(s.parent)!.push(s);\n }\n }\n\n return adjList;\n}\n\nexport function getStateValue(\n rootNode: AnyStateNode,\n configuration: AnyConfiguration\n): StateValue {\n const config = getConfiguration(configuration);\n return getValueFromAdj(rootNode, getAdjList(config));\n}\n\nexport function isInFinalState(\n configuration: Array<AnyStateNode>,\n stateNode: AnyStateNode = configuration[0].machine.root\n): boolean {\n if (stateNode.type === 'compound') {\n return getChildren(stateNode).some(\n (s) => s.type === 'final' && configuration.includes(s)\n );\n }\n if (stateNode.type === 'parallel') {\n return getChildren(stateNode).every((sn) =>\n isInFinalState(configuration, sn)\n );\n }\n\n return false;\n}\n\nexport const isStateId = (str: string) => str[0] === STATE_IDENTIFIER;\n\nexport function getCandidates<TEvent extends EventObject>(\n stateNode: StateNode<any, TEvent>,\n receivedEventType: TEvent['type'],\n /**\n * If `true`, will use SCXML event partial token matching semantics\n * without the need for the \".*\" suffix\n */\n partialMatch: boolean = false\n): Array<TransitionDefinition<any, TEvent>> {\n const candidates = stateNode.transitions.filter((transition) => {\n const { eventType } = transition;\n // First, check the trivial case: event names are exactly equal\n if (eventType === receivedEventType) {\n return true;\n }\n\n // Then, check if transition is a wildcard transition,\n // which matches any non-transient events\n if (eventType === WILDCARD) {\n return true;\n }\n\n if (!partialMatch && !eventType.endsWith('.*')) {\n return false;\n }\n\n if (!IS_PRODUCTION) {\n warn(\n !/.*\\*.+/.test(eventType),\n `Wildcards can only be the last token of an event descriptor (e.g., \"event.*\") or the entire event descriptor (\"*\"). Check the \"${eventType}\" event.`\n );\n }\n\n const partialEventTokens = eventType.split('.');\n const eventTokens = receivedEventType.split('.');\n\n for (\n let tokenIndex = 0;\n tokenIndex < partialEventTokens.length;\n tokenIndex++\n ) {\n const partialEventToken = partialEventTokens[tokenIndex];\n const eventToken = eventTokens[tokenIndex];\n\n if (partialEventToken === '*') {\n const isLastToken = tokenIndex === partialEventTokens.length - 1;\n\n if (!IS_PRODUCTION) {\n warn(\n isLastToken,\n `Infix wildcards in transition events are not allowed. Check the \"${eventType}\" event.`\n );\n }\n\n return isLastToken;\n }\n\n if (partialEventToken !== eventToken) {\n return false;\n }\n }\n\n return true;\n });\n\n return candidates;\n}\n\n/**\n * All delayed transitions from the config.\n */\nexport function getDelayedTransitions<\n TContext extends MachineContext,\n TEvent extends EventObject\n>(\n stateNode: AnyStateNode\n): Array<DelayedTransitionDefinition<TContext, TEvent>> {\n const afterConfig = stateNode.config.after;\n if (!afterConfig) {\n return [];\n }\n\n const mutateEntryExit = (\n delay: string | number | DelayExpr<TContext, TEvent>,\n i: number\n ) => {\n const delayRef = isFunction(delay) ? `${stateNode.id}:delay[${i}]` : delay;\n const eventType = after(delayRef, stateNode.id);\n stateNode.entry.push(raise({ type: eventType } as TEvent, { delay }));\n stateNode.exit.push(cancel(eventType));\n return eventType;\n };\n\n const delayedTransitions = isArray(afterConfig)\n ? afterConfig.map((transition, i) => {\n const eventType = mutateEntryExit(transition.delay, i);\n return { ...transition, event: eventType };\n })\n : Object.keys(afterConfig).flatMap((delay, i) => {\n const configTransition = afterConfig[delay];\n const resolvedTransition = isString(configTransition)\n ? { target: configTransition }\n : configTransition;\n const resolvedDelay = !isNaN(+delay) ? +delay : delay;\n const eventType = mutateEntryExit(resolvedDelay, i);\n return toArray(resolvedTransition).map((transition) => ({\n ...transition,\n event: eventType,\n delay: resolvedDelay\n }));\n });\n return delayedTransitions.map((delayedTransition) => {\n const { delay } = delayedTransition;\n return {\n ...formatTransition(stateNode, delayedTransition),\n delay\n };\n });\n}\n\nexport function formatTransition<\n TContext extends MachineContext,\n TEvent extends EventObject\n>(\n stateNode: AnyStateNode,\n transitionConfig: TransitionConfig<TContext, TEvent> & {\n event: TEvent['type'] | typeof NULL_EVENT | '*';\n }\n): AnyTransitionDefinition {\n const normalizedTarget = normalizeTarget(transitionConfig.target);\n const reenter = transitionConfig.reenter ?? false;\n const { guards } = stateNode.machine.options;\n const target = resolveTarget(stateNode, normalizedTarget);\n\n // TODO: should this be part of a lint rule instead?\n if (!IS_PRODUCTION && (transitionConfig as any).cond) {\n throw new Error(\n `State \"${stateNode.id}\" has declared \\`cond\\` for one of its transitions. This property has been renamed to \\`guard\\`. Please update your code.`\n );\n }\n const transition = {\n ...transitionConfig,\n actions: toActionObjects(toArray(transitionConfig.actions)),\n guard: transitionConfig.guard\n ? toGuardDefinition(\n transitionConfig.guard,\n (guardType) => guards[guardType]\n )\n : undefined,\n target,\n source: stateNode,\n reenter,\n eventType: transitionConfig.event,\n toJSON: () => ({\n ...transition,\n source: `#${stateNode.id}`,\n target: target ? target.map((t) => `#${t.id}`) : undefined\n })\n };\n\n return transition;\n}\n\nexport function formatTransitions<\n TContext extends MachineContext,\n TEvent extends EventObject\n>(stateNode: AnyStateNode): Array<AnyTransitionDefinition> {\n const transitionConfigs: Array<\n TransitionConfig<TContext, TEvent> & {\n event: string;\n }\n > = [];\n if (Array.isArray(stateNode.config.on)) {\n transitionConfigs.push(...stateNode.config.on);\n } else if (stateNode.config.on) {\n const { [WILDCARD]: wildcardConfigs = [], ...namedTransitionConfigs } =\n stateNode.config.on;\n for (const eventType of Object.keys(namedTransitionConfigs)) {\n if (eventType === NULL_EVENT) {\n throw new Error(\n 'Null events (\"\") cannot be specified as a transition key. Use `always: { ... }` instead.'\n );\n }\n const eventTransitionConfigs = toTransitionConfigArray<TContext, TEvent>(\n eventType,\n namedTransitionConfigs![eventType as string]\n );\n\n transitionConfigs.push(...eventTransitionConfigs);\n // TODO: add dev-mode validation for unreachable transitions\n }\n transitionConfigs.push(\n ...toTransitionConfigArray(\n WILDCARD,\n wildcardConfigs as SingleOrArray<\n TransitionConfig<TContext, TEvent> & {\n event: '*';\n }\n >\n )\n );\n }\n const doneConfig = stateNode.config.onDone\n ? toTransitionConfigArray(\n String(done(stateNode.id)),\n stateNode.config.onDone\n )\n : [];\n const invokeConfig = stateNode.invoke.flatMap((invokeDef) => {\n const settleTransitions: any[] = [];\n if (invokeDef.onDone) {\n settleTransitions.push(\n ...toTransitionConfigArray(\n `done.invoke.${invokeDef.id}`,\n invokeDef.onDone\n )\n );\n }\n if (invokeDef.onError) {\n settleTransitions.push(\n ...toTransitionConfigArray(\n `error.platform.${invokeDef.id}`,\n invokeDef.onError\n )\n );\n }\n if (invokeDef.onSnapshot) {\n settleTransitions.push(\n ...toTransitionConfigArray(\n `xstate.snapshot.${invokeDef.id}`,\n invokeDef.onSnapshot\n )\n );\n }\n return settleTransitions;\n });\n const delayedTransitions = stateNode.after;\n const formattedTransitions = [\n ...doneConfig,\n ...invokeConfig,\n ...transitionConfigs\n ].flatMap(\n (\n transitionConfig: TransitionConfig<TContext, TEvent> & {\n event: TEvent['type'] | '*';\n }\n ) =>\n toArray(transitionConfig).map((transition) =>\n formatTransition(stateNode, transition)\n )\n );\n for (const delayedTransition of delayedTransitions) {\n formattedTransitions.push(delayedTransition as any);\n }\n return formattedTransitions;\n}\n\nexport function formatInitialTransition<\n TContext extends MachineContext,\n TEvent extends EventObject\n>(\n stateNode: AnyStateNode,\n _target: SingleOrArray<string> | InitialTransitionConfig<TContext, TEvent>\n): InitialTransitionDefinition<TContext, TEvent> {\n if (isString(_target) || isArray(_target)) {\n const targets = toArray(_target).map((t) => {\n // Resolve state string keys (which represent children)\n // to their state node\n const descStateNode = isString(t)\n ? isStateId(t)\n ? stateNode.machine.getStateNodeById(t)\n : stateNode.states[t]\n : t;\n\n if (!descStateNode) {\n throw new Error(\n `Initial state node \"${t}\" not found on parent state node #${stateNode.id}`\n );\n }\n\n if (!isDescendant(descStateNode, stateNode)) {\n throw new Error(\n `Invalid initial target: state node #${descStateNode.id} is not a descendant of #${stateNode.id}`\n );\n }\n\n return descStateNode;\n });\n const resolvedTarget = resolveTarget(stateNode, targets);\n\n const transition = {\n source: stateNode,\n actions: [],\n eventType: null as any,\n reenter: false,\n target: resolvedTarget!,\n toJSON: () => ({\n ...transition,\n source: `#${stateNode.id}`,\n target: resolvedTarget\n ? resolvedTarget.map((t) => `#${t.id}`)\n : undefined\n })\n };\n\n return transition;\n }\n\n return formatTransition(stateNode, {\n target: toArray(_target.target).map((t) => {\n if (isString(t)) {\n return isStateId(t) ? t : `${stateNode.machine.delimiter}${t}`;\n }\n\n return t;\n }),\n actions: _target.actions,\n event: null as any\n }) as InitialTransitionDefinition<TContext, TEvent>;\n}\n\nexport function resolveTarget(\n stateNode: AnyStateNode,\n targets: Array<string | AnyStateNode> | undefined\n): Array<AnyStateNode> | undefined {\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 (!isString(target)) {\n return target;\n }\n if (isStateId(target)) {\n return stateNode.machine.getStateNodeById(target);\n }\n\n const isInternalTarget = target[0] === stateNode.machine.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(\n stateNode.parent,\n resolvedTarget\n );\n return targetStateNode;\n } catch (err) {\n throw new Error(\n `Invalid transition definition for state node '${stateNode.id}':\\n${err.message}`\n );\n }\n } else {\n throw new Error(\n `Invalid target: \"${target}\" is not a valid target from the root node. Did you mean \".${target}\"?`\n );\n }\n });\n}\n\nfunction resolveHistoryTarget<\n TContext extends MachineContext,\n TEvent extends EventObject\n>(stateNode: AnyStateNode & { type: 'history' }): Array<AnyStateNode> {\n const normalizedTarget = normalizeTarget<TContext, TEvent>(stateNode.target);\n if (!normalizedTarget) {\n return stateNode.parent!.initial.target;\n }\n return normalizedTarget.map((t) =>\n typeof t === 'string' ? getStateNodeByPath(stateNode.parent!, t) : t\n );\n}\n\nfunction isHistoryNode(\n stateNode: AnyStateNode\n): stateNode is AnyStateNode & { type: 'history' } {\n return stateNode.type === 'history';\n}\n\nexport function getInitialStateNodes(\n stateNode: AnyStateNode\n): Array<AnyStateNode> {\n const set = new Set<AnyStateNode>();\n\n function iter(descStateNode: AnyStateNode): void {\n if (set.has(descStateNode)) {\n return;\n }\n set.add(descStateNode);\n if (descStateNode.type === 'compound') {\n for (const targetStateNode of descStateNode.initial.target) {\n for (const a of getProperAncestors(targetStateNode, stateNode)) {\n set.add(a);\n }\n\n iter(targetStateNode);\n }\n } else if (descStateNode.type === 'parallel') {\n for (const child of getChildren(descStateNode)) {\n iter(child);\n }\n }\n }\n\n iter(stateNode);\n\n return [...set];\n}\n/**\n * Returns the child state node from its relative `stateKey`, or throws.\n */\nexport function getStateNode(\n stateNode: AnyStateNode,\n stateKey: string\n): AnyStateNode {\n if (isStateId(stateKey)) {\n return stateNode.machine.getStateNodeById(stateKey);\n }\n if (!stateNode.states) {\n throw new Error(\n `Unable to retrieve child state '${stateKey}' from '${stateNode.id}'; no child states exist.`\n );\n }\n const result = stateNode.states[stateKey];\n if (!result) {\n throw new Error(\n `Child state '${stateKey}' does not exist on '${stateNode.id}'`\n );\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 */\nexport function getStateNodeByPath(\n stateNode: AnyStateNode,\n statePath: string | string[]\n): AnyStateNode {\n if (typeof statePath === 'string' && isStateId(statePath)) {\n try {\n return stateNode.machine.getStateNodeById(statePath);\n } catch (e) {\n // try individual paths\n // throw e;\n }\n }\n const arrayStatePath = toStatePath(\n statePath,\n stateNode.machine.delimiter\n ).slice();\n let currentStateNode: AnyStateNode = 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 state The state value or State instance\n */\nexport function getStateNodes<\n TContext extends MachineContext,\n TEvent extends EventObject\n>(\n stateNode: AnyStateNode,\n state: StateValue | State<TContext, TEvent>\n): Array<AnyStateNode> {\n const stateValue =\n state instanceof State\n ? state.value\n : toStateValue(state, stateNode.machine.delimiter);\n\n if (isString(stateValue)) {\n return [stateNode, stateNode.states[stateValue]];\n }\n\n const childStateKeys = Object.keys(stateValue);\n const childStateNodes: Array<AnyStateNode> = childStateKeys\n .map((subStateKey) => getStateNode(stateNode, subStateKey))\n .filter(Boolean);\n\n return [stateNode.machine.root, stateNode].concat(\n childStateNodes,\n childStateKeys.reduce((allSubStateNodes, subStateKey) => {\n const subStateNode = getStateNode(stateNode, subStateKey);\n if (!subStateNode) {\n return allSubStateNodes;\n }\n const subStateNodes = getStateNodes(\n subStateNode,\n stateValue[subStateKey]\n );\n\n return allSubStateNodes.concat(subStateNodes);\n }, [] as Array<AnyStateNode>)\n );\n}\n\nexport function transitionAtomicNode<\n TContext extends MachineContext,\n TEvent extends EventObject\n>(\n stateNode: AnyStateNode,\n stateValue: string,\n state: State<TContext, TEvent>,\n _event: SCXML.Event<TEvent>\n): Array<TransitionDefinition<TContext, TEvent>> | undefined {\n const childStateNode = getStateNode(stateNode, stateValue);\n const next = childStateNode.next(state, _event);\n\n if (!next || !next.length) {\n return stateNode.next(state, _event);\n }\n\n return next;\n}\n\nexport function transitionCompoundNode<\n TContext extends MachineContext,\n TEvent extends EventObject\n>(\n stateNode: AnyStateNode,\n stateValue: StateValueMap,\n state: State<TContext, TEvent>,\n _event: SCXML.Event<TEvent>\n): Array<TransitionDefinition<TContext, TEvent>> | undefined {\n const subStateKeys = Object.keys(stateValue);\n\n const childStateNode = getStateNode(stateNode, subStateKeys[0]);\n const next = transitionNode(\n childStateNode,\n stateValue[subStateKeys[0]],\n state,\n _event\n );\n\n if (!next || !next.length) {\n return stateNode.next(state, _event);\n }\n\n return next;\n}\n\nexport function transitionParallelNode<\n TContext extends MachineContext,\n TEvent extends EventObject\n>(\n stateNode: AnyStateNode,\n stateValue: StateValueMap,\n state: State<TContext, TEvent>,\n _event: SCXML.Event<TEvent>\n): Array<TransitionDefinition<TContext, TEvent>> | undefined {\n const allInnerTransitions: Array<TransitionDefinition<TContext, TEvent>> = [];\n\n for (const subStateKey of Object.keys(stateValue)) {\n const subStateValue = stateValue[subStateKey];\n\n if (!subStateValue) {\n continue;\n }\n\n const subStateNode = getStateNode(stateNode, subStateKey);\n const innerTransitions = transitionNode(\n subStateNode,\n subStateValue,\n state,\n _event\n );\n if (innerTransitions) {\n allInnerTransitions.push(...innerTransitions);\n }\n }\n if (!allInnerTransitions.length) {\n return stateNode.next(state, _event);\n }\n\n return allInnerTransitions;\n}\n\nexport function transitionNode<\n TContext extends MachineContext,\n TEvent extends EventObject\n>(\n stateNode: AnyStateNode,\n stateValue: StateValue,\n state: State<TContext, TEvent, any>,\n _event: SCXML.Event<TEvent>\n): Array<TransitionDefinition<TContext, TEvent>> | undefined {\n // leaf node\n if (isString(stateValue)) {\n return transitionAtomicNode(stateNode, stateValue, state, _event);\n }\n\n // compound node\n if (Object.keys(stateValue).length === 1) {\n return transitionCompoundNode(stateNode, stateValue, state, _event);\n }\n\n // parallel node\n return transitionParallelNode(stateNode, stateValue, state, _event);\n}\n\nfunction getHistoryNodes(stateNode: AnyStateNode): Array<AnyStateNode> {\n return Object.keys(stateNode.states)\n .map((key) => stateNode.states[key])\n .filter((sn) => sn.type === 'history');\n}\n\nfunction isDescendant(\n childStateNode: AnyStateNode,\n parentStateNode: AnyStateNode\n): boolean {\n let marker = childStateNode;\n while (marker.parent && marker.parent !== parentStateNode) {\n marker = marker.parent;\n }\n\n return marker.parent === parentStateNode;\n}\n\nfunction getPathFromRootToNode(stateNode: AnyStateNode): Array<AnyStateNode> {\n const path: Array<AnyStateNode> = [];\n let marker = stateNode.parent;\n\n while (marker) {\n path.unshift(marker);\n marker = marker.parent;\n }\n\n return path;\n}\n\nfunction hasIntersection<T>(s1: Iterable<T>, s2: Iterable<T>): boolean {\n const set1 = new Set(s1);\n const set2 = new Set(s2);\n\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}\n\nexport function removeConflictingTransitions(\n enabledTransitions: Array<AnyTransitionDefinition>,\n configuration: Set<AnyStateNode>,\n historyValue: AnyHistoryValue\n): Array<AnyTransitionDefinition> {\n const filteredTransitions = new Set<AnyTransitionDefinition>();\n\n for (const t1 of enabledTransitions) {\n let t1Preempted = false;\n const transitionsToRemove = new Set<AnyTransitionDefinition>();\n for (const t2 of filteredTransitions) {\n if (\n hasIntersection(\n computeExitSet([t1], configuration, historyValue),\n computeExitSet([t2], configuration, historyValue)\n )\n ) {\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\n return Array.from(filteredTransitions);\n}\n\nfunction findLCCA(stateNodes: Array<AnyStateNode>): AnyStateNode {\n const [head] = stateNodes;\n\n let current = getPathFromRootToNode(head);\n let candidates: Array<AnyStateNode> = [];\n\n for (const stateNode of stateNodes) {\n const path = getPathFromRootToNode(stateNode);\n\n candidates = current.filter((sn) => path.includes(sn));\n current = candidates;\n candidates = [];\n }\n\n return current[current.length - 1];\n}\n\nfunction getEffectiveTargetStates(\n transition: AnyTransitionDefinition,\n historyValue: AnyHistoryValue\n): Array<AnyStateNode> {\n if (!transition.target) {\n return [];\n }\n\n const targets = new Set<AnyStateNode>();\n\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(\n {\n target: resolveHistoryTarget(targetNode)\n } as AnyTransitionDefinition,\n historyValue\n )) {\n targets.add(node);\n }\n }\n } else {\n targets.add(targetNode);\n }\n }\n\n return [...targets];\n}\n\nfunction getTransitionDomain(\n transition: AnyTransitionDefinition,\n historyValue: AnyHistoryValue\n): AnyStateNode | null {\n const targetStates = getEffectiveTargetStates(transition, historyValue);\n\n if (!targetStates) {\n return null;\n }\n\n if (\n !transition.reenter &&\n transition.source.type !== 'parallel' &&\n targetStates.every((targetStateNode) =>\n isDescendant(targetStateNode, transition.source)\n )\n ) {\n return transition.source;\n }\n\n const lcca = findLCCA(targetStates.concat(transition.source));\n\n return lcca;\n}\n\nfunction computeExitSet(\n transitions: AnyTransitionDefinition[],\n configuration: Set<AnyStateNode>,\n historyValue: AnyHistoryValue\n): Array<AnyStateNode> {\n const statesToExit = new Set<AnyStateNode>();\n\n for (const t of transitions) {\n if (t.target?.length) {\n const domain = getTransitionDomain(t, historyValue);\n\n for (const stateNode of configuration) {\n if (isDescendant(stateNode, domain!)) {\n statesToExit.add(stateNode);\n }\n }\n }\n }\n\n return [...statesToExit];\n}\n\n/**\n * https://www.w3.org/TR/scxml/#microstepProcedure\n *\n * @private\n * @param transitions\n * @param currentState\n * @param mutConfiguration\n */\n\nexport function microstep<\n TContext extends MachineContext,\n TEvent extends EventObject\n>(\n transitions: Array<TransitionDefinition<TContext, TEvent>>,\n currentState: State<TContext, TEvent, any>,\n actorCtx: AnyActorContext | undefined,\n scxmlEvent: SCXML.Event<TEvent>\n): State<TContext, TEvent, any> {\n const { machine } = currentState;\n // Transition will \"apply\" if:\n // - the state node is the initial state (there is no current state)\n // - OR there are transitions\n const willTransition = currentState._initial || transitions.length > 0;\n\n const mutConfiguration = new Set(currentState.configuration);\n\n if (!currentState._initial && !willTransition) {\n const inertState = cloneState(currentState, {\n _event: scxmlEvent,\n actions: [],\n transitions: []\n });\n\n inertState.changed = false;\n return inertState;\n }\n\n const microstate = microstepProcedure(\n currentState._initial\n ? [\n {\n target: [...currentState.configuration].filter(isAtomicStateNode),\n source: machine.root,\n reenter: true,\n actions: [],\n eventType: null as any,\n toJSON: null as any // TODO: fix\n }\n ]\n : transitions,\n currentState,\n mutConfiguration,\n scxmlEvent,\n actorCtx\n );\n\n const { context, actions: nonRaisedActions } = microstate;\n\n const children = setChildren(currentState, nonRaisedActions);\n\n const nextState = cloneState(microstate, {\n value: {}, // TODO: make optional\n transitions,\n children\n });\n\n nextState.changed = currentState._initial\n ? undefined\n : !stateValuesEqual(nextState.value, currentState.value) ||\n nextState.actions.length > 0 ||\n context !== currentState.context;\n\n return nextState;\n}\n\nfunction setChildren(\n currentState: AnyState,\n nonRaisedActions: BaseActionObject[]\n) {\n const children = { ...currentState.children };\n for (const action of nonRaisedActions) {\n if (\n action.type === actionTypes.invoke &&\n (action as InvokeActionObject).params.ref\n ) {\n const ref = (action as InvokeActionObject).params.ref;\n if (ref) {\n children[ref.id] = ref;\n }\n } else if (action.type === actionTypes.stop) {\n const ref = (action as StopActionObject).params.actor;\n if (ref) {\n delete children[ref.id];\n }\n }\n }\n return children;\n}\n\nfunction microstepProcedure(\n transitions: Array<AnyTransitionDefinition>,\n currentState: AnyState,\n mutConfiguration: Set<AnyStateNode>,\n scxmlEvent: SCXML.Event<AnyEventObject>,\n actorCtx: AnyActorContext | undefined\n): typeof currentState {\n const { machine } = currentState;\n const actions: BaseActionObject[] = [];\n const historyValue = {\n ...currentState.historyValue\n };\n\n const filteredTransitions = removeConflictingTransitions(\n transitions,\n mutConfiguration,\n historyValue\n );\n\n const internalQueue = [...currentState._internalQueue];\n\n // Exit states\n if (!currentState._initial) {\n exitStates(filteredTransitions, mutConfiguration, historyValue, actions);\n }\n\n // Execute transition content\n actions.push(...filteredTransitions.flatMap((t) => t.actions));\n\n // Enter states\n enterStates(\n filteredTransitions,\n mutConfiguration,\n actions,\n internalQueue,\n currentState,\n historyValue\n );\n\n const nextConfiguration = [...mutConfiguration];\n\n const done = isInFinalState(nextConfiguration);\n\n if (done) {\n const finalActions = nextConfiguration\n .sort((a, b) => b.order - a.order)\n .flatMap((state) => state.exit);\n actions.push(...finalActions);\n }\n\n try {\n const { nextState } = resolveActionsAndContext(\n actions,\n scxmlEvent,\n currentState,\n actorCtx\n );\n\n const output = done\n ? getOutput(nextConfiguration, nextState.context, scxmlEvent)\n : undefined;\n\n internalQueue.push(...nextState._internalQueue);\n\n return cloneState(currentState, {\n actions: nextState.actions,\n configuration: nextConfiguration,\n historyValue,\n _internalQueue: internalQueue,\n context: nextState.context,\n _event: scxmlEvent,\n done,\n output,\n children: nextState.children\n });\n } catch (e) {\n // TODO: Refactor this once proper error handling is implemented.\n // See https://github.com/statelyai/rfcs/pull/4\n if (machine.config.scxml) {\n return cloneState(currentState, {\n actions: [],\n configuration: Array.from(mutConfiguration),\n historyValue,\n _internalQueue: [toSCXMLEvent({ type: 'error.execution' })],\n context: currentState.context\n });\n } else {\n throw e;\n }\n }\n}\n\nfunction enterStates(\n filteredTransitions: AnyTransitionDefinition[],\n mutConfiguration: Set<AnyStateNode>,\n actions: BaseActionObject[],\n internalQueue: SCXML.Event<AnyEventObject>[],\n currentState: AnyState,\n historyValue: HistoryValue<any, any>\n): void {\n const statesToEnter = new Set<AnyStateNode>();\n const statesForDefaultEntry = new Set<AnyStateNode>();\n\n computeEntrySet(\n filteredTransitions,\n historyValue,\n statesForDefaultEntry,\n statesToEnter\n );\n\n // In the initial state, the root state node is \"entered\".\n if (currentState._initial) {\n statesForDefaultEntry.add(currentState.machine.root);\n }\n\n for (const stateNodeToEnter of [...statesToEnter].sort(\n (a, b) => a.order - b.order\n )) {\n mutConfiguration.add(stateNodeToEnter);\n\n for (const invokeDef of stateNodeToEnter.invoke) {\n actions.push(invoke(invokeDef));\n }\n\n // Add entry actions\n actions.push(...stateNodeToEnter.entry);\n\n if (statesForDefaultEntry.has(stateNodeToEnter)) {\n for (const stateNode of statesForDefaultEntry) {\n const initialActions = stateNode.initial!.actions;\n actions.push(...initialActions);\n }\n }\n if (stateNodeToEnter.type === 'final') {\n const parent = stateNodeToEnter.parent!;\n\n if (!parent.parent) {\n continue;\n }\n\n internalQueue.push(\n toSCXMLEvent(\n done(\n parent!.id,\n stateNodeToEnter.output\n ? mapContext(\n stateNodeToEnter.output,\n currentState.context,\n currentState._event\n )\n : undefined\n )\n )\n );\n\n if (parent.parent) {\n const grandparent = parent.parent;\n\n if (grandparent.type === 'parallel') {\n if (\n getChildren(grandparent).every((parentNode) =>\n isInFinalState([...mutConfiguration], parentNode)\n )\n ) {\n internalQueue.push(toSCXMLEvent(done(grandparent.id)));\n }\n }\n }\n }\n }\n}\n\nfunction computeEntrySet(\n transitions: Array<AnyTransitionDefinition>,\n historyValue: HistoryValue<any, any>,\n statesForDefaultEntry: Set<AnyStateNode>,\n statesToEnter: Set<AnyStateNode>\n) {\n for (const t of transitions) {\n for (const s of t.target || []) {\n addDescendantStatesToEnter(\n s,\n historyValue,\n statesForDefaultEntry,\n statesToEnter\n );\n }\n const ancestor = getTransitionDomain(t, historyValue);\n const targetStates = getEffectiveTargetStates(t, historyValue);\n for (const s of targetStates) {\n addAncestorStatesToEnter(\n s,\n ancestor,\n statesToEnter,\n historyValue,\n statesForDefaultEntry\n );\n }\n }\n}\n\nfunction addDescendantStatesToEnter<\n TContext extends MachineContext,\n TEvent extends EventObject\n>(\n stateNode: AnyStateNode,\n historyValue: HistoryValue<any, any>,\n statesForDefaultEntry: Set<AnyStateNode>,\n statesToEnter: Set<AnyStateNode>\n) {\n if (isHistoryNode(stateNode)) {\n if (historyValue[stateNode.id]) {\n const historyStateNodes = historyValue[stateNode.id];\n for (const s of historyStateNodes) {\n addDescendantStatesToEnter(\n s,\n historyValue,\n statesForDefaultEntry,\n statesToEnter\n );\n }\n for (const s of historyStateNodes) {\n addAncestorStatesToEnter(\n s,\n stateNode.parent!,\n statesToEnter,\n historyValue,\n statesForDefaultEntry\n );\n for (const stateForDefaultEntry of statesForDefaultEntry) {\n statesForDefaultEntry.add(stateForDefaultEntry);\n }\n }\n } else {\n const targets = resolveHistoryTarget<TContext, TEvent>(stateNode);\n for (const s of targets) {\n addDescendantStatesToEnter(\n s,\n historyValue,\n statesForDefaultEntry,\n statesToEnter\n );\n }\n for (const s of targets) {\n addAncestorStatesToEnter(\n s,\n stateNode,\n statesToEnter,\n historyValue,\n statesForDefaultEntry\n );\n for (const stateForDefaultEntry of statesForDefaultEntry) {\n statesForDefaultEntry.add(stateForDefaultEntry);\n }\n }\n }\n } else {\n statesToEnter.add(stateNode);\n if (stateNode.type === 'compound') {\n statesForDefaultEntry.add(stateNode);\n const initialStates = stateNode.initial.target;\n\n for (const initialState of initialStates) {\n addDescendantStatesToEnter(\n initialState,\n historyValue,\n statesForDefaultEntry,\n statesToEnter\n );\n }\n\n for (const initialState of initialStates) {\n addAncestorStatesToEnter(\n initialState,\n stateNode,\n statesToEnter,\n historyValue,\n statesForDefaultEntry\n );\n }\n } else {\n if (stateNode.type === 'parallel') {\n for (const child of getChildren(stateNode).filter(\n (sn) => !isHistoryNode(sn)\n )) {\n if (![...statesToEnter].some((s) => isDescendant(s, child))) {\n addDescendantStatesToEnter(\n child,\n historyValue,\n statesForDefaultEntry,\n statesToEnter\n );\n }\n }\n }\n }\n }\n}\n\nfunction addAncestorStatesToEnter(\n stateNode: AnyStateNode,\n toStateNode: AnyStateNode | null,\n statesToEnter: Set<AnyStateNode>,\n historyValue: HistoryValue<any, any>,\n statesForDefaultEntry: Set<AnyStateNode>\n) {\n const properAncestors = getProperAncestors(stateNode, toStateNode);\n for (const anc of properAncestors) {\n statesToEnter.add(anc);\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 addDescendantStatesToEnter(\n child,\n historyValue,\n statesForDefaultEntry,\n statesToEnter\n );\n }\n }\n }\n }\n}\n\nfunction exitStates(\n transitions: AnyTransitionDefinition[],\n mutConfiguration: Set<AnyStateNode>,\n historyValue: HistoryValue<any, any>,\n actions: BaseActionObject[]\n) {\n const statesToExit = computeExitSet(\n transitions,\n mutConfiguration,\n historyValue\n );\n\n statesToExit.sort((a, b) => b.order - a.order);\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: (sn: AnyStateNode) => boolean;\n if (historyNode.history === 'deep') {\n predicate = (sn) =>\n isAtomicStateNode(sn) && isDescendant(sn, exitStateNode);\n } else {\n predicate = (sn) => {\n return sn.parent === exitStateNode;\n };\n }\n historyValue[historyNode.id] =\n Array.from(mutConfiguration).filter(predicate);\n }\n }\n\n for (const s of statesToExit) {\n actions.push(...s.exit.flat(), ...s.invoke.map((def) => stop(def.id)));\n mutConfiguration.delete(s);\n }\n}\n\nexport function resolveActionsAndContext<\n TContext extends MachineContext,\n TEvent extends EventObject\n>(\n actions: BaseActionObject[],\n scxmlEvent: SCXML.Event<TEvent>,\n currentState: State<TContext, TEvent, any>,\n actorCtx: AnyActorContext | undefined\n): {\n nextState: AnyState;\n} {\n const { machine } = currentState;\n const resolvedActions: BaseActionObject[] = [];\n const raiseActions: Array<RaiseActionObject<TContext, TEvent>> = [];\n let intermediateState = currentState;\n\n function handleAction(action: BaseActionObject): void {\n resolvedActions.push(action);\n if (actorCtx?.self.status === ActorStatus.Running) {\n action.execute?.(actorCtx!);\n // TODO: this is hacky; re-evaluate\n delete action.execute;\n }\n }\n\n function resolveAction(actionObject: BaseActionObject) {\n const executableActionObject = resolveActionObject(\n actionObject,\n machine.options.actions\n );\n\n if (isDynamicAction(executableActionObject)) {\n const [nextState, resolvedAction] = executableActionObject.resolve(\n scxmlEvent,\n {\n state: intermediateState,\n action: actionObject,\n actorContext: actorCtx\n }\n );\n const matchedActions = resolvedAction.params?.actions;\n\n intermediateState = nextState;\n\n if (\n (resolvedAction.type === actionTypes.raise ||\n (resolvedAction.type === actionTypes.send &&\n (resolvedAction as SendActionObject).params.internal)) &&\n typeof (resolvedAction as any).params.delay !== 'number'\n ) {\n raiseActions.push(resolvedAction);\n }\n\n // TODO: remove the check; just handleAction\n if (resolvedAction.type !== actionTypes.pure) {\n handleAction(resolvedAction);\n }\n\n toActionObjects(matchedActions).forEach(resolveAction);\n\n return;\n }\n\n handleAction(executableActionObject);\n }\n\n for (const actionObject of actions) {\n resolveAction(actionObject);\n }\n\n return {\n nextState: cloneState(intermediateState, {\n actions: resolvedActions,\n _internalQueue: raiseActions.map((a) => a.params._event)\n })\n };\n}\n\nexport function macrostep<TMachine extends AnyStateMachine>(\n state: StateFromMachine<TMachine>,\n scxmlEvent: SCXML.Event<TMachine['__TEvent']>,\n actorCtx: AnyActorContext | undefined\n): {\n state: typeof state;\n microstates: Array<typeof state>;\n} {\n if (!IS_PRODUCTION && scxmlEvent.name === WILDCARD) {\n throw new Error(`An event cannot have the wildcard type ('${WILDCARD}')`);\n }\n\n let nextState = state;\n const states: StateFromMachine<TMachine>[] = [];\n\n // Handle stop event\n if (scxmlEvent?.name === stopSignalType) {\n nextState = stopStep(scxmlEvent, nextState, actorCtx);\n states.push(nextState);\n\n return {\n state: nextState,\n microstates: states\n };\n }\n\n // Assume the state is at rest (no raised events)\n // Determine the next state based on the next microstep\n if (scxmlEvent.name !== actionTypes.init) {\n const transitions = selectTransitions(scxmlEvent, nextState);\n nextState = microstep(transitions, state, actorCtx, scxmlEvent);\n states.push(nextState);\n }\n\n while (!nextState.done) {\n let enabledTransitions = selectEventlessTransitions(nextState);\n\n if (enabledTransitions.length === 0) {\n // TODO: this is a bit of a hack, we need to review this\n // this matches the behavior from v4 for eventless transitions\n // where for `hasAlwaysTransitions` we were always trying to resolve with a NULL event\n // and if a transition was not selected the `state.transitions` stayed empty\n // without this we get into an infinite loop in the dieHard test in `@xstate/test` for the `simplePathsTo`\n if (nextState.configuration.some((state) => state.always)) {\n nextState.transitions = [];\n }\n\n if (!nextState._internalQueue.length) {\n break;\n } else {\n const currentActions = nextState.actions;\n const nextEvent = nextState._internalQueue[0];\n const transitions = selectTransitions(nextEvent, nextState);\n nextState = microstep(transitions, nextState, actorCtx, nextEvent);\n nextState._internalQueue.shift();\n nextState.actions.unshift(...currentActions);\n\n states.push(nextState);\n }\n }\n\n if (enabledTransitions.length) {\n const currentActions = nextState.actions;\n nextState = microstep(\n enabledTransitions,\n nextState,\n actorCtx,\n nextState._event\n );\n nextState.actions.unshift(...currentActions);\n\n states.push(nextState);\n }\n }\n\n if (nextState.done) {\n // Perform the stop step to ensure that child actors are stopped\n stopStep(nextState._event, nextState, actorCtx);\n }\n\n return {\n state: nextState,\n microstates: states\n };\n}\n\nfunction stopStep(\n scxmlEvent: SCXML.Event<any>,\n nextState: AnyState,\n actorCtx: AnyActorContext | undefined\n): AnyState {\n const actions: BaseActionObject[] = [];\n\n for (const stateNode of nextState.configuration.sort(\n (a, b) => b.order - a.order\n )) {\n actions.push(...stateNode.exit);\n }\n\n for (const child of Object.values(nextState.children)) {\n actions.push(stop(child));\n }\n\n const { nextState: stoppedState } = resolveActionsAndContext(\n actions,\n scxmlEvent,\n nextState,\n actorCtx\n );\n\n return stoppedState;\n}\n\nfunction selectTransitions(\n scxmlEvent: SCXML.Event<any>,\n nextState: AnyState\n): AnyTransitionDefinition[] {\n return nextState.machine.getTransitionData(nextState, scxmlEvent);\n}\n\nfunction selectEventlessTransitions(\n nextState: AnyState\n): AnyTransitionDefinition[] {\n const enabledTransitionSet: Set<AnyTransitionDefinition> = new Set();\n const atomicStates = nextState.configuration.filter(isAtomicStateNode);\n\n for (const stateNode of atomicStates) {\n loop: for (const s of [stateNode].concat(\n getProperAncestors(stateNode, null)\n )) {\n if (!s.always) {\n continue;\n }\n for (const transition of s.always) {\n if (\n transition.guard === undefined ||\n evaluateGuard(\n transition.guard,\n nextState.context,\n nextState._event,\n nextState\n )\n ) {\n enabledTransitionSet.add(transition);\n break loop;\n }\n }\n }\n }\n\n return removeConflictingTransitions(\n Array.from(enabledTransitionSet),\n new Set(nextState.configuration),\n nextState.historyValue\n );\n}\n\n/**\n * Resolves a partial state value with its full representation in the state node's machine.\n *\n * @param stateValue The partial state value to resolve.\n */\nexport function resolveStateValue(\n rootNode: AnyStateNode,\n stateValue: StateValue\n): StateValue {\n const configuration = getConfiguration(getStateNodes(rootNode, stateValue));\n return getStateValue(rootNode, [...configuration]);\n}\n\nexport function stateValuesEqual(\n a: StateValue | undefined,\n b: StateValue | undefined\n): boolean {\n if (a === b) {\n return true;\n }\n\n if (a === undefined || b === undefined) {\n return false;\n }\n\n if (isString(a) || isString(b)) {\n return a === b;\n }\n\n const aKeys = Object.keys(a as StateValueMap);\n const bKeys = Object.keys(b as StateValueMap);\n\n return (\n aKeys.length === bKeys.length &&\n aKeys.every((key) => stateValuesEqual(a[key], b[key]))\n );\n}\n\nexport function getInitialConfiguration(\n rootNode: AnyStateNode\n): AnyStateNode[] {\n const configuration: AnyStateNode[] = [];\n const initialTransition = rootNode.initial;\n\n const statesToEnter = new Set<AnyStateNode>();\n const statesForDefaultEntry = new Set<AnyStateNode>([rootNode]);\n\n computeEntrySet(\n [initialTransition],\n {},\n statesForDefaultEntry,\n statesToEnter\n );\n\n for (const stateNodeToEnter of [...statesToEnter].sort(\n (a, b) => a.order - b.order\n )) {\n configuration.push(stateNodeToEnter);\n }\n\n return configuration;\n}\n"],"names":["isString","value","toGuardDefinition","guardConfig","getPredicate","type","predicate","undefined","params","name","children","_guardConfig$children","map","childGuard","guards","op","guard","evaluate","context","_event","state","every","evaluateGuard","machine","options","_machine$options","_machine$options$guar2","Error","event","data","some","stateValue","configuration","sn","id","slice","matches"],"mappings":"oPAiVO,SAASA,EAASC,GACvB,MAAwB,iBAAVA,ECvOT,SAASC,EAIdC,EACAC,GACmC,MACnC,OAAIJ,EAASG,GACJ,CACLE,KAAMF,EACNG,WAAWF,MAAAA,SAAAA,EAAeD,UAAgBI,EAC1CC,OAAQ,CAAEH,KAAMF,IDwNI,mBCpNTA,EACN,CACLE,KAAMF,EAAYM,KAClBH,UAAWH,EACXK,OAAQ,CACNH,KAAMF,EAAYM,KAClBA,KAAMN,EAAYM,OAKjB,CACLJ,KAAMF,EAAYE,KAClBG,OAAQL,EAAYK,QAAUL,EAC9BO,mBACEP,EAAYO,6BADJC,EAEPC,KAAI,SAACC,GAAU,OAAKX,EAAkBW,EAAYT,MACrDE,WACEF,MAAAA,SAAAA,EAAeD,EAAYE,QAAUF,EAAoBG,iBA7FxD,SAILQ,GAEA,MAAO,CACLT,KAAM,iBACNG,OAAQ,CAAEO,GAAI,OACdL,SAAUI,EAAOF,KAAI,SAACI,GAAK,OAAKd,EAAkBc,MAClDV,UAAW,YAAiD,IAA9CW,IAAAA,SAAUD,IAAAA,MAAOE,IAAAA,QAASC,IAAAA,OAAQC,IAAAA,MAC9C,OAAOJ,EAAMN,SAAUW,OAAM,SAACR,GAC5B,OAAOI,EAASJ,EAAYK,EAASC,EAAQC,yBAqB9C,SAASE,EAIdN,EACAE,EACAC,EACAC,GACS,UACDG,EAAYH,EAAZG,QAEFjB,YAAYiB,MAAAA,aAAAA,EAASC,gCAATC,EAAkBX,2BAAlBY,EAA2BV,EAAMX,qBAASW,EAAMV,UAElE,IAAKA,EACH,MAAM,IAAIqB,uBAAgBX,EAAMX,iCAGlC,OAAOC,EAAU,CACfY,QAAAA,EACAU,MAAOT,EAAOU,KACdT,MAAAA,EACAJ,MAAAA,EACAG,OAAAA,EACAF,SAAUK,WAxEP,SAILN,GAEA,MAAO,CACLX,KAAM,iBACNG,OAAQ,CAAEO,GAAI,OACdL,SAAU,CAACR,EAAkBc,IAC7BV,UAAW,YAAiD,IAA9CW,IAAAA,SAAUD,IAAAA,MAAOE,IAAAA,QAASC,IAAAA,OAAQC,IAAAA,MAC9C,OAAQH,EAASD,EAAMN,SAAU,GAAIQ,EAASC,EAAQC,WAuBrD,SACLN,GAEA,MAAO,CACLT,KAAM,iBACNG,OAAQ,CAAEO,GAAI,MACdL,SAAUI,EAAOF,KAAI,SAACI,GAAK,OAAKd,EAAkBc,MAClDV,UAAW,YAAiD,IAA9CW,IAAAA,SAAUD,IAAAA,MAAOE,IAAAA,QAASC,IAAAA,OAAQC,IAAAA,MAC9C,OAAOJ,EAAMN,SAAUoB,MAAK,SAACjB,GAC3B,OAAOI,EAASJ,EAAYK,EAASC,EAAQC,mBA5D9C,SAGLW,GACA,MAAO,CACL1B,KAAM,kBACNG,OAAQ,CAAEuB,WAAAA,GACVzB,UAAW,YAAe,IAAZc,IAAAA,MACZ,OAAIpB,EAAS+B,ICnBa,MDmBYA,EEgNE,GF/M/BX,EAAMY,cAAcF,MAAK,SAACG,GAAE,OAAKA,EAAGC,KAAOH,EAAWI,MAAM,MAG9Df,EAAMgB,QAAQL"}
1
+ {"version":3,"file":"xstate-guards.umd.min.js","sources":["../../src/constants.ts","../../src/stateUtils.ts","../../src/guards.ts"],"sourcesContent":["export const STATE_DELIMITER = '.';\nexport const TARGETLESS_KEY = '';\nexport const NULL_EVENT = '';\nexport const STATE_IDENTIFIER = '#';\nexport const WILDCARD = '*';\nexport const XSTATE_INIT = 'xstate.init';\nexport const XSTATE_ERROR = 'xstate.error';\nexport const XSTATE_STOP = 'xstate.stop';\n","import isDevelopment from '#is-development';\nimport { MachineSnapshot, cloneMachineSnapshot } from './State.ts';\nimport type { StateNode } from './StateNode.ts';\nimport { raise } from './actions.ts';\nimport { createAfterEvent, createDoneStateEvent } from './eventUtils.ts';\nimport { cancel } from './actions/cancel.ts';\nimport { spawnChild } from './actions/spawnChild.ts';\nimport { stopChild } from './actions/stopChild.ts';\nimport {\n XSTATE_INIT,\n NULL_EVENT,\n STATE_DELIMITER,\n STATE_IDENTIFIER,\n XSTATE_STOP,\n WILDCARD\n} from './constants.ts';\nimport { evaluateGuard } from './guards.ts';\nimport {\n ActionArgs,\n AnyEventObject,\n AnyHistoryValue,\n AnyMachineSnapshot,\n AnyStateNode,\n AnyTransitionDefinition,\n DelayExpr,\n DelayedTransitionDefinition,\n EventObject,\n HistoryValue,\n InitialTransitionConfig,\n InitialTransitionDefinition,\n MachineContext,\n StateValue,\n StateValueMap,\n TransitionDefinition,\n TODO,\n UnknownAction,\n ParameterizedObject,\n ActionFunction,\n AnyTransitionConfig,\n ProvidedActor,\n AnyActorScope\n} from './types.ts';\nimport {\n resolveOutput,\n normalizeTarget,\n toArray,\n toStatePath,\n toTransitionConfigArray,\n isErrorActorEvent\n} from './utils.ts';\nimport { ProcessingStatus } from './interpreter.ts';\n\ntype StateNodeIterable<\n TContext extends MachineContext,\n TE extends EventObject\n> = Iterable<StateNode<TContext, TE>>;\ntype AnyStateNodeIterable = StateNodeIterable<any, any>;\n\ntype AdjList = Map<AnyStateNode, Array<AnyStateNode>>;\n\nexport const isAtomicStateNode = (stateNode: StateNode<any, any>) =>\n stateNode.type === 'atomic' || stateNode.type === 'final';\n\nfunction getChildren<TContext extends MachineContext, TE extends EventObject>(\n stateNode: StateNode<TContext, TE>\n): Array<StateNode<TContext, TE>> {\n return Object.values(stateNode.states).filter((sn) => sn.type !== 'history');\n}\n\nfunction getProperAncestors(\n stateNode: AnyStateNode,\n toStateNode: AnyStateNode | undefined\n): Array<typeof stateNode> {\n const ancestors: Array<typeof stateNode> = [];\n\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\n return ancestors;\n}\n\nexport function getAllStateNodes(\n stateNodes: Iterable<AnyStateNode>\n): Set<AnyStateNode> {\n const nodeSet = new Set(stateNodes);\n\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) =>\n nodeSet.add(sn)\n );\n } else {\n if (s.type === 'parallel') {\n for (const child of getChildren(s)) {\n if (child.type === 'history') {\n continue;\n }\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\n while (m) {\n nodeSet.add(m);\n m = m.parent;\n }\n }\n\n return nodeSet;\n}\n\nfunction getValueFromAdj(baseNode: AnyStateNode, adjList: AdjList): StateValue {\n const childStateNodes = adjList.get(baseNode);\n\n if (!childStateNodes) {\n return {}; // todo: fix?\n }\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\n const stateValue: StateValue = {};\n for (const childStateNode of childStateNodes) {\n stateValue[childStateNode.key] = getValueFromAdj(childStateNode, adjList);\n }\n\n return stateValue;\n}\n\nexport function getAdjList<\n TContext extends MachineContext,\n TE extends EventObject\n>(stateNodes: StateNodeIterable<TContext, TE>): AdjList {\n const adjList: AdjList = new Map();\n\n for (const s of stateNodes) {\n if (!adjList.has(s)) {\n adjList.set(s, []);\n }\n\n if (s.parent) {\n if (!adjList.has(s.parent)) {\n adjList.set(s.parent, []);\n }\n\n adjList.get(s.parent)!.push(s);\n }\n }\n\n return adjList;\n}\n\nexport function getStateValue(\n rootNode: AnyStateNode,\n stateNodes: AnyStateNodeIterable\n): StateValue {\n const config = getAllStateNodes(stateNodes);\n return getValueFromAdj(rootNode, getAdjList(config));\n}\n\nexport function isInFinalState(\n stateNodeSet: Set<AnyStateNode>,\n stateNode: AnyStateNode\n): boolean {\n if (stateNode.type === 'compound') {\n return getChildren(stateNode).some(\n (s) => s.type === 'final' && stateNodeSet.has(s)\n );\n }\n if (stateNode.type === 'parallel') {\n return getChildren(stateNode).every((sn) =>\n isInFinalState(stateNodeSet, sn)\n );\n }\n\n return stateNode.type === 'final';\n}\n\nexport const isStateId = (str: string) => str[0] === STATE_IDENTIFIER;\n\nexport function getCandidates<TEvent extends EventObject>(\n stateNode: StateNode<any, TEvent>,\n receivedEventType: TEvent['type']\n): Array<TransitionDefinition<any, TEvent>> {\n const candidates =\n stateNode.transitions.get(receivedEventType) ||\n [...stateNode.transitions.keys()]\n .filter((descriptor) => {\n // check if transition is a wildcard transition,\n // which matches any non-transient events\n if (descriptor === WILDCARD) {\n return true;\n }\n\n if (!descriptor.endsWith('.*')) {\n return false;\n }\n\n if (isDevelopment && /.*\\*.+/.test(descriptor)) {\n console.warn(\n `Wildcards can only be the last token of an event descriptor (e.g., \"event.*\") or the entire event descriptor (\"*\"). Check the \"${descriptor}\" event.`\n );\n }\n\n const partialEventTokens = descriptor.split('.');\n const eventTokens = receivedEventType.split('.');\n\n for (\n let tokenIndex = 0;\n tokenIndex < partialEventTokens.length;\n tokenIndex++\n ) {\n const partialEventToken = partialEventTokens[tokenIndex];\n const eventToken = eventTokens[tokenIndex];\n\n if (partialEventToken === '*') {\n const isLastToken = tokenIndex === partialEventTokens.length - 1;\n\n if (isDevelopment && !isLastToken) {\n console.warn(\n `Infix wildcards in transition events are not allowed. Check the \"${descriptor}\" transition.`\n );\n }\n\n return isLastToken;\n }\n\n if (partialEventToken !== eventToken) {\n return false;\n }\n }\n\n return true;\n })\n .sort((a, b) => b.length - a.length)\n .flatMap((key) => stateNode.transitions.get(key)!);\n\n return candidates;\n}\n\n/**\n * All delayed transitions from the config.\n */\nexport function getDelayedTransitions(\n stateNode: AnyStateNode\n): Array<DelayedTransitionDefinition<MachineContext, EventObject>> {\n const afterConfig = stateNode.config.after;\n if (!afterConfig) {\n return [];\n }\n\n const mutateEntryExit = (delay: string | number, i: number) => {\n const afterEvent = createAfterEvent(delay, stateNode.id);\n const eventType = afterEvent.type;\n stateNode.entry.push(raise(afterEvent, { id: eventType, delay }));\n stateNode.exit.push(cancel(eventType));\n return eventType;\n };\n\n const delayedTransitions = Object.keys(afterConfig).flatMap((delay, i) => {\n const configTransition = afterConfig[delay];\n const resolvedTransition =\n typeof configTransition === 'string'\n ? { target: configTransition }\n : configTransition;\n const resolvedDelay = Number.isNaN(+delay) ? delay : +delay;\n const eventType = mutateEntryExit(resolvedDelay, i);\n return toArray(resolvedTransition).map((transition) => ({\n ...transition,\n event: eventType,\n delay: resolvedDelay\n }));\n });\n return delayedTransitions.map((delayedTransition) => {\n const { delay } = delayedTransition;\n return {\n ...formatTransition(\n stateNode,\n delayedTransition.event,\n delayedTransition\n ),\n delay\n };\n });\n}\n\nexport function formatTransition<\n TContext extends MachineContext,\n TEvent extends EventObject\n>(\n stateNode: AnyStateNode,\n descriptor: string,\n transitionConfig: AnyTransitionConfig\n): AnyTransitionDefinition {\n const normalizedTarget = normalizeTarget(transitionConfig.target);\n const reenter = transitionConfig.reenter ?? false;\n const target = resolveTarget(stateNode, normalizedTarget);\n\n // TODO: should this be part of a lint rule instead?\n if (isDevelopment && (transitionConfig as any).cond) {\n throw new Error(\n `State \"${stateNode.id}\" has declared \\`cond\\` for one of its transitions. This property has been renamed to \\`guard\\`. Please update your code.`\n );\n }\n const transition = {\n ...transitionConfig,\n actions: toArray(transitionConfig.actions),\n guard: transitionConfig.guard as never,\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\n return transition;\n}\n\nexport function formatTransitions<\n TContext extends MachineContext,\n TEvent extends EventObject\n>(\n stateNode: AnyStateNode\n): Map<string, TransitionDefinition<TContext, TEvent>[]> {\n const transitions = new Map<\n string,\n TransitionDefinition<TContext, AnyEventObject>[]\n >();\n if (stateNode.config.on) {\n for (const descriptor of Object.keys(stateNode.config.on)) {\n if (descriptor === NULL_EVENT) {\n throw new Error(\n 'Null events (\"\") cannot be specified as a transition key. Use `always: { ... }` instead.'\n );\n }\n const transitionsConfig = stateNode.config.on[descriptor];\n transitions.set(\n descriptor,\n toTransitionConfigArray(transitionsConfig).map((t) =>\n formatTransition(stateNode, descriptor, t)\n )\n );\n }\n }\n if (stateNode.config.onDone) {\n const descriptor = `xstate.done.state.${stateNode.id}`;\n transitions.set(\n descriptor,\n toTransitionConfigArray(stateNode.config.onDone).map((t) =>\n formatTransition(stateNode, descriptor, t)\n )\n );\n }\n for (const invokeDef of stateNode.invoke) {\n if (invokeDef.onDone) {\n const descriptor = `xstate.done.actor.${invokeDef.id}`;\n transitions.set(\n descriptor,\n toTransitionConfigArray(invokeDef.onDone).map((t) =>\n formatTransition(stateNode, descriptor, t)\n )\n );\n }\n if (invokeDef.onError) {\n const descriptor = `xstate.error.actor.${invokeDef.id}`;\n transitions.set(\n descriptor,\n toTransitionConfigArray(invokeDef.onError).map((t) =>\n formatTransition(stateNode, descriptor, t)\n )\n );\n }\n if (invokeDef.onSnapshot) {\n const descriptor = `xstate.snapshot.${invokeDef.id}`;\n transitions.set(\n descriptor,\n toTransitionConfigArray(invokeDef.onSnapshot).map((t) =>\n formatTransition(stateNode, descriptor, t)\n )\n );\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 as Map<string, TransitionDefinition<TContext, any>[]>;\n}\n\nexport function formatInitialTransition<\n TContext extends MachineContext,\n TEvent extends EventObject\n>(\n stateNode: AnyStateNode,\n _target:\n | string\n | undefined\n | InitialTransitionConfig<TContext, TEvent, TODO, TODO, TODO, TODO>\n): InitialTransitionDefinition<TContext, TEvent> {\n const resolvedTarget =\n typeof _target === 'string'\n ? stateNode.states[_target]\n : _target\n ? stateNode.states[_target.target]\n : undefined;\n if (!resolvedTarget && _target) {\n throw new Error(\n `Initial state node \"${_target}\" not found on parent state node #${stateNode.id}`\n );\n }\n const transition: InitialTransitionDefinition<TContext, TEvent> = {\n source: stateNode,\n actions:\n !_target || typeof _target === 'string' ? [] : toArray(_target.actions),\n eventType: null as any,\n reenter: false,\n target: resolvedTarget ? [resolvedTarget] : [],\n toJSON: () => ({\n ...transition,\n source: `#${stateNode.id}`,\n target: resolvedTarget ? [`#${resolvedTarget.id}`] : []\n })\n };\n\n return transition;\n}\n\nexport function resolveTarget(\n stateNode: AnyStateNode,\n targets: ReadonlyArray<string | AnyStateNode> | undefined\n): ReadonlyArray<AnyStateNode> | undefined {\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\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(\n stateNode.parent,\n resolvedTarget\n );\n return targetStateNode;\n } catch (err: any) {\n throw new Error(\n `Invalid transition definition for state node '${stateNode.id}':\\n${err.message}`\n );\n }\n } else {\n throw new Error(\n `Invalid target: \"${target}\" is not a valid target from the root node. Did you mean \".${target}\"?`\n );\n }\n });\n}\n\nfunction resolveHistoryDefaultTransition<\n TContext extends MachineContext,\n TEvent extends EventObject\n>(stateNode: AnyStateNode & { type: 'history' }) {\n const normalizedTarget = normalizeTarget<TContext, TEvent>(\n stateNode.config.target\n );\n if (!normalizedTarget) {\n return stateNode.parent!.initial;\n }\n return {\n target: normalizedTarget.map((t) =>\n typeof t === 'string' ? getStateNodeByPath(stateNode.parent!, t) : t\n )\n };\n}\n\nfunction isHistoryNode(\n stateNode: AnyStateNode\n): stateNode is AnyStateNode & { type: 'history' } {\n return stateNode.type === 'history';\n}\n\nexport function getInitialStateNodesWithTheirAncestors(\n stateNode: AnyStateNode\n) {\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}\n\nexport function getInitialStateNodes(stateNode: AnyStateNode) {\n const set = new Set<AnyStateNode>();\n\n function iter(descStateNode: AnyStateNode): void {\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\n iter(stateNode);\n\n return set;\n}\n/**\n * Returns the child state node from its relative `stateKey`, or throws.\n */\nexport function getStateNode(\n stateNode: AnyStateNode,\n stateKey: string\n): AnyStateNode {\n if (isStateId(stateKey)) {\n return stateNode.machine.getStateNodeById(stateKey);\n }\n if (!stateNode.states) {\n throw new Error(\n `Unable to retrieve child state '${stateKey}' from '${stateNode.id}'; no child states exist.`\n );\n }\n const result = stateNode.states[stateKey];\n if (!result) {\n throw new Error(\n `Child state '${stateKey}' does not exist on '${stateNode.id}'`\n );\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 */\nexport function getStateNodeByPath(\n stateNode: AnyStateNode,\n statePath: string | string[]\n): AnyStateNode {\n if (typeof statePath === 'string' && isStateId(statePath)) {\n try {\n return stateNode.machine.getStateNodeById(statePath);\n } catch (e) {\n // try individual paths\n // throw e;\n }\n }\n const arrayStatePath = toStatePath(statePath).slice();\n let currentStateNode: AnyStateNode = 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 */\nexport function getStateNodes<\n TContext extends MachineContext,\n TEvent extends EventObject\n>(stateNode: AnyStateNode, stateValue: StateValue): Array<AnyStateNode> {\n if (typeof stateValue === 'string') {\n return [stateNode, stateNode.states[stateValue]];\n }\n\n const childStateKeys = Object.keys(stateValue);\n const childStateNodes: Array<AnyStateNode> = childStateKeys\n .map((subStateKey) => getStateNode(stateNode, subStateKey))\n .filter(Boolean);\n\n return [stateNode.machine.root, stateNode].concat(\n childStateNodes,\n childStateKeys.reduce((allSubStateNodes, subStateKey) => {\n const subStateNode = getStateNode(stateNode, subStateKey);\n if (!subStateNode) {\n return allSubStateNodes;\n }\n const subStateNodes = getStateNodes(\n subStateNode,\n stateValue[subStateKey]\n );\n\n return allSubStateNodes.concat(subStateNodes);\n }, [] as Array<AnyStateNode>)\n );\n}\n\nexport function transitionAtomicNode<\n TContext extends MachineContext,\n TEvent extends EventObject\n>(\n stateNode: AnyStateNode,\n stateValue: string,\n snapshot: MachineSnapshot<TContext, TEvent, any, any, any, any>,\n event: TEvent\n): Array<TransitionDefinition<TContext, TEvent>> | undefined {\n const childStateNode = getStateNode(stateNode, stateValue);\n const next = childStateNode.next(snapshot, event);\n\n if (!next || !next.length) {\n return stateNode.next(snapshot, event);\n }\n\n return next;\n}\n\nexport function transitionCompoundNode<\n TContext extends MachineContext,\n TEvent extends EventObject\n>(\n stateNode: AnyStateNode,\n stateValue: StateValueMap,\n snapshot: MachineSnapshot<TContext, TEvent, any, any, any, any>,\n event: TEvent\n): Array<TransitionDefinition<TContext, TEvent>> | undefined {\n const subStateKeys = Object.keys(stateValue);\n\n const childStateNode = getStateNode(stateNode, subStateKeys[0]);\n const next = transitionNode(\n childStateNode,\n stateValue[subStateKeys[0]],\n snapshot,\n event\n );\n\n if (!next || !next.length) {\n return stateNode.next(snapshot, event);\n }\n\n return next;\n}\n\nexport function transitionParallelNode<\n TContext extends MachineContext,\n TEvent extends EventObject\n>(\n stateNode: AnyStateNode,\n stateValue: StateValueMap,\n snapshot: MachineSnapshot<TContext, TEvent, any, any, any, any>,\n event: TEvent\n): Array<TransitionDefinition<TContext, TEvent>> | undefined {\n const allInnerTransitions: Array<TransitionDefinition<TContext, TEvent>> = [];\n\n for (const subStateKey of Object.keys(stateValue)) {\n const subStateValue = stateValue[subStateKey];\n\n if (!subStateValue) {\n continue;\n }\n\n const subStateNode = getStateNode(stateNode, subStateKey);\n const innerTransitions = transitionNode(\n subStateNode,\n subStateValue,\n snapshot,\n event\n );\n if (innerTransitions) {\n allInnerTransitions.push(...innerTransitions);\n }\n }\n if (!allInnerTransitions.length) {\n return stateNode.next(snapshot, event);\n }\n\n return allInnerTransitions;\n}\n\nexport function transitionNode<\n TContext extends MachineContext,\n TEvent extends EventObject\n>(\n stateNode: AnyStateNode,\n stateValue: StateValue,\n snapshot: MachineSnapshot<TContext, TEvent, any, any, any, any, any>,\n event: TEvent\n): Array<TransitionDefinition<TContext, TEvent>> | undefined {\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}\n\nfunction getHistoryNodes(stateNode: AnyStateNode): Array<AnyStateNode> {\n return Object.keys(stateNode.states)\n .map((key) => stateNode.states[key])\n .filter((sn) => sn.type === 'history');\n}\n\nfunction isDescendant(\n childStateNode: AnyStateNode,\n parentStateNode: AnyStateNode\n): boolean {\n let marker = childStateNode;\n while (marker.parent && marker.parent !== parentStateNode) {\n marker = marker.parent;\n }\n\n return marker.parent === parentStateNode;\n}\n\nfunction getPathFromRootToNode(stateNode: AnyStateNode): Array<AnyStateNode> {\n const path: Array<AnyStateNode> = [];\n let marker = stateNode.parent;\n\n while (marker) {\n path.unshift(marker);\n marker = marker.parent;\n }\n\n return path;\n}\n\nfunction hasIntersection<T>(s1: Iterable<T>, s2: Iterable<T>): boolean {\n const set1 = new Set(s1);\n const set2 = new Set(s2);\n\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}\n\nexport function removeConflictingTransitions(\n enabledTransitions: Array<AnyTransitionDefinition>,\n stateNodeSet: Set<AnyStateNode>,\n historyValue: AnyHistoryValue\n): Array<AnyTransitionDefinition> {\n const filteredTransitions = new Set<AnyTransitionDefinition>();\n\n for (const t1 of enabledTransitions) {\n let t1Preempted = false;\n const transitionsToRemove = new Set<AnyTransitionDefinition>();\n for (const t2 of filteredTransitions) {\n if (\n hasIntersection(\n computeExitSet([t1], stateNodeSet, historyValue),\n computeExitSet([t2], stateNodeSet, historyValue)\n )\n ) {\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\n return Array.from(filteredTransitions);\n}\n\nfunction findLeastCommonAncestor(\n stateNodes: Array<AnyStateNode>\n): AnyStateNode | undefined {\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}\n\nfunction getEffectiveTargetStates(\n transition: Pick<AnyTransitionDefinition, 'target'>,\n historyValue: AnyHistoryValue\n): Array<AnyStateNode> {\n if (!transition.target) {\n return [];\n }\n\n const targets = new Set<AnyStateNode>();\n\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(\n resolveHistoryDefaultTransition(targetNode),\n historyValue\n )) {\n targets.add(node);\n }\n }\n } else {\n targets.add(targetNode);\n }\n }\n\n return [...targets];\n}\n\nfunction getTransitionDomain(\n transition: AnyTransitionDefinition,\n historyValue: AnyHistoryValue\n): AnyStateNode | undefined {\n const targetStates = getEffectiveTargetStates(transition, historyValue);\n\n if (!targetStates) {\n return;\n }\n\n if (\n !transition.reenter &&\n targetStates.every(\n (target) =>\n target === transition.source || isDescendant(target, transition.source)\n )\n ) {\n return transition.source;\n }\n\n const lca = findLeastCommonAncestor(targetStates.concat(transition.source));\n\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\n return transition.source.machine.root;\n}\n\nfunction computeExitSet(\n transitions: AnyTransitionDefinition[],\n stateNodeSet: Set<AnyStateNode>,\n historyValue: AnyHistoryValue\n): Array<AnyStateNode> {\n const statesToExit = new Set<AnyStateNode>();\n\n for (const t of transitions) {\n if (t.target?.length) {\n const domain = getTransitionDomain(t, historyValue);\n\n if (t.reenter && t.source === domain) {\n statesToExit.add(domain);\n }\n\n for (const stateNode of stateNodeSet) {\n if (isDescendant(stateNode, domain!)) {\n statesToExit.add(stateNode);\n }\n }\n }\n }\n\n return [...statesToExit];\n}\n\nfunction areStateNodeCollectionsEqual(\n prevStateNodes: StateNode<any, any>[],\n nextStateNodeSet: Set<StateNode<any, any>>\n) {\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/**\n * https://www.w3.org/TR/scxml/#microstepProcedure\n */\nexport function microstep<\n TContext extends MachineContext,\n TEvent extends EventObject\n>(\n transitions: Array<AnyTransitionDefinition>,\n currentSnapshot: AnyMachineSnapshot,\n actorScope: AnyActorScope,\n event: AnyEventObject,\n isInitial: boolean,\n internalQueue: Array<AnyEventObject>\n): AnyMachineSnapshot {\n if (!transitions.length) {\n return currentSnapshot;\n }\n const mutStateNodeSet = new Set(currentSnapshot._nodes);\n let historyValue = currentSnapshot.historyValue;\n\n const filteredTransitions = removeConflictingTransitions(\n transitions,\n mutStateNodeSet,\n historyValue\n );\n\n let nextState = currentSnapshot;\n\n // Exit states\n if (!isInitial) {\n [nextState, historyValue] = exitStates(\n nextState,\n event,\n actorScope,\n filteredTransitions,\n mutStateNodeSet,\n historyValue,\n internalQueue\n );\n }\n\n // Execute transition content\n nextState = resolveActionsAndContext(\n nextState,\n event,\n actorScope,\n filteredTransitions.flatMap((t) => t.actions),\n internalQueue\n );\n\n // Enter states\n nextState = enterStates(\n nextState,\n event,\n actorScope,\n filteredTransitions,\n mutStateNodeSet,\n internalQueue,\n historyValue,\n isInitial\n );\n\n const nextStateNodes = [...mutStateNodeSet];\n\n if (nextState.status === 'done') {\n nextState = resolveActionsAndContext(\n nextState,\n event,\n actorScope,\n nextStateNodes\n .sort((a, b) => b.order - a.order)\n .flatMap((state) => state.exit),\n internalQueue\n );\n }\n\n try {\n if (\n historyValue === currentSnapshot.historyValue &&\n areStateNodeCollectionsEqual(currentSnapshot._nodes, mutStateNodeSet)\n ) {\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}\n\nfunction getMachineOutput(\n snapshot: AnyMachineSnapshot,\n event: AnyEventObject,\n actorScope: AnyActorScope,\n rootNode: AnyStateNode,\n rootCompletionNode: AnyStateNode\n) {\n if (!rootNode.output) {\n return;\n }\n const doneStateEvent = createDoneStateEvent(\n rootCompletionNode.id,\n rootCompletionNode.output && rootCompletionNode.parent\n ? resolveOutput(\n rootCompletionNode.output,\n snapshot.context,\n event,\n actorScope.self\n )\n : undefined\n );\n return resolveOutput(\n rootNode.output,\n snapshot.context,\n doneStateEvent,\n actorScope.self\n );\n}\n\nfunction enterStates(\n currentSnapshot: AnyMachineSnapshot,\n event: AnyEventObject,\n actorScope: AnyActorScope,\n filteredTransitions: AnyTransitionDefinition[],\n mutStateNodeSet: Set<AnyStateNode>,\n internalQueue: AnyEventObject[],\n historyValue: HistoryValue<any, any>,\n isInitial: boolean\n) {\n let nextSnapshot = currentSnapshot;\n const statesToEnter = new Set<AnyStateNode>();\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<AnyStateNode>();\n computeEntrySet(\n filteredTransitions,\n historyValue,\n statesForDefaultEntry,\n statesToEnter\n );\n\n // In the initial state, the root state node is \"entered\".\n if (isInitial) {\n statesForDefaultEntry.add(currentSnapshot.machine.root);\n }\n\n const completedNodes = new Set();\n\n for (const stateNodeToEnter of [...statesToEnter].sort(\n (a, b) => a.order - b.order\n )) {\n mutStateNodeSet.add(stateNodeToEnter);\n const actions: UnknownAction[] = [];\n\n // Add entry actions\n actions.push(...stateNodeToEnter.entry);\n\n for (const invokeDef of stateNodeToEnter.invoke) {\n actions.push(\n spawnChild(invokeDef.src, {\n ...invokeDef,\n syncSnapshot: !!invokeDef.onSnapshot\n })\n );\n }\n\n if (statesForDefaultEntry.has(stateNodeToEnter)) {\n const initialActions = stateNodeToEnter.initial!.actions;\n actions.push(...initialActions);\n }\n\n nextSnapshot = resolveActionsAndContext(\n nextSnapshot,\n event,\n actorScope,\n actions,\n internalQueue,\n stateNodeToEnter.invoke.map((invokeDef) => invokeDef.id)\n );\n\n if (stateNodeToEnter.type === 'final') {\n const parent = stateNodeToEnter.parent;\n\n let ancestorMarker =\n parent?.type === 'parallel' ? parent : parent?.parent;\n let rootCompletionNode = ancestorMarker || stateNodeToEnter;\n\n if (parent?.type === 'compound') {\n internalQueue.push(\n createDoneStateEvent(\n parent!.id,\n stateNodeToEnter.output\n ? resolveOutput(\n stateNodeToEnter.output,\n nextSnapshot.context,\n event,\n actorScope.self\n )\n : undefined\n )\n );\n }\n while (\n ancestorMarker?.type === 'parallel' &&\n !completedNodes.has(ancestorMarker) &&\n isInFinalState(mutStateNodeSet, ancestorMarker)\n ) {\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\n nextSnapshot = cloneMachineSnapshot(nextSnapshot, {\n status: 'done',\n output: getMachineOutput(\n nextSnapshot,\n event,\n actorScope,\n nextSnapshot.machine.root,\n rootCompletionNode\n )\n });\n }\n }\n\n return nextSnapshot;\n}\n\nfunction computeEntrySet(\n transitions: Array<AnyTransitionDefinition>,\n historyValue: HistoryValue<any, any>,\n statesForDefaultEntry: Set<AnyStateNode>,\n statesToEnter: Set<AnyStateNode>\n) {\n for (const t of transitions) {\n const domain = getTransitionDomain(t, historyValue);\n\n for (const s of t.target || []) {\n if (\n !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 ) {\n statesToEnter.add(s);\n statesForDefaultEntry.add(s);\n }\n addDescendantStatesToEnter(\n s,\n historyValue,\n statesForDefaultEntry,\n statesToEnter\n );\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(\n statesToEnter,\n historyValue,\n statesForDefaultEntry,\n ancestors,\n !t.source.parent && t.reenter ? undefined : domain\n );\n }\n }\n}\n\nfunction addDescendantStatesToEnter<\n TContext extends MachineContext,\n TEvent extends EventObject\n>(\n stateNode: AnyStateNode,\n historyValue: HistoryValue<any, any>,\n statesForDefaultEntry: Set<AnyStateNode>,\n statesToEnter: Set<AnyStateNode>\n) {\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\n addDescendantStatesToEnter(\n s,\n historyValue,\n statesForDefaultEntry,\n statesToEnter\n );\n }\n for (const s of historyStateNodes) {\n addProperAncestorStatesToEnter(\n s,\n stateNode.parent!,\n statesToEnter,\n historyValue,\n statesForDefaultEntry\n );\n }\n } else {\n const historyDefaultTransition = resolveHistoryDefaultTransition<\n TContext,\n TEvent\n >(stateNode);\n for (const s of historyDefaultTransition.target) {\n statesToEnter.add(s);\n\n if (historyDefaultTransition === stateNode.parent?.initial) {\n statesForDefaultEntry.add(stateNode.parent);\n }\n\n addDescendantStatesToEnter(\n s,\n historyValue,\n statesForDefaultEntry,\n statesToEnter\n );\n }\n\n for (const s of historyDefaultTransition.target) {\n addProperAncestorStatesToEnter(\n s,\n stateNode,\n statesToEnter,\n historyValue,\n statesForDefaultEntry\n );\n }\n }\n } else {\n if (stateNode.type === 'compound') {\n const [initialState] = stateNode.initial.target;\n\n if (!isHistoryNode(initialState)) {\n statesToEnter.add(initialState);\n statesForDefaultEntry.add(initialState);\n }\n addDescendantStatesToEnter(\n initialState,\n historyValue,\n statesForDefaultEntry,\n statesToEnter\n );\n\n addProperAncestorStatesToEnter(\n initialState,\n stateNode,\n statesToEnter,\n historyValue,\n statesForDefaultEntry\n );\n } else {\n if (stateNode.type === 'parallel') {\n for (const child of getChildren(stateNode).filter(\n (sn) => !isHistoryNode(sn)\n )) {\n if (![...statesToEnter].some((s) => isDescendant(s, child))) {\n if (!isHistoryNode(child)) {\n statesToEnter.add(child);\n statesForDefaultEntry.add(child);\n }\n addDescendantStatesToEnter(\n child,\n historyValue,\n statesForDefaultEntry,\n statesToEnter\n );\n }\n }\n }\n }\n }\n}\n\nfunction addAncestorStatesToEnter(\n statesToEnter: Set<AnyStateNode>,\n historyValue: HistoryValue<any, any>,\n statesForDefaultEntry: Set<AnyStateNode>,\n ancestors: AnyStateNode[],\n reentrancyDomain?: AnyStateNode\n) {\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(\n child,\n historyValue,\n statesForDefaultEntry,\n statesToEnter\n );\n }\n }\n }\n }\n}\n\nfunction addProperAncestorStatesToEnter(\n stateNode: AnyStateNode,\n toStateNode: AnyStateNode | undefined,\n statesToEnter: Set<AnyStateNode>,\n historyValue: HistoryValue<any, any>,\n statesForDefaultEntry: Set<AnyStateNode>\n) {\n addAncestorStatesToEnter(\n statesToEnter,\n historyValue,\n statesForDefaultEntry,\n getProperAncestors(stateNode, toStateNode)\n );\n}\n\nfunction exitStates(\n currentSnapshot: AnyMachineSnapshot,\n event: AnyEventObject,\n actorScope: AnyActorScope,\n transitions: AnyTransitionDefinition[],\n mutStateNodeSet: Set<AnyStateNode>,\n historyValue: HistoryValue<any, any>,\n internalQueue: AnyEventObject[]\n) {\n let nextSnapshot = currentSnapshot;\n const statesToExit = computeExitSet(\n transitions,\n mutStateNodeSet,\n historyValue\n );\n\n statesToExit.sort((a, b) => b.order - a.order);\n\n let changedHistory: typeof historyValue | undefined;\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: (sn: AnyStateNode) => boolean;\n if (historyNode.history === 'deep') {\n predicate = (sn) =>\n isAtomicStateNode(sn) && isDescendant(sn, exitStateNode);\n } else {\n predicate = (sn) => {\n return sn.parent === exitStateNode;\n };\n }\n changedHistory ??= { ...historyValue };\n changedHistory[historyNode.id] =\n Array.from(mutStateNodeSet).filter(predicate);\n }\n }\n\n for (const s of statesToExit) {\n nextSnapshot = resolveActionsAndContext(\n nextSnapshot,\n event,\n actorScope,\n [...s.exit, ...s.invoke.map((def) => stopChild(def.id))],\n internalQueue\n );\n mutStateNodeSet.delete(s);\n }\n return [nextSnapshot, changedHistory || historyValue] as const;\n}\n\ninterface BuiltinAction {\n (): void;\n resolve: (\n actorScope: AnyActorScope,\n snapshot: AnyMachineSnapshot,\n actionArgs: ActionArgs<any, any, any>,\n actionParams: ParameterizedObject['params'] | undefined,\n action: unknown,\n extra: unknown\n ) => [\n newState: AnyMachineSnapshot,\n params: unknown,\n actions?: UnknownAction[]\n ];\n retryResolve: (\n actorScope: AnyActorScope,\n snapshot: AnyMachineSnapshot,\n params: unknown\n ) => void;\n execute: (actorScope: AnyActorScope, params: unknown) => void;\n}\n\nfunction resolveActionsAndContextWorker(\n currentSnapshot: AnyMachineSnapshot,\n event: AnyEventObject,\n actorScope: AnyActorScope,\n actions: UnknownAction[],\n extra: {\n internalQueue: AnyEventObject[];\n deferredActorIds: string[] | undefined;\n },\n retries: (readonly [BuiltinAction, unknown])[] | undefined\n): AnyMachineSnapshot {\n const { machine } = currentSnapshot;\n let intermediateSnapshot = currentSnapshot;\n\n for (const action of actions) {\n const isInline = typeof action === 'function';\n const resolvedAction = isInline\n ? 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 machine.implementations.actions as Record<\n string,\n ActionFunction<\n MachineContext,\n EventObject,\n EventObject,\n ParameterizedObject['params'] | undefined,\n ProvidedActor,\n ParameterizedObject,\n ParameterizedObject,\n string\n >\n >\n )[typeof action === 'string' ? action : action.type];\n\n if (!resolvedAction) {\n continue;\n }\n\n const actionArgs = {\n context: intermediateSnapshot.context,\n event,\n self: actorScope?.self,\n system: actorScope?.system\n };\n\n const actionParams =\n isInline || typeof action === 'string'\n ? undefined\n : 'params' in action\n ? typeof action.params === 'function'\n ? action.params({ context: intermediateSnapshot.context, event })\n : action.params\n : undefined;\n\n if (!('resolve' in resolvedAction)) {\n if (actorScope?.self._processingStatus === ProcessingStatus.Running) {\n resolvedAction(actionArgs, actionParams);\n } else {\n actorScope?.defer(() => {\n resolvedAction(actionArgs, actionParams);\n });\n }\n continue;\n }\n\n const builtinAction = resolvedAction as BuiltinAction;\n\n const [nextState, params, actions] = builtinAction.resolve(\n actorScope,\n intermediateSnapshot,\n actionArgs,\n actionParams,\n resolvedAction, // this holds all params\n extra\n );\n intermediateSnapshot = nextState;\n\n if ('retryResolve' in builtinAction) {\n retries?.push([builtinAction, params]);\n }\n\n if ('execute' in builtinAction) {\n if (actorScope?.self._processingStatus === ProcessingStatus.Running) {\n builtinAction.execute(actorScope!, params);\n } else {\n actorScope?.defer(\n builtinAction.execute.bind(null, actorScope!, params)\n );\n }\n }\n\n if (actions) {\n intermediateSnapshot = resolveActionsAndContextWorker(\n intermediateSnapshot,\n event,\n actorScope,\n actions,\n extra,\n retries\n );\n }\n }\n\n return intermediateSnapshot;\n}\n\nexport function resolveActionsAndContext(\n currentSnapshot: AnyMachineSnapshot,\n event: AnyEventObject,\n actorScope: AnyActorScope,\n actions: UnknownAction[],\n internalQueue: AnyEventObject[],\n deferredActorIds?: string[]\n): AnyMachineSnapshot {\n const retries: (readonly [BuiltinAction, unknown])[] | undefined =\n deferredActorIds ? [] : undefined;\n const nextState = resolveActionsAndContextWorker(\n currentSnapshot,\n event,\n actorScope,\n actions,\n { internalQueue, deferredActorIds },\n retries\n );\n retries?.forEach(([builtinAction, params]) => {\n builtinAction.retryResolve(actorScope, nextState, params);\n });\n return nextState;\n}\n\nexport function macrostep(\n snapshot: AnyMachineSnapshot,\n event: EventObject,\n actorScope: AnyActorScope,\n internalQueue: AnyEventObject[] = []\n): {\n snapshot: typeof snapshot;\n microstates: Array<typeof snapshot>;\n} {\n if (isDevelopment && event.type === WILDCARD) {\n throw new Error(`An event cannot have the wildcard type ('${WILDCARD}')`);\n }\n\n let nextSnapshot = snapshot;\n const states: AnyMachineSnapshot[] = [];\n\n // Handle stop event\n if (event.type === XSTATE_STOP) {\n nextSnapshot = cloneMachineSnapshot(\n stopChildren(nextSnapshot, event, actorScope),\n {\n status: 'stopped'\n }\n );\n states.push(nextSnapshot);\n\n return {\n snapshot: nextSnapshot,\n microstates: states\n };\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\n const transitions = selectTransitions(currentEvent, nextSnapshot);\n\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<typeof snapshot>(snapshot, {\n status: 'error',\n error: currentEvent.error\n });\n states.push(nextSnapshot);\n return {\n snapshot: nextSnapshot,\n microstates: states\n };\n }\n nextSnapshot = microstep(\n transitions,\n snapshot,\n actorScope,\n nextEvent,\n false,\n internalQueue\n );\n states.push(nextSnapshot);\n }\n\n let shouldSelectEventlessTransitions = true;\n\n while (nextSnapshot.status === 'active') {\n let enabledTransitions: AnyTransitionDefinition[] =\n shouldSelectEventlessTransitions\n ? selectEventlessTransitions(nextSnapshot, nextEvent)\n : [];\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\n if (!enabledTransitions.length) {\n if (!internalQueue.length) {\n break;\n }\n nextEvent = internalQueue.shift()!;\n enabledTransitions = selectTransitions(nextEvent, nextSnapshot);\n }\n\n nextSnapshot = microstep(\n enabledTransitions,\n nextSnapshot,\n actorScope,\n nextEvent,\n false,\n internalQueue\n );\n shouldSelectEventlessTransitions = nextSnapshot !== previousState;\n states.push(nextSnapshot);\n }\n\n if (nextSnapshot.status !== 'active') {\n stopChildren(nextSnapshot, nextEvent, actorScope);\n }\n\n return {\n snapshot: nextSnapshot,\n microstates: states\n };\n}\n\nfunction stopChildren(\n nextState: AnyMachineSnapshot,\n event: AnyEventObject,\n actorScope: AnyActorScope\n) {\n return resolveActionsAndContext(\n nextState,\n event,\n actorScope,\n Object.values(nextState.children).map((child: any) => stopChild(child)),\n []\n );\n}\n\nfunction selectTransitions(\n event: AnyEventObject,\n nextState: AnyMachineSnapshot\n): AnyTransitionDefinition[] {\n return nextState.machine.getTransitionData(nextState as any, event);\n}\n\nfunction selectEventlessTransitions(\n nextState: AnyMachineSnapshot,\n event: AnyEventObject\n): AnyTransitionDefinition[] {\n const enabledTransitionSet: Set<AnyTransitionDefinition> = new Set();\n const atomicStates = nextState._nodes.filter(isAtomicStateNode);\n\n for (const stateNode of atomicStates) {\n loop: for (const s of [stateNode].concat(\n getProperAncestors(stateNode, undefined)\n )) {\n if (!s.always) {\n continue;\n }\n for (const transition of s.always) {\n if (\n transition.guard === undefined ||\n evaluateGuard(transition.guard, nextState.context, event, nextState)\n ) {\n enabledTransitionSet.add(transition);\n break loop;\n }\n }\n }\n }\n\n return removeConflictingTransitions(\n Array.from(enabledTransitionSet),\n new Set(nextState._nodes),\n nextState.historyValue\n );\n}\n\n/**\n * Resolves a partial state value with its full representation in the state node's machine.\n *\n * @param stateValue The partial state value to resolve.\n */\nexport function resolveStateValue(\n rootNode: AnyStateNode,\n stateValue: StateValue\n): StateValue {\n const allStateNodes = getAllStateNodes(getStateNodes(rootNode, stateValue));\n return getStateValue(rootNode, [...allStateNodes]);\n}\n\nexport function stateValuesEqual(\n a: StateValue | undefined,\n b: StateValue | undefined\n): boolean {\n if (a === b) {\n return true;\n }\n\n if (a === undefined || b === undefined) {\n return false;\n }\n\n if (typeof a === 'string' || typeof b === 'string') {\n return a === b;\n }\n\n const aKeys = Object.keys(a as StateValueMap);\n const bKeys = Object.keys(b as StateValueMap);\n\n return (\n aKeys.length === bKeys.length &&\n aKeys.every((key) => stateValuesEqual(a[key], b[key]))\n );\n}\n","import isDevelopment from '#is-development';\nimport type {\n EventObject,\n StateValue,\n MachineContext,\n ParameterizedObject,\n AnyMachineSnapshot,\n NoRequiredParams,\n NoInfer,\n WithDynamicParams,\n Identity,\n Elements\n} from './types.ts';\nimport { isStateId } from './stateUtils.ts';\n\ntype SingleGuardArg<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TParams extends ParameterizedObject['params'] | undefined,\n TGuardArg\n> = [TGuardArg] extends [{ type: string }]\n ? Identity<TGuardArg>\n : [TGuardArg] extends [string]\n ? TGuardArg\n : GuardPredicate<TContext, TExpressionEvent, TParams, ParameterizedObject>;\n\ntype NormalizeGuardArg<TGuardArg> = TGuardArg extends { type: string }\n ? Identity<TGuardArg> & { params: unknown }\n : TGuardArg extends string\n ? { type: TGuardArg; params: undefined }\n : '_out_TGuard' extends keyof TGuardArg\n ? TGuardArg['_out_TGuard'] & ParameterizedObject\n : never;\n\ntype NormalizeGuardArgArray<TArg extends unknown[]> = Elements<{\n [K in keyof TArg]: NormalizeGuardArg<TArg[K]>;\n}>;\n\nexport type GuardPredicate<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TParams extends ParameterizedObject['params'] | undefined,\n TGuard extends ParameterizedObject\n> = {\n (args: GuardArgs<TContext, TExpressionEvent>, params: TParams): boolean;\n _out_TGuard?: TGuard;\n};\n\nexport interface GuardArgs<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject\n> {\n context: TContext;\n event: TExpressionEvent;\n}\n\nexport type Guard<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TParams extends ParameterizedObject['params'] | undefined,\n TGuard extends ParameterizedObject\n> =\n | NoRequiredParams<TGuard>\n | WithDynamicParams<TContext, TExpressionEvent, TGuard>\n | GuardPredicate<TContext, TExpressionEvent, TParams, TGuard>;\n\nexport type UnknownGuard = UnknownReferencedGuard | UnknownInlineGuard;\n\ntype UnknownReferencedGuard = Guard<\n MachineContext,\n EventObject,\n ParameterizedObject['params'],\n ParameterizedObject\n>;\n\ntype UnknownInlineGuard = Guard<\n MachineContext,\n EventObject,\n undefined,\n ParameterizedObject\n>;\n\ninterface BuiltinGuard {\n (): boolean;\n check: (\n snapshot: AnyMachineSnapshot,\n guardArgs: GuardArgs<any, any>,\n params: unknown\n ) => boolean;\n}\n\nfunction checkStateIn(\n snapshot: AnyMachineSnapshot,\n _: GuardArgs<any, any>,\n { stateValue }: { stateValue: 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\n return snapshot.matches(stateValue);\n}\n\nexport function stateIn<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TParams extends ParameterizedObject['params'] | undefined\n>(\n stateValue: StateValue\n): GuardPredicate<\n TContext,\n TExpressionEvent,\n TParams,\n any // TODO: recheck if we could replace this with something better here\n> {\n function stateIn(\n args: GuardArgs<TContext, TExpressionEvent>,\n params: TParams\n ) {\n if (isDevelopment) {\n throw new Error(`This isn't supposed to be called`);\n }\n return false;\n }\n\n stateIn.check = checkStateIn;\n stateIn.stateValue = stateValue;\n\n return stateIn;\n}\n\nfunction checkNot(\n snapshot: AnyMachineSnapshot,\n { context, event }: GuardArgs<any, any>,\n { guards }: { guards: readonly UnknownGuard[] }\n) {\n return !evaluateGuard(guards[0], context, event, snapshot);\n}\n\nexport function not<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TArg\n>(\n guard: SingleGuardArg<TContext, TExpressionEvent, unknown, TArg>\n): GuardPredicate<\n TContext,\n TExpressionEvent,\n unknown,\n NormalizeGuardArg<NoInfer<TArg>>\n> {\n function not(args: GuardArgs<TContext, TExpressionEvent>, params: unknown) {\n if (isDevelopment) {\n throw new Error(`This isn't supposed to be called`);\n }\n return false;\n }\n\n not.check = checkNot;\n not.guards = [guard];\n\n return not;\n}\n\nfunction checkAnd(\n snapshot: AnyMachineSnapshot,\n { context, event }: GuardArgs<any, any>,\n { guards }: { guards: readonly UnknownGuard[] }\n) {\n return guards.every((guard) =>\n evaluateGuard(guard, context, event, snapshot)\n );\n}\n\nexport function and<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TArg extends unknown[]\n>(\n guards: readonly [\n ...{\n [K in keyof TArg]: SingleGuardArg<\n TContext,\n TExpressionEvent,\n unknown,\n TArg[K]\n >;\n }\n ]\n): GuardPredicate<\n TContext,\n TExpressionEvent,\n unknown,\n NormalizeGuardArgArray<NoInfer<TArg>>\n> {\n function and(args: GuardArgs<TContext, TExpressionEvent>, params: unknown) {\n if (isDevelopment) {\n throw new Error(`This isn't supposed to be called`);\n }\n return false;\n }\n\n and.check = checkAnd;\n and.guards = guards;\n\n return and;\n}\n\nfunction checkOr(\n snapshot: AnyMachineSnapshot,\n { context, event }: GuardArgs<any, any>,\n { guards }: { guards: readonly UnknownGuard[] }\n) {\n return guards.some((guard) => evaluateGuard(guard, context, event, snapshot));\n}\n\nexport function or<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TArg extends unknown[]\n>(\n guards: readonly [\n ...{\n [K in keyof TArg]: SingleGuardArg<\n TContext,\n TExpressionEvent,\n unknown,\n TArg[K]\n >;\n }\n ]\n): GuardPredicate<\n TContext,\n TExpressionEvent,\n unknown,\n NormalizeGuardArgArray<NoInfer<TArg>>\n> {\n function or(args: GuardArgs<TContext, TExpressionEvent>, params: unknown) {\n if (isDevelopment) {\n throw new Error(`This isn't supposed to be called`);\n }\n return false;\n }\n\n or.check = checkOr;\n or.guards = guards;\n\n return or;\n}\n\n// TODO: throw on cycles (depth check should be enough)\nexport function evaluateGuard<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject\n>(\n guard: UnknownGuard | UnknownInlineGuard,\n context: TContext,\n event: TExpressionEvent,\n snapshot: AnyMachineSnapshot\n): boolean {\n const { machine } = snapshot;\n const isInline = typeof guard === 'function';\n\n const resolved = isInline\n ? guard\n : machine.implementations.guards[\n typeof guard === 'string' ? guard : guard.type\n ];\n\n if (!isInline && !resolved) {\n throw new Error(\n `Guard '${\n typeof guard === 'string' ? guard : guard.type\n }' is not implemented.'.`\n );\n }\n\n if (typeof resolved !== 'function') {\n return evaluateGuard(resolved!, context, event, snapshot);\n }\n\n const guardArgs = {\n context,\n event\n };\n\n const guardParams =\n isInline || typeof guard === 'string'\n ? undefined\n : 'params' in guard\n ? typeof guard.params === 'function'\n ? guard.params({ context, event })\n : guard.params\n : undefined;\n\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 as never);\n }\n\n const builtinGuard = resolved as unknown as BuiltinGuard;\n\n return builtinGuard.check(\n snapshot,\n guardArgs,\n resolved // this holds all params\n );\n}\n"],"names":["isStateId","str","checkStateIn","snapshot","_","stateValue","target","machine","getStateNodeById","_nodes","some","sn","matches","checkNot","context","event","guards","evaluateGuard","checkAnd","every","guard","checkOr","isInline","resolved","implementations","type","Error","guardArgs","guardParams","undefined","params","check","and","args","not","or","stateIn"],"mappings":"oPAGO,MC8MMA,EAAaC,GD9MM,MC8MUA,EAAI,GCtH9C,SAASC,EACPC,EACAC,GACAC,WAAEA,IAEF,GAA0B,iBAAfA,GAA2BL,EAAUK,GAAa,CAC3D,MAAMC,EAASH,EAASI,QAAQC,iBAAiBH,GACjD,OAAOF,EAASM,OAAOC,MAAMC,GAAOA,IAAOL,GAC7C,CAEA,OAAOH,EAASS,QAAQP,EAC1B,CA8BA,SAASQ,EACPV,GACAW,QAAEA,EAAOC,MAAEA,IACXC,OAAEA,IAEF,OAAQC,EAAcD,EAAO,GAAIF,EAASC,EAAOZ,EACnD,CA2BA,SAASe,EACPf,GACAW,QAAEA,EAAOC,MAAEA,IACXC,OAAEA,IAEF,OAAOA,EAAOG,OAAOC,GACnBH,EAAcG,EAAON,EAASC,EAAOZ,IAEzC,CAoCA,SAASkB,EACPlB,GACAW,QAAEA,EAAOC,MAAEA,IACXC,OAAEA,IAEF,OAAOA,EAAON,MAAMU,GAAUH,EAAcG,EAAON,EAASC,EAAOZ,IACrE,CAqCO,SAASc,EAIdG,EACAN,EACAC,EACAZ,GAEA,MAAMI,QAAEA,GAAYJ,EACdmB,EAA4B,mBAAVF,EAElBG,EAAWD,EACbF,EACAb,EAAQiB,gBAAgBR,OACL,iBAAVI,EAAqBA,EAAQA,EAAMK,MAGhD,IAAKH,IAAaC,EAChB,MAAM,IAAIG,MACP,UACkB,iBAAVN,EAAqBA,EAAQA,EAAMK,+BAKhD,GAAwB,mBAAbF,EACT,OAAON,EAAcM,EAAWT,EAASC,EAAOZ,GAGlD,MAAMwB,EAAY,CAChBb,UACAC,SAGIa,EACJN,GAA6B,iBAAVF,OACfS,EACA,WAAYT,EACc,mBAAjBA,EAAMU,OACXV,EAAMU,OAAO,CAAEhB,UAASC,UACxBK,EAAMU,YACRD,EAER,KAAM,UAAWN,GAIf,OAAOA,EAASI,EAAWC,GAK7B,OAFqBL,EAEDQ,MAClB5B,EACAwB,EACAJ,EAEJ,OAvIO,SAKLP,GAgBA,SAASgB,EAAIC,EAA6CH,GAIxD,OAAO,CACT,CAKA,OAHAE,EAAID,MAAQb,EACZc,EAAIhB,OAASA,EAENgB,CACT,0BAnEO,SAKLZ,GAOA,SAASc,EAAID,EAA6CH,GAIxD,OAAO,CACT,CAKA,OAHAI,EAAIH,MAAQlB,EACZqB,EAAIlB,OAAS,CAACI,GAEPc,CACT,OAsDO,SAKLlB,GAgBA,SAASmB,EAAGF,EAA6CH,GAIvD,OAAO,CACT,CAKA,OAHAK,EAAGJ,MAAQV,EACXc,EAAGnB,OAASA,EAELmB,CACT,YAjJO,SAKL9B,GAOA,SAAS+B,EACPH,EACAH,GAKA,OAAO,CACT,CAKA,OAHAM,EAAQL,MAAQ7B,EAChBkC,EAAQ/B,WAAaA,EAEd+B,CACT"}
package/package.json CHANGED
@@ -1,33 +1,89 @@
1
1
  {
2
2
  "name": "xstate",
3
- "version": "5.0.0-beta.8",
3
+ "version": "5.0.0",
4
4
  "description": "Finite State Machines and Statecharts for the Modern Web.",
5
5
  "main": "dist/xstate.cjs.js",
6
6
  "module": "dist/xstate.esm.js",
7
7
  "umd:main": "dist/xstate.umd.min.js",
8
8
  "exports": {
9
9
  ".": {
10
+ "types": {
11
+ "import": "./dist/xstate.cjs.mjs",
12
+ "default": "./dist/xstate.cjs.js"
13
+ },
14
+ "development": {
15
+ "module": "./dist/xstate.development.esm.js",
16
+ "import": "./dist/xstate.development.cjs.mjs",
17
+ "default": "./dist/xstate.development.cjs.js"
18
+ },
10
19
  "module": "./dist/xstate.esm.js",
20
+ "import": "./dist/xstate.cjs.mjs",
11
21
  "default": "./dist/xstate.cjs.js"
12
22
  },
13
23
  "./guards": {
24
+ "types": {
25
+ "import": "./guards/dist/xstate-guards.cjs.mjs",
26
+ "default": "./guards/dist/xstate-guards.cjs.js"
27
+ },
28
+ "development": {
29
+ "module": "./guards/dist/xstate-guards.development.esm.js",
30
+ "import": "./guards/dist/xstate-guards.development.cjs.mjs",
31
+ "default": "./guards/dist/xstate-guards.development.cjs.js"
32
+ },
14
33
  "module": "./guards/dist/xstate-guards.esm.js",
34
+ "import": "./guards/dist/xstate-guards.cjs.mjs",
15
35
  "default": "./guards/dist/xstate-guards.cjs.js"
16
36
  },
17
37
  "./actions": {
38
+ "types": {
39
+ "import": "./actions/dist/xstate-actions.cjs.mjs",
40
+ "default": "./actions/dist/xstate-actions.cjs.js"
41
+ },
42
+ "development": {
43
+ "module": "./actions/dist/xstate-actions.development.esm.js",
44
+ "import": "./actions/dist/xstate-actions.development.cjs.mjs",
45
+ "default": "./actions/dist/xstate-actions.development.cjs.js"
46
+ },
18
47
  "module": "./actions/dist/xstate-actions.esm.js",
48
+ "import": "./actions/dist/xstate-actions.cjs.mjs",
19
49
  "default": "./actions/dist/xstate-actions.cjs.js"
20
50
  },
21
51
  "./dev": {
52
+ "types": {
53
+ "import": "./dev/dist/xstate-dev.cjs.mjs",
54
+ "default": "./dev/dist/xstate-dev.cjs.js"
55
+ },
56
+ "development": {
57
+ "module": "./dev/dist/xstate-dev.development.esm.js",
58
+ "import": "./dev/dist/xstate-dev.development.cjs.mjs",
59
+ "default": "./dev/dist/xstate-dev.development.cjs.js"
60
+ },
22
61
  "module": "./dev/dist/xstate-dev.esm.js",
62
+ "import": "./dev/dist/xstate-dev.cjs.mjs",
23
63
  "default": "./dev/dist/xstate-dev.cjs.js"
24
64
  },
25
65
  "./actors": {
66
+ "types": {
67
+ "import": "./actors/dist/xstate-actors.cjs.mjs",
68
+ "default": "./actors/dist/xstate-actors.cjs.js"
69
+ },
70
+ "development": {
71
+ "module": "./actors/dist/xstate-actors.development.esm.js",
72
+ "import": "./actors/dist/xstate-actors.development.cjs.mjs",
73
+ "default": "./actors/dist/xstate-actors.development.cjs.js"
74
+ },
26
75
  "module": "./actors/dist/xstate-actors.esm.js",
76
+ "import": "./actors/dist/xstate-actors.cjs.mjs",
27
77
  "default": "./actors/dist/xstate-actors.cjs.js"
28
78
  },
29
79
  "./package.json": "./package.json"
30
80
  },
81
+ "imports": {
82
+ "#is-development": {
83
+ "development": "./src/true.ts",
84
+ "default": "./src/false.ts"
85
+ }
86
+ },
31
87
  "sideEffects": false,
32
88
  "funding": {
33
89
  "type": "opencollective",
@@ -63,6 +119,8 @@
63
119
  "homepage": "https://github.com/statelyai/xstate/tree/main/packages/core#readme",
64
120
  "devDependencies": {
65
121
  "@scion-scxml/test-framework": "^2.0.15",
122
+ "@xstate-repo/jest-utils": "*",
123
+ "ajv": "^8.12.0",
66
124
  "jsdom": "^14.0.0",
67
125
  "jsdom-global": "^3.0.2",
68
126
  "pkg-up": "^3.1.0",
@@ -1,32 +0,0 @@
1
- 'use strict';
2
-
3
- Object.defineProperty(exports, '__esModule', { value: true });
4
-
5
- var actors_dist_xstateActors = require('../../dist/actions-d06ca158.cjs.dev.js');
6
- require('../../dist/index-ebaab3c9.cjs.dev.js');
7
-
8
-
9
-
10
- exports.actionTypes = actors_dist_xstateActors.actionTypes;
11
- exports.after = actors_dist_xstateActors.after;
12
- exports.assign = actors_dist_xstateActors.assign;
13
- exports.cancel = actors_dist_xstateActors.cancel;
14
- exports.choose = actors_dist_xstateActors.choose;
15
- exports.createInitEvent = actors_dist_xstateActors.createInitEvent;
16
- exports.done = actors_dist_xstateActors.done;
17
- exports.doneInvoke = actors_dist_xstateActors.doneInvoke;
18
- exports.error = actors_dist_xstateActors.error;
19
- exports.escalate = actors_dist_xstateActors.escalate;
20
- exports.forwardTo = actors_dist_xstateActors.forwardTo;
21
- exports.initEvent = actors_dist_xstateActors.initEvent;
22
- exports.log = actors_dist_xstateActors.log;
23
- exports.pure = actors_dist_xstateActors.pure;
24
- exports.raise = actors_dist_xstateActors.raise;
25
- exports.resolveActionObject = actors_dist_xstateActors.resolveActionObject;
26
- exports.respond = actors_dist_xstateActors.respond;
27
- exports.send = actors_dist_xstateActors.send;
28
- exports.sendParent = actors_dist_xstateActors.sendParent;
29
- exports.sendTo = actors_dist_xstateActors.sendTo;
30
- exports.stop = actors_dist_xstateActors.stop;
31
- exports.toActionObject = actors_dist_xstateActors.toActionObject;
32
- exports.toActionObjects = actors_dist_xstateActors.toActionObjects;
@@ -1,32 +0,0 @@
1
- 'use strict';
2
-
3
- Object.defineProperty(exports, '__esModule', { value: true });
4
-
5
- var actors_dist_xstateActors = require('../../dist/actions-900f9761.cjs.prod.js');
6
- require('../../dev/dist/xstate-dev.cjs.prod.js');
7
-
8
-
9
-
10
- exports.actionTypes = actors_dist_xstateActors.actionTypes;
11
- exports.after = actors_dist_xstateActors.after;
12
- exports.assign = actors_dist_xstateActors.assign;
13
- exports.cancel = actors_dist_xstateActors.cancel;
14
- exports.choose = actors_dist_xstateActors.choose;
15
- exports.createInitEvent = actors_dist_xstateActors.createInitEvent;
16
- exports.done = actors_dist_xstateActors.done;
17
- exports.doneInvoke = actors_dist_xstateActors.doneInvoke;
18
- exports.error = actors_dist_xstateActors.error;
19
- exports.escalate = actors_dist_xstateActors.escalate;
20
- exports.forwardTo = actors_dist_xstateActors.forwardTo;
21
- exports.initEvent = actors_dist_xstateActors.initEvent;
22
- exports.log = actors_dist_xstateActors.log;
23
- exports.pure = actors_dist_xstateActors.pure;
24
- exports.raise = actors_dist_xstateActors.raise;
25
- exports.resolveActionObject = actors_dist_xstateActors.resolveActionObject;
26
- exports.respond = actors_dist_xstateActors.respond;
27
- exports.send = actors_dist_xstateActors.send;
28
- exports.sendParent = actors_dist_xstateActors.sendParent;
29
- exports.sendTo = actors_dist_xstateActors.sendTo;
30
- exports.stop = actors_dist_xstateActors.stop;
31
- exports.toActionObject = actors_dist_xstateActors.toActionObject;
32
- exports.toActionObjects = actors_dist_xstateActors.toActionObjects;