@camcima/finita 2.0.0 → 2.1.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 (297) hide show
  1. package/LICENSE +21 -0
  2. package/dist/index.cjs +1422 -0
  3. package/dist/index.cjs.map +1 -0
  4. package/dist/index.d.cts +525 -0
  5. package/dist/index.d.ts +525 -22
  6. package/dist/index.js +1356 -26
  7. package/dist/index.js.map +1 -1
  8. package/package.json +21 -4
  9. package/dist/Dispatcher.d.ts +0 -11
  10. package/dist/Dispatcher.d.ts.map +0 -1
  11. package/dist/Dispatcher.js +0 -30
  12. package/dist/Dispatcher.js.map +0 -1
  13. package/dist/Event.d.ts +0 -22
  14. package/dist/Event.d.ts.map +0 -1
  15. package/dist/Event.js +0 -54
  16. package/dist/Event.js.map +0 -1
  17. package/dist/MaybePromise.d.ts +0 -2
  18. package/dist/MaybePromise.d.ts.map +0 -1
  19. package/dist/MaybePromise.js +0 -2
  20. package/dist/MaybePromise.js.map +0 -1
  21. package/dist/Process.d.ts +0 -15
  22. package/dist/Process.d.ts.map +0 -1
  23. package/dist/Process.js +0 -43
  24. package/dist/Process.js.map +0 -1
  25. package/dist/State.d.ts +0 -22
  26. package/dist/State.d.ts.map +0 -1
  27. package/dist/State.js +0 -65
  28. package/dist/State.js.map +0 -1
  29. package/dist/StateCollection.d.ts +0 -14
  30. package/dist/StateCollection.d.ts.map +0 -1
  31. package/dist/StateCollection.js +0 -37
  32. package/dist/StateCollection.js.map +0 -1
  33. package/dist/Statemachine.d.ts +0 -45
  34. package/dist/Statemachine.d.ts.map +0 -1
  35. package/dist/Statemachine.js +0 -206
  36. package/dist/Statemachine.js.map +0 -1
  37. package/dist/Transition.d.ts +0 -19
  38. package/dist/Transition.d.ts.map +0 -1
  39. package/dist/Transition.js +0 -46
  40. package/dist/Transition.js.map +0 -1
  41. package/dist/condition/AndComposite.d.ts +0 -9
  42. package/dist/condition/AndComposite.d.ts.map +0 -1
  43. package/dist/condition/AndComposite.js +0 -23
  44. package/dist/condition/AndComposite.js.map +0 -1
  45. package/dist/condition/CallbackCondition.d.ts +0 -11
  46. package/dist/condition/CallbackCondition.d.ts.map +0 -1
  47. package/dist/condition/CallbackCondition.js +0 -15
  48. package/dist/condition/CallbackCondition.js.map +0 -1
  49. package/dist/condition/Contradiction.d.ts +0 -8
  50. package/dist/condition/Contradiction.d.ts.map +0 -1
  51. package/dist/condition/Contradiction.js +0 -13
  52. package/dist/condition/Contradiction.js.map +0 -1
  53. package/dist/condition/Not.d.ts +0 -8
  54. package/dist/condition/Not.d.ts.map +0 -1
  55. package/dist/condition/Not.js +0 -13
  56. package/dist/condition/Not.js.map +0 -1
  57. package/dist/condition/OrComposite.d.ts +0 -9
  58. package/dist/condition/OrComposite.d.ts.map +0 -1
  59. package/dist/condition/OrComposite.js +0 -23
  60. package/dist/condition/OrComposite.js.map +0 -1
  61. package/dist/condition/Tautology.d.ts +0 -8
  62. package/dist/condition/Tautology.d.ts.map +0 -1
  63. package/dist/condition/Tautology.js +0 -13
  64. package/dist/condition/Tautology.js.map +0 -1
  65. package/dist/condition/Timeout.d.ts +0 -10
  66. package/dist/condition/Timeout.d.ts.map +0 -1
  67. package/dist/condition/Timeout.js +0 -30
  68. package/dist/condition/Timeout.js.map +0 -1
  69. package/dist/condition/index.d.ts +0 -9
  70. package/dist/condition/index.d.ts.map +0 -1
  71. package/dist/condition/index.js +0 -8
  72. package/dist/condition/index.js.map +0 -1
  73. package/dist/error/DuplicateStateError.d.ts +0 -5
  74. package/dist/error/DuplicateStateError.d.ts.map +0 -1
  75. package/dist/error/DuplicateStateError.js +0 -9
  76. package/dist/error/DuplicateStateError.js.map +0 -1
  77. package/dist/error/LockCanNotBeAcquiredError.d.ts +0 -4
  78. package/dist/error/LockCanNotBeAcquiredError.d.ts.map +0 -1
  79. package/dist/error/LockCanNotBeAcquiredError.js +0 -7
  80. package/dist/error/LockCanNotBeAcquiredError.js.map +0 -1
  81. package/dist/error/WrongEventForStateError.d.ts +0 -6
  82. package/dist/error/WrongEventForStateError.d.ts.map +0 -1
  83. package/dist/error/WrongEventForStateError.js +0 -11
  84. package/dist/error/WrongEventForStateError.js.map +0 -1
  85. package/dist/error/index.d.ts +0 -4
  86. package/dist/error/index.d.ts.map +0 -1
  87. package/dist/error/index.js +0 -4
  88. package/dist/error/index.js.map +0 -1
  89. package/dist/factory/AbstractNamedProcessDetector.d.ts +0 -10
  90. package/dist/factory/AbstractNamedProcessDetector.d.ts.map +0 -1
  91. package/dist/factory/AbstractNamedProcessDetector.js +0 -18
  92. package/dist/factory/AbstractNamedProcessDetector.js.map +0 -1
  93. package/dist/factory/Factory.d.ts +0 -22
  94. package/dist/factory/Factory.d.ts.map +0 -1
  95. package/dist/factory/Factory.js +0 -42
  96. package/dist/factory/Factory.js.map +0 -1
  97. package/dist/factory/SingleProcessDetector.d.ts +0 -8
  98. package/dist/factory/SingleProcessDetector.d.ts.map +0 -1
  99. package/dist/factory/SingleProcessDetector.js +0 -10
  100. package/dist/factory/SingleProcessDetector.js.map +0 -1
  101. package/dist/factory/StatefulStateNameDetector.d.ts +0 -6
  102. package/dist/factory/StatefulStateNameDetector.d.ts.map +0 -1
  103. package/dist/factory/StatefulStateNameDetector.js +0 -15
  104. package/dist/factory/StatefulStateNameDetector.js.map +0 -1
  105. package/dist/factory/index.d.ts +0 -5
  106. package/dist/factory/index.d.ts.map +0 -1
  107. package/dist/factory/index.js +0 -5
  108. package/dist/factory/index.js.map +0 -1
  109. package/dist/filter/ActiveTransitionFilter.d.ts +0 -6
  110. package/dist/filter/ActiveTransitionFilter.d.ts.map +0 -1
  111. package/dist/filter/ActiveTransitionFilter.js +0 -12
  112. package/dist/filter/ActiveTransitionFilter.js.map +0 -1
  113. package/dist/filter/FilterStateByEvent.d.ts +0 -5
  114. package/dist/filter/FilterStateByEvent.d.ts.map +0 -1
  115. package/dist/filter/FilterStateByEvent.js +0 -10
  116. package/dist/filter/FilterStateByEvent.js.map +0 -1
  117. package/dist/filter/FilterStateByFinalState.d.ts +0 -5
  118. package/dist/filter/FilterStateByFinalState.d.ts.map +0 -1
  119. package/dist/filter/FilterStateByFinalState.js +0 -15
  120. package/dist/filter/FilterStateByFinalState.js.map +0 -1
  121. package/dist/filter/FilterStateByTransition.d.ts +0 -8
  122. package/dist/filter/FilterStateByTransition.d.ts.map +0 -1
  123. package/dist/filter/FilterStateByTransition.js +0 -16
  124. package/dist/filter/FilterStateByTransition.js.map +0 -1
  125. package/dist/filter/FilterTransitionByEvent.d.ts +0 -5
  126. package/dist/filter/FilterTransitionByEvent.d.ts.map +0 -1
  127. package/dist/filter/FilterTransitionByEvent.js +0 -10
  128. package/dist/filter/FilterTransitionByEvent.js.map +0 -1
  129. package/dist/filter/index.d.ts +0 -6
  130. package/dist/filter/index.d.ts.map +0 -1
  131. package/dist/filter/index.js +0 -6
  132. package/dist/filter/index.js.map +0 -1
  133. package/dist/graph/GraphBuilder.d.ts +0 -37
  134. package/dist/graph/GraphBuilder.d.ts.map +0 -1
  135. package/dist/graph/GraphBuilder.js +0 -132
  136. package/dist/graph/GraphBuilder.js.map +0 -1
  137. package/dist/graph/index.d.ts +0 -3
  138. package/dist/graph/index.d.ts.map +0 -1
  139. package/dist/graph/index.js +0 -2
  140. package/dist/graph/index.js.map +0 -1
  141. package/dist/index.d.ts.map +0 -1
  142. package/dist/interfaces/ConditionInterface.d.ts +0 -6
  143. package/dist/interfaces/ConditionInterface.d.ts.map +0 -1
  144. package/dist/interfaces/ConditionInterface.js +0 -2
  145. package/dist/interfaces/ConditionInterface.js.map +0 -1
  146. package/dist/interfaces/DispatcherInterface.d.ts +0 -11
  147. package/dist/interfaces/DispatcherInterface.d.ts.map +0 -1
  148. package/dist/interfaces/DispatcherInterface.js +0 -2
  149. package/dist/interfaces/DispatcherInterface.js.map +0 -1
  150. package/dist/interfaces/EventInterface.d.ts +0 -12
  151. package/dist/interfaces/EventInterface.d.ts.map +0 -1
  152. package/dist/interfaces/EventInterface.js +0 -2
  153. package/dist/interfaces/EventInterface.js.map +0 -1
  154. package/dist/interfaces/FactoryInterface.d.ts +0 -13
  155. package/dist/interfaces/FactoryInterface.d.ts.map +0 -1
  156. package/dist/interfaces/FactoryInterface.js +0 -2
  157. package/dist/interfaces/FactoryInterface.js.map +0 -1
  158. package/dist/interfaces/LastStateHasChangedDateInterface.d.ts +0 -4
  159. package/dist/interfaces/LastStateHasChangedDateInterface.d.ts.map +0 -1
  160. package/dist/interfaces/LastStateHasChangedDateInterface.js +0 -2
  161. package/dist/interfaces/LastStateHasChangedDateInterface.js.map +0 -1
  162. package/dist/interfaces/LockAdapterInterface.d.ts +0 -7
  163. package/dist/interfaces/LockAdapterInterface.d.ts.map +0 -1
  164. package/dist/interfaces/LockAdapterInterface.js +0 -2
  165. package/dist/interfaces/LockAdapterInterface.js.map +0 -1
  166. package/dist/interfaces/LoggerInterface.d.ts +0 -4
  167. package/dist/interfaces/LoggerInterface.d.ts.map +0 -1
  168. package/dist/interfaces/LoggerInterface.js +0 -2
  169. package/dist/interfaces/LoggerInterface.js.map +0 -1
  170. package/dist/interfaces/Metadata.d.ts +0 -4
  171. package/dist/interfaces/Metadata.d.ts.map +0 -1
  172. package/dist/interfaces/Metadata.js +0 -2
  173. package/dist/interfaces/Metadata.js.map +0 -1
  174. package/dist/interfaces/MutexFactoryInterface.d.ts +0 -6
  175. package/dist/interfaces/MutexFactoryInterface.d.ts.map +0 -1
  176. package/dist/interfaces/MutexFactoryInterface.js +0 -2
  177. package/dist/interfaces/MutexFactoryInterface.js.map +0 -1
  178. package/dist/interfaces/MutexInterface.d.ts +0 -8
  179. package/dist/interfaces/MutexInterface.d.ts.map +0 -1
  180. package/dist/interfaces/MutexInterface.js +0 -2
  181. package/dist/interfaces/MutexInterface.js.map +0 -1
  182. package/dist/interfaces/Named.d.ts +0 -4
  183. package/dist/interfaces/Named.d.ts.map +0 -1
  184. package/dist/interfaces/Named.js +0 -2
  185. package/dist/interfaces/Named.js.map +0 -1
  186. package/dist/interfaces/Observer.d.ts +0 -11
  187. package/dist/interfaces/Observer.d.ts.map +0 -1
  188. package/dist/interfaces/Observer.js +0 -2
  189. package/dist/interfaces/Observer.js.map +0 -1
  190. package/dist/interfaces/ProcessDetectorInterface.d.ts +0 -5
  191. package/dist/interfaces/ProcessDetectorInterface.d.ts.map +0 -1
  192. package/dist/interfaces/ProcessDetectorInterface.js +0 -2
  193. package/dist/interfaces/ProcessDetectorInterface.js.map +0 -1
  194. package/dist/interfaces/ProcessInterface.d.ts +0 -7
  195. package/dist/interfaces/ProcessInterface.d.ts.map +0 -1
  196. package/dist/interfaces/ProcessInterface.js +0 -2
  197. package/dist/interfaces/ProcessInterface.js.map +0 -1
  198. package/dist/interfaces/StateCollectionInterface.d.ts +0 -7
  199. package/dist/interfaces/StateCollectionInterface.d.ts.map +0 -1
  200. package/dist/interfaces/StateCollectionInterface.js +0 -2
  201. package/dist/interfaces/StateCollectionInterface.js.map +0 -1
  202. package/dist/interfaces/StateInterface.d.ts +0 -16
  203. package/dist/interfaces/StateInterface.d.ts.map +0 -1
  204. package/dist/interfaces/StateInterface.js +0 -2
  205. package/dist/interfaces/StateInterface.js.map +0 -1
  206. package/dist/interfaces/StateNameDetectorInterface.d.ts +0 -4
  207. package/dist/interfaces/StateNameDetectorInterface.d.ts.map +0 -1
  208. package/dist/interfaces/StateNameDetectorInterface.js +0 -2
  209. package/dist/interfaces/StateNameDetectorInterface.js.map +0 -1
  210. package/dist/interfaces/StatefulInterface.d.ts +0 -5
  211. package/dist/interfaces/StatefulInterface.d.ts.map +0 -1
  212. package/dist/interfaces/StatefulInterface.js +0 -2
  213. package/dist/interfaces/StatefulInterface.js.map +0 -1
  214. package/dist/interfaces/StatemachineInterface.d.ts +0 -20
  215. package/dist/interfaces/StatemachineInterface.d.ts.map +0 -1
  216. package/dist/interfaces/StatemachineInterface.js +0 -2
  217. package/dist/interfaces/StatemachineInterface.js.map +0 -1
  218. package/dist/interfaces/TransitionInterface.d.ts +0 -12
  219. package/dist/interfaces/TransitionInterface.d.ts.map +0 -1
  220. package/dist/interfaces/TransitionInterface.js +0 -2
  221. package/dist/interfaces/TransitionInterface.js.map +0 -1
  222. package/dist/interfaces/TransitionSelectorInterface.d.ts +0 -5
  223. package/dist/interfaces/TransitionSelectorInterface.d.ts.map +0 -1
  224. package/dist/interfaces/TransitionSelectorInterface.js +0 -2
  225. package/dist/interfaces/TransitionSelectorInterface.js.map +0 -1
  226. package/dist/interfaces/Weighted.d.ts +0 -4
  227. package/dist/interfaces/Weighted.d.ts.map +0 -1
  228. package/dist/interfaces/Weighted.js +0 -2
  229. package/dist/interfaces/Weighted.js.map +0 -1
  230. package/dist/interfaces/index.d.ts +0 -24
  231. package/dist/interfaces/index.d.ts.map +0 -1
  232. package/dist/interfaces/index.js +0 -2
  233. package/dist/interfaces/index.js.map +0 -1
  234. package/dist/mutex/LockAdapterMutex.d.ts +0 -13
  235. package/dist/mutex/LockAdapterMutex.d.ts.map +0 -1
  236. package/dist/mutex/LockAdapterMutex.js +0 -32
  237. package/dist/mutex/LockAdapterMutex.js.map +0 -1
  238. package/dist/mutex/MutexFactory.d.ts +0 -11
  239. package/dist/mutex/MutexFactory.d.ts.map +0 -1
  240. package/dist/mutex/MutexFactory.js +0 -13
  241. package/dist/mutex/MutexFactory.js.map +0 -1
  242. package/dist/mutex/NullMutex.d.ts +0 -9
  243. package/dist/mutex/NullMutex.d.ts.map +0 -1
  244. package/dist/mutex/NullMutex.js +0 -18
  245. package/dist/mutex/NullMutex.js.map +0 -1
  246. package/dist/mutex/index.d.ts +0 -5
  247. package/dist/mutex/index.d.ts.map +0 -1
  248. package/dist/mutex/index.js +0 -4
  249. package/dist/mutex/index.js.map +0 -1
  250. package/dist/observer/CallbackObserver.d.ts +0 -8
  251. package/dist/observer/CallbackObserver.d.ts.map +0 -1
  252. package/dist/observer/CallbackObserver.js +0 -14
  253. package/dist/observer/CallbackObserver.js.map +0 -1
  254. package/dist/observer/OnEnterObserver.d.ts +0 -8
  255. package/dist/observer/OnEnterObserver.d.ts.map +0 -1
  256. package/dist/observer/OnEnterObserver.js +0 -28
  257. package/dist/observer/OnEnterObserver.js.map +0 -1
  258. package/dist/observer/StatefulStatusChanger.d.ts +0 -5
  259. package/dist/observer/StatefulStatusChanger.d.ts.map +0 -1
  260. package/dist/observer/StatefulStatusChanger.js +0 -24
  261. package/dist/observer/StatefulStatusChanger.js.map +0 -1
  262. package/dist/observer/TransitionLogger.d.ts +0 -9
  263. package/dist/observer/TransitionLogger.d.ts.map +0 -1
  264. package/dist/observer/TransitionLogger.js +0 -62
  265. package/dist/observer/TransitionLogger.js.map +0 -1
  266. package/dist/observer/index.d.ts +0 -5
  267. package/dist/observer/index.d.ts.map +0 -1
  268. package/dist/observer/index.js +0 -5
  269. package/dist/observer/index.js.map +0 -1
  270. package/dist/selector/OneOrNoneActiveTransition.d.ts +0 -6
  271. package/dist/selector/OneOrNoneActiveTransition.d.ts.map +0 -1
  272. package/dist/selector/OneOrNoneActiveTransition.js +0 -14
  273. package/dist/selector/OneOrNoneActiveTransition.js.map +0 -1
  274. package/dist/selector/ScoreTransition.d.ts +0 -9
  275. package/dist/selector/ScoreTransition.d.ts.map +0 -1
  276. package/dist/selector/ScoreTransition.js +0 -34
  277. package/dist/selector/ScoreTransition.js.map +0 -1
  278. package/dist/selector/WeightTransition.d.ts +0 -9
  279. package/dist/selector/WeightTransition.d.ts.map +0 -1
  280. package/dist/selector/WeightTransition.js +0 -27
  281. package/dist/selector/WeightTransition.js.map +0 -1
  282. package/dist/selector/index.d.ts +0 -4
  283. package/dist/selector/index.d.ts.map +0 -1
  284. package/dist/selector/index.js +0 -4
  285. package/dist/selector/index.js.map +0 -1
  286. package/dist/util/SetupHelper.d.ts +0 -17
  287. package/dist/util/SetupHelper.d.ts.map +0 -1
  288. package/dist/util/SetupHelper.js +0 -48
  289. package/dist/util/SetupHelper.js.map +0 -1
  290. package/dist/util/StateCollectionMerger.d.ts +0 -23
  291. package/dist/util/StateCollectionMerger.d.ts.map +0 -1
  292. package/dist/util/StateCollectionMerger.js +0 -83
  293. package/dist/util/StateCollectionMerger.js.map +0 -1
  294. package/dist/util/index.d.ts +0 -3
  295. package/dist/util/index.d.ts.map +0 -1
  296. package/dist/util/index.js +0 -3
  297. package/dist/util/index.js.map +0 -1
package/dist/index.cjs ADDED
@@ -0,0 +1,1422 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ AbstractNamedProcessDetector: () => AbstractNamedProcessDetector,
24
+ ActiveTransitionFilter: () => ActiveTransitionFilter,
25
+ AndComposite: () => AndComposite,
26
+ CallbackCondition: () => CallbackCondition,
27
+ CallbackObserver: () => CallbackObserver,
28
+ Contradiction: () => Contradiction,
29
+ Dispatcher: () => Dispatcher,
30
+ DuplicateStateError: () => DuplicateStateError,
31
+ Event: () => Event,
32
+ Factory: () => Factory,
33
+ FilterStateByEvent: () => FilterStateByEvent,
34
+ FilterStateByFinalState: () => FilterStateByFinalState,
35
+ FilterStateByTransition: () => FilterStateByTransition,
36
+ FilterTransitionByEvent: () => FilterTransitionByEvent,
37
+ GraphBuilder: () => GraphBuilder,
38
+ LockAdapterMutex: () => LockAdapterMutex,
39
+ LockCanNotBeAcquiredError: () => LockCanNotBeAcquiredError,
40
+ MutexFactory: () => MutexFactory,
41
+ Not: () => Not,
42
+ NullMutex: () => NullMutex,
43
+ OnEnterObserver: () => OnEnterObserver,
44
+ OneOrNoneActiveTransition: () => OneOrNoneActiveTransition,
45
+ OrComposite: () => OrComposite,
46
+ Process: () => Process,
47
+ ScoreTransition: () => ScoreTransition,
48
+ SetupHelper: () => SetupHelper,
49
+ SingleProcessDetector: () => SingleProcessDetector,
50
+ State: () => State,
51
+ StateCollection: () => StateCollection,
52
+ StateCollectionMerger: () => StateCollectionMerger,
53
+ StatefulStateNameDetector: () => StatefulStateNameDetector,
54
+ StatefulStatusChanger: () => StatefulStatusChanger,
55
+ Statemachine: () => Statemachine,
56
+ Tautology: () => Tautology,
57
+ Timeout: () => Timeout,
58
+ Transition: () => Transition,
59
+ TransitionLogger: () => TransitionLogger,
60
+ WeightTransition: () => WeightTransition,
61
+ WrongEventForStateError: () => WrongEventForStateError
62
+ });
63
+ module.exports = __toCommonJS(index_exports);
64
+
65
+ // src/Event.ts
66
+ var Event = class {
67
+ name;
68
+ observers = /* @__PURE__ */ new Set();
69
+ metadata = /* @__PURE__ */ new Map();
70
+ invokeArgs = [];
71
+ constructor(name) {
72
+ this.name = name;
73
+ }
74
+ getName() {
75
+ return this.name;
76
+ }
77
+ getInvokeArgs() {
78
+ return this.invokeArgs;
79
+ }
80
+ async invoke(...args) {
81
+ this.invokeArgs = args;
82
+ try {
83
+ await this.notify();
84
+ } finally {
85
+ this.invokeArgs = [];
86
+ }
87
+ }
88
+ attach(observer) {
89
+ this.observers.add(observer);
90
+ }
91
+ detach(observer) {
92
+ this.observers.delete(observer);
93
+ }
94
+ async notify() {
95
+ for (const observer of this.observers) {
96
+ await observer.update(this);
97
+ }
98
+ }
99
+ getObservers() {
100
+ return this.observers;
101
+ }
102
+ getMetadata() {
103
+ return Object.fromEntries(this.metadata);
104
+ }
105
+ getMetadataValue(key) {
106
+ return this.metadata.get(key);
107
+ }
108
+ setMetadataValue(key, value) {
109
+ this.metadata.set(key, value);
110
+ }
111
+ hasMetadataValue(key) {
112
+ return this.metadata.has(key);
113
+ }
114
+ deleteMetadataValue(key) {
115
+ this.metadata.delete(key);
116
+ }
117
+ };
118
+
119
+ // src/State.ts
120
+ var State = class {
121
+ name;
122
+ transitions = /* @__PURE__ */ new Set();
123
+ events = /* @__PURE__ */ new Map();
124
+ metadata = /* @__PURE__ */ new Map();
125
+ constructor(name) {
126
+ this.name = name;
127
+ }
128
+ getName() {
129
+ return this.name;
130
+ }
131
+ getTransitions() {
132
+ return this.transitions;
133
+ }
134
+ addTransition(transition) {
135
+ if (this.transitions.has(transition)) {
136
+ return;
137
+ }
138
+ const targetName = transition.getTargetState().getName();
139
+ const eventName = transition.getEventName();
140
+ const conditionName = transition.getConditionName();
141
+ for (const existing of this.transitions) {
142
+ if (existing.getTargetState().getName() === targetName && existing.getEventName() === eventName && existing.getConditionName() === conditionName) {
143
+ return;
144
+ }
145
+ }
146
+ this.transitions.add(transition);
147
+ if (eventName) {
148
+ this.getEvent(eventName);
149
+ }
150
+ }
151
+ getEventNames() {
152
+ return Array.from(this.events.keys());
153
+ }
154
+ hasEvent(name) {
155
+ return this.events.has(name);
156
+ }
157
+ getEvent(name) {
158
+ let event = this.events.get(name);
159
+ if (!event) {
160
+ event = new Event(name);
161
+ this.events.set(name, event);
162
+ }
163
+ return event;
164
+ }
165
+ getMetadata() {
166
+ return Object.fromEntries(this.metadata);
167
+ }
168
+ getMetadataValue(key) {
169
+ return this.metadata.get(key);
170
+ }
171
+ setMetadataValue(key, value) {
172
+ this.metadata.set(key, value);
173
+ }
174
+ hasMetadataValue(key) {
175
+ return this.metadata.has(key);
176
+ }
177
+ deleteMetadataValue(key) {
178
+ this.metadata.delete(key);
179
+ }
180
+ };
181
+
182
+ // src/Transition.ts
183
+ var Transition = class {
184
+ targetState;
185
+ eventName;
186
+ condition;
187
+ weight = 1;
188
+ constructor(targetState, eventName = null, condition = null) {
189
+ this.targetState = targetState;
190
+ this.eventName = eventName;
191
+ this.condition = condition;
192
+ }
193
+ getTargetState() {
194
+ return this.targetState;
195
+ }
196
+ getEventName() {
197
+ return this.eventName;
198
+ }
199
+ getConditionName() {
200
+ if (this.condition) {
201
+ return this.condition.getName();
202
+ }
203
+ return null;
204
+ }
205
+ getCondition() {
206
+ return this.condition;
207
+ }
208
+ async isActive(subject, context, event) {
209
+ let result;
210
+ if (event) {
211
+ result = event.getName() === this.eventName;
212
+ } else {
213
+ result = this.eventName === null;
214
+ }
215
+ if (this.condition && result) {
216
+ result = await this.condition.checkCondition(subject, context);
217
+ }
218
+ return result;
219
+ }
220
+ getWeight() {
221
+ return this.weight;
222
+ }
223
+ setWeight(weight) {
224
+ this.weight = weight;
225
+ }
226
+ };
227
+
228
+ // src/util/StateCollectionMerger.ts
229
+ var StateCollectionMerger = class {
230
+ targetCollection;
231
+ stateNamePrefix = "";
232
+ constructor(targetCollection) {
233
+ this.targetCollection = targetCollection;
234
+ }
235
+ getStateNamePrefix() {
236
+ return this.stateNamePrefix;
237
+ }
238
+ setStateNamePrefix(prefix) {
239
+ this.stateNamePrefix = prefix;
240
+ }
241
+ getTargetCollection() {
242
+ return this.targetCollection;
243
+ }
244
+ createState(name) {
245
+ return new State(name);
246
+ }
247
+ findOrCreateState(name) {
248
+ const prefixedName = this.stateNamePrefix + name;
249
+ if (this.targetCollection.hasState(prefixedName)) {
250
+ return this.targetCollection.getState(prefixedName);
251
+ }
252
+ const state = this.createState(prefixedName);
253
+ this.targetCollection.addState(state);
254
+ return state;
255
+ }
256
+ createCondition(sourceTransition) {
257
+ return sourceTransition.getCondition();
258
+ }
259
+ createTransition(sourceTransition) {
260
+ const targetStateName = sourceTransition.getTargetState().getName();
261
+ const targetState = this.findOrCreateState(targetStateName);
262
+ this.mergeMetadata(sourceTransition.getTargetState(), targetState);
263
+ const eventName = sourceTransition.getEventName();
264
+ const condition = this.createCondition(sourceTransition);
265
+ const transition = new Transition(targetState, eventName, condition);
266
+ transition.setWeight(sourceTransition.getWeight());
267
+ return transition;
268
+ }
269
+ mergeMetadata(source, target) {
270
+ const metadata = source.getMetadata();
271
+ for (const [key, value] of Object.entries(metadata)) {
272
+ target.setMetadataValue(key, value);
273
+ }
274
+ }
275
+ mergeEvent(source, target, eventName) {
276
+ const sourceEvent = source.getEvent(eventName);
277
+ const targetEvent = target.getEvent(eventName);
278
+ const sourceMetadata = sourceEvent.getMetadata();
279
+ for (const [key, value] of Object.entries(sourceMetadata)) {
280
+ targetEvent.setMetadataValue(key, value);
281
+ }
282
+ for (const observer of sourceEvent.getObservers()) {
283
+ targetEvent.attach(observer);
284
+ }
285
+ }
286
+ mergeState(sourceState) {
287
+ const targetState = this.findOrCreateState(sourceState.getName());
288
+ this.mergeMetadata(sourceState, targetState);
289
+ for (const sourceTransition of sourceState.getTransitions()) {
290
+ const targetTransition = this.createTransition(sourceTransition);
291
+ targetState.addTransition(targetTransition);
292
+ }
293
+ for (const eventName of sourceState.getEventNames()) {
294
+ this.mergeEvent(sourceState, targetState, eventName);
295
+ }
296
+ }
297
+ merge(source) {
298
+ if ("getStates" in source && typeof source.getStates === "function") {
299
+ const collection = source;
300
+ for (const state of collection.getStates()) {
301
+ this.mergeState(state);
302
+ }
303
+ } else {
304
+ this.mergeState(source);
305
+ }
306
+ }
307
+ };
308
+
309
+ // src/error/DuplicateStateError.ts
310
+ var DuplicateStateError = class extends Error {
311
+ stateName;
312
+ constructor(stateName) {
313
+ super(
314
+ `There is already a different state with name "${stateName}" in this collection`
315
+ );
316
+ this.name = "DuplicateStateError";
317
+ this.stateName = stateName;
318
+ }
319
+ };
320
+
321
+ // src/StateCollection.ts
322
+ var StateCollection = class {
323
+ states = /* @__PURE__ */ new Map();
324
+ stateCollectionMerger = null;
325
+ getState(name) {
326
+ const state = this.states.get(name);
327
+ if (!state) {
328
+ throw new Error(`State "${name}" not found`);
329
+ }
330
+ return state;
331
+ }
332
+ getStates() {
333
+ return this.states.values();
334
+ }
335
+ hasState(name) {
336
+ return this.states.has(name);
337
+ }
338
+ addState(state) {
339
+ const existing = this.states.get(state.getName());
340
+ if (existing && existing !== state) {
341
+ throw new DuplicateStateError(state.getName());
342
+ }
343
+ this.states.set(state.getName(), state);
344
+ }
345
+ getStateCollectionMerger() {
346
+ if (!this.stateCollectionMerger) {
347
+ this.stateCollectionMerger = new StateCollectionMerger(this);
348
+ }
349
+ return this.stateCollectionMerger;
350
+ }
351
+ merge(source) {
352
+ const merger = this.getStateCollectionMerger();
353
+ merger.merge(source);
354
+ }
355
+ };
356
+
357
+ // src/Process.ts
358
+ var Process = class {
359
+ name;
360
+ initialState;
361
+ states;
362
+ constructor(name, initialState) {
363
+ this.name = name;
364
+ this.initialState = initialState;
365
+ this.states = new StateCollection();
366
+ this.registerState(initialState);
367
+ }
368
+ registerState(state) {
369
+ const name = state.getName();
370
+ if (this.states.hasState(name)) {
371
+ if (this.states.getState(name) !== state) {
372
+ throw new DuplicateStateError(name);
373
+ }
374
+ return;
375
+ }
376
+ this.states.addState(state);
377
+ for (const transition of state.getTransitions()) {
378
+ const targetState = transition.getTargetState();
379
+ this.registerState(targetState);
380
+ }
381
+ }
382
+ getName() {
383
+ return this.name;
384
+ }
385
+ getInitialState() {
386
+ return this.initialState;
387
+ }
388
+ getStates() {
389
+ return this.states.getStates();
390
+ }
391
+ getState(name) {
392
+ return this.states.getState(name);
393
+ }
394
+ hasState(name) {
395
+ return this.states.hasState(name);
396
+ }
397
+ };
398
+
399
+ // src/selector/OneOrNoneActiveTransition.ts
400
+ var OneOrNoneActiveTransition = class {
401
+ selectTransition(transitions) {
402
+ const arr = Array.from(transitions);
403
+ switch (arr.length) {
404
+ case 0:
405
+ return null;
406
+ case 1:
407
+ return arr[0];
408
+ default:
409
+ throw new Error("More than one transition is active!");
410
+ }
411
+ }
412
+ };
413
+
414
+ // src/mutex/NullMutex.ts
415
+ var NullMutex = class {
416
+ acquired = false;
417
+ acquireLock() {
418
+ this.acquired = true;
419
+ return true;
420
+ }
421
+ releaseLock() {
422
+ this.acquired = false;
423
+ return true;
424
+ }
425
+ isAcquired() {
426
+ return this.acquired;
427
+ }
428
+ isLocked() {
429
+ return false;
430
+ }
431
+ };
432
+
433
+ // src/Dispatcher.ts
434
+ var Dispatcher = class {
435
+ commands = [];
436
+ onReadyCallbacks = [];
437
+ ready = false;
438
+ dispatch(event, args = [], onReadyCallback) {
439
+ if (this.ready) {
440
+ throw new Error("Was already invoked!");
441
+ }
442
+ this.commands.push({ event, args });
443
+ if (onReadyCallback) {
444
+ this.onReadyCallbacks.push(onReadyCallback);
445
+ }
446
+ }
447
+ async invoke() {
448
+ if (this.ready) {
449
+ throw new Error("Was already invoked!");
450
+ }
451
+ for (const { event, args } of this.commands) {
452
+ await event.invoke(...args);
453
+ }
454
+ this.ready = true;
455
+ for (const callback of this.onReadyCallbacks) {
456
+ await callback.invoke();
457
+ }
458
+ }
459
+ isReady() {
460
+ return this.ready;
461
+ }
462
+ };
463
+
464
+ // src/filter/ActiveTransitionFilter.ts
465
+ var ActiveTransitionFilter = class {
466
+ static async filter(transitions, subject, context, event) {
467
+ const active = [];
468
+ for (const transition of transitions) {
469
+ if (await transition.isActive(subject, context, event)) {
470
+ active.push(transition);
471
+ }
472
+ }
473
+ return active;
474
+ }
475
+ };
476
+
477
+ // src/error/WrongEventForStateError.ts
478
+ var WrongEventForStateError = class extends Error {
479
+ stateName;
480
+ eventName;
481
+ constructor(stateName, eventName) {
482
+ super(`Current state "${stateName}" doesn't have event "${eventName}"`);
483
+ this.name = "WrongEventForStateError";
484
+ this.stateName = stateName;
485
+ this.eventName = eventName;
486
+ }
487
+ };
488
+
489
+ // src/error/LockCanNotBeAcquiredError.ts
490
+ var LockCanNotBeAcquiredError = class extends Error {
491
+ constructor(message = "Lock can not be acquired!") {
492
+ super(message);
493
+ this.name = "LockCanNotBeAcquiredError";
494
+ }
495
+ };
496
+
497
+ // src/Statemachine.ts
498
+ var Statemachine = class {
499
+ subject;
500
+ currentState;
501
+ lastState = null;
502
+ transitionSelector;
503
+ selectedTransition = null;
504
+ process;
505
+ mutex;
506
+ autoreleaseLock = true;
507
+ dispatcher = null;
508
+ currentEvent = null;
509
+ currentContext = null;
510
+ observers = /* @__PURE__ */ new Set();
511
+ constructor(subject, process, stateName, transitionSelector, mutex) {
512
+ this.subject = subject;
513
+ if (stateName) {
514
+ this.currentState = process.getState(stateName);
515
+ } else {
516
+ this.currentState = process.getInitialState();
517
+ }
518
+ this.transitionSelector = transitionSelector ?? new OneOrNoneActiveTransition();
519
+ this.process = process;
520
+ this.mutex = mutex ?? new NullMutex();
521
+ }
522
+ getProcess() {
523
+ return this.process;
524
+ }
525
+ getCurrentState() {
526
+ return this.currentState;
527
+ }
528
+ getLastState() {
529
+ return this.lastState;
530
+ }
531
+ getSubject() {
532
+ return this.subject;
533
+ }
534
+ getSelectedTransition() {
535
+ return this.selectedTransition;
536
+ }
537
+ getCurrentContext() {
538
+ return this.currentContext;
539
+ }
540
+ async doCheckTransitions(context, event, automaticVisited) {
541
+ try {
542
+ const transitions = this.currentState.getTransitions();
543
+ const activeTransitions = await ActiveTransitionFilter.filter(
544
+ transitions,
545
+ this.subject,
546
+ context,
547
+ event
548
+ );
549
+ this.selectedTransition = this.transitionSelector.selectTransition(activeTransitions);
550
+ if (this.selectedTransition) {
551
+ const targetState = this.selectedTransition.getTargetState();
552
+ if (this.selectedTransition.getEventName() === null) {
553
+ if (!automaticVisited) {
554
+ automaticVisited = /* @__PURE__ */ new Set();
555
+ }
556
+ automaticVisited.add(this.currentState);
557
+ if (automaticVisited.has(targetState)) {
558
+ throw new Error(
559
+ `Automatic transition cycle detected: state "${targetState.getName()}" was already visited \u2014 this would cause infinite recursion`
560
+ );
561
+ }
562
+ }
563
+ if (this.currentState !== targetState) {
564
+ this.lastState = this.currentState;
565
+ this.currentState = targetState;
566
+ this.currentContext = context;
567
+ this.currentEvent = event ?? null;
568
+ try {
569
+ await this.notify();
570
+ } finally {
571
+ this.currentContext = null;
572
+ this.currentEvent = null;
573
+ this.selectedTransition = null;
574
+ this.lastState = null;
575
+ }
576
+ }
577
+ await this.doCheckTransitions(context, void 0, automaticVisited);
578
+ }
579
+ } catch (error) {
580
+ let message = `Exception was thrown when doing a transition from current state "${this.currentState.getName()}"`;
581
+ if (this.currentEvent) {
582
+ message += ` with event "${this.currentEvent.getName()}"`;
583
+ }
584
+ const named = this.subject;
585
+ if (named && typeof named.getName === "function") {
586
+ message += ` for "${named.getName()}"`;
587
+ }
588
+ throw new Error(message, { cause: error });
589
+ }
590
+ }
591
+ async onDispatcherReady() {
592
+ if (this.dispatcher && this.dispatcher.isReady()) {
593
+ const context = this.currentContext;
594
+ const event = this.currentEvent ?? void 0;
595
+ this.dispatcher = null;
596
+ this.currentContext = null;
597
+ this.currentEvent = null;
598
+ try {
599
+ await this.doCheckTransitions(context, event);
600
+ } finally {
601
+ if (this.autoreleaseLock && this.isLockAcquired()) {
602
+ await this.releaseLock();
603
+ }
604
+ }
605
+ }
606
+ }
607
+ async dispatchEvent(dispatcher, name, context) {
608
+ if (this.dispatcher) {
609
+ throw new Error("Event dispatching is still running!");
610
+ }
611
+ if (this.currentState.hasEvent(name)) {
612
+ await this.acquireLockOrThrowException();
613
+ try {
614
+ this.dispatcher = dispatcher;
615
+ this.currentContext = context ?? /* @__PURE__ */ new Map();
616
+ this.currentEvent = this.currentState.getEvent(name);
617
+ dispatcher.dispatch(
618
+ this.currentEvent,
619
+ [this.subject, this.currentContext],
620
+ { invoke: () => this.onDispatcherReady() }
621
+ );
622
+ } catch (error) {
623
+ this.dispatcher = null;
624
+ this.currentContext = null;
625
+ this.currentEvent = null;
626
+ if (this.autoreleaseLock) {
627
+ await this.releaseLock();
628
+ }
629
+ throw error;
630
+ }
631
+ } else {
632
+ throw new WrongEventForStateError(this.currentState.getName(), name);
633
+ }
634
+ }
635
+ async triggerEvent(name, context) {
636
+ const dispatcher = new Dispatcher();
637
+ try {
638
+ await this.dispatchEvent(dispatcher, name, context);
639
+ await dispatcher.invoke();
640
+ } finally {
641
+ this.dispatcher = null;
642
+ this.currentContext = null;
643
+ this.currentEvent = null;
644
+ if (this.autoreleaseLock && this.isLockAcquired()) {
645
+ await this.releaseLock();
646
+ }
647
+ }
648
+ }
649
+ async checkTransitions(context) {
650
+ await this.acquireLockOrThrowException();
651
+ const ctx = context ?? /* @__PURE__ */ new Map();
652
+ try {
653
+ await this.doCheckTransitions(ctx);
654
+ } finally {
655
+ if (this.autoreleaseLock && this.isLockAcquired()) {
656
+ await this.releaseLock();
657
+ }
658
+ }
659
+ }
660
+ async acquireLockOrThrowException() {
661
+ if (!await this.acquireLock()) {
662
+ throw new LockCanNotBeAcquiredError("Lock can not be acquired!");
663
+ }
664
+ }
665
+ isAutoreleaseLock() {
666
+ return this.autoreleaseLock;
667
+ }
668
+ setAutoreleaseLock(autorelease) {
669
+ this.autoreleaseLock = autorelease;
670
+ }
671
+ async acquireLock() {
672
+ if (this.mutex.isAcquired()) {
673
+ return true;
674
+ }
675
+ return this.mutex.acquireLock();
676
+ }
677
+ async releaseLock() {
678
+ await this.mutex.releaseLock();
679
+ }
680
+ isLockAcquired() {
681
+ return this.mutex.isAcquired();
682
+ }
683
+ attach(observer) {
684
+ this.observers.add(observer);
685
+ }
686
+ detach(observer) {
687
+ this.observers.delete(observer);
688
+ }
689
+ async notify() {
690
+ for (const observer of this.observers) {
691
+ await observer.update(this);
692
+ }
693
+ }
694
+ getObservers() {
695
+ return this.observers;
696
+ }
697
+ };
698
+
699
+ // src/condition/Tautology.ts
700
+ var Tautology = class {
701
+ name;
702
+ constructor(name = "Tautology") {
703
+ this.name = name;
704
+ }
705
+ getName() {
706
+ return this.name;
707
+ }
708
+ checkCondition(_subject, _context) {
709
+ return true;
710
+ }
711
+ };
712
+
713
+ // src/condition/Contradiction.ts
714
+ var Contradiction = class {
715
+ name;
716
+ constructor(name = "Contradiction") {
717
+ this.name = name;
718
+ }
719
+ getName() {
720
+ return this.name;
721
+ }
722
+ checkCondition(_subject, _context) {
723
+ return false;
724
+ }
725
+ };
726
+
727
+ // src/condition/CallbackCondition.ts
728
+ var CallbackCondition = class {
729
+ name;
730
+ callable;
731
+ constructor(name, callable) {
732
+ this.name = name;
733
+ this.callable = callable;
734
+ }
735
+ getName() {
736
+ return this.name;
737
+ }
738
+ checkCondition(subject, context) {
739
+ return this.callable(subject, context);
740
+ }
741
+ };
742
+
743
+ // src/condition/Timeout.ts
744
+ function isLastStateHasChangedDate(obj) {
745
+ return typeof obj === "object" && obj !== null && "getLastStateHasChangedDate" in obj && typeof obj.getLastStateHasChangedDate === "function";
746
+ }
747
+ var Timeout = class {
748
+ timeoutMs;
749
+ label;
750
+ constructor(timeoutMs, label) {
751
+ this.timeoutMs = timeoutMs;
752
+ this.label = label ?? `${timeoutMs}ms`;
753
+ }
754
+ getName() {
755
+ return `Timeout: ${this.label}`;
756
+ }
757
+ getLastStateHasChangedDate(subject, _context) {
758
+ if (isLastStateHasChangedDate(subject)) {
759
+ return subject.getLastStateHasChangedDate();
760
+ }
761
+ throw new Error("Subject must implement LastStateHasChangedDateInterface");
762
+ }
763
+ checkCondition(subject, context) {
764
+ const date = new Date(
765
+ this.getLastStateHasChangedDate(subject, context).getTime()
766
+ );
767
+ date.setTime(date.getTime() + this.timeoutMs);
768
+ return date <= /* @__PURE__ */ new Date();
769
+ }
770
+ };
771
+
772
+ // src/condition/AndComposite.ts
773
+ var AndComposite = class {
774
+ conditions = [];
775
+ constructor(condition) {
776
+ this.conditions.push(condition);
777
+ }
778
+ addAnd(condition) {
779
+ this.conditions.push(condition);
780
+ return this;
781
+ }
782
+ getName() {
783
+ const names = this.conditions.map((c) => c.getName());
784
+ return `(${names.join(" and ")})`;
785
+ }
786
+ async checkCondition(subject, context) {
787
+ for (const condition of this.conditions) {
788
+ if (!await condition.checkCondition(subject, context)) {
789
+ return false;
790
+ }
791
+ }
792
+ return true;
793
+ }
794
+ };
795
+
796
+ // src/condition/OrComposite.ts
797
+ var OrComposite = class {
798
+ conditions = [];
799
+ constructor(condition) {
800
+ this.conditions.push(condition);
801
+ }
802
+ addOr(condition) {
803
+ this.conditions.push(condition);
804
+ return this;
805
+ }
806
+ getName() {
807
+ const names = this.conditions.map((c) => c.getName());
808
+ return `(${names.join(" or ")})`;
809
+ }
810
+ async checkCondition(subject, context) {
811
+ for (const condition of this.conditions) {
812
+ if (await condition.checkCondition(subject, context)) {
813
+ return true;
814
+ }
815
+ }
816
+ return false;
817
+ }
818
+ };
819
+
820
+ // src/condition/Not.ts
821
+ var Not = class {
822
+ condition;
823
+ constructor(condition) {
824
+ this.condition = condition;
825
+ }
826
+ getName() {
827
+ return `not ( ${this.condition.getName()} )`;
828
+ }
829
+ async checkCondition(subject, context) {
830
+ return !await this.condition.checkCondition(subject, context);
831
+ }
832
+ };
833
+
834
+ // src/observer/CallbackObserver.ts
835
+ var CallbackObserver = class {
836
+ callback;
837
+ constructor(callback) {
838
+ this.callback = callback;
839
+ }
840
+ update(subject) {
841
+ const event = subject;
842
+ if (typeof event.getInvokeArgs === "function") {
843
+ return this.callback(...event.getInvokeArgs());
844
+ }
845
+ return this.callback(subject);
846
+ }
847
+ };
848
+
849
+ // src/observer/StatefulStatusChanger.ts
850
+ function isStatemachine(obj) {
851
+ return typeof obj === "object" && obj !== null && "getCurrentState" in obj && "getSubject" in obj;
852
+ }
853
+ function isStateful(obj) {
854
+ return typeof obj === "object" && obj !== null && "setCurrentStateName" in obj && typeof obj.setCurrentStateName === "function";
855
+ }
856
+ var StatefulStatusChanger = class {
857
+ update(subject) {
858
+ if (isStatemachine(subject)) {
859
+ const subjectObj = subject.getSubject();
860
+ if (isStateful(subjectObj)) {
861
+ const stateName = subject.getCurrentState().getName();
862
+ subjectObj.setCurrentStateName(stateName);
863
+ }
864
+ }
865
+ }
866
+ };
867
+
868
+ // src/observer/OnEnterObserver.ts
869
+ function isStatemachine2(obj) {
870
+ return typeof obj === "object" && obj !== null && "getCurrentState" in obj && "triggerEvent" in obj;
871
+ }
872
+ var OnEnterObserver = class _OnEnterObserver {
873
+ static DEFAULT_EVENT_NAME = "onEnter";
874
+ eventName;
875
+ constructor(eventName = _OnEnterObserver.DEFAULT_EVENT_NAME) {
876
+ this.eventName = eventName;
877
+ }
878
+ async update(subject) {
879
+ if (isStatemachine2(subject) && subject.getCurrentState().hasEvent(this.eventName)) {
880
+ const sm = subject;
881
+ const autorelease = sm.isAutoreleaseLock();
882
+ sm.setAutoreleaseLock(false);
883
+ try {
884
+ await sm.triggerEvent(
885
+ this.eventName,
886
+ sm.getCurrentContext() ?? void 0
887
+ );
888
+ } finally {
889
+ sm.setAutoreleaseLock(autorelease);
890
+ }
891
+ }
892
+ }
893
+ };
894
+
895
+ // src/observer/TransitionLogger.ts
896
+ function isStatemachine3(obj) {
897
+ return typeof obj === "object" && obj !== null && "getCurrentState" in obj && "getSubject" in obj;
898
+ }
899
+ function isNamed(obj) {
900
+ return typeof obj === "object" && obj !== null && "getName" in obj && typeof obj.getName === "function";
901
+ }
902
+ function convertToString(obj) {
903
+ if (isNamed(obj)) {
904
+ return obj.getName();
905
+ }
906
+ return String(obj);
907
+ }
908
+ var TransitionLogger = class {
909
+ logger;
910
+ loggerLevel;
911
+ constructor(logger, loggerLevel = "info") {
912
+ this.logger = logger;
913
+ this.loggerLevel = loggerLevel;
914
+ }
915
+ update(subject) {
916
+ if (!isStatemachine3(subject)) {
917
+ return;
918
+ }
919
+ const context = {};
920
+ context["subject"] = subject.getSubject();
921
+ context["currentState"] = subject.getCurrentState();
922
+ context["lastState"] = subject.getLastState();
923
+ context["transition"] = subject.getSelectedTransition();
924
+ let message = "Transition";
925
+ if (context["subject"] != null) {
926
+ message += ` for "${convertToString(context["subject"])}"`;
927
+ }
928
+ if (context["lastState"] != null) {
929
+ message += ` from "${convertToString(context["lastState"])}"`;
930
+ }
931
+ if (context["currentState"] != null) {
932
+ message += ` to "${convertToString(context["currentState"])}"`;
933
+ }
934
+ const transition = context["transition"];
935
+ if (transition && typeof transition.getEventName === "function") {
936
+ const eventName = transition.getEventName();
937
+ const condition = transition.getConditionName?.();
938
+ if (eventName || condition) {
939
+ message += " with";
940
+ if (eventName) {
941
+ message += ` event "${eventName}"`;
942
+ }
943
+ if (condition) {
944
+ message += ` condition "${condition}"`;
945
+ }
946
+ }
947
+ }
948
+ this.logger.log(this.loggerLevel, message, context);
949
+ }
950
+ };
951
+
952
+ // src/filter/FilterStateByEvent.ts
953
+ var FilterStateByEvent = class {
954
+ static *filter(states, eventName) {
955
+ for (const state of states) {
956
+ if (state.hasEvent(eventName)) {
957
+ yield state;
958
+ }
959
+ }
960
+ }
961
+ };
962
+
963
+ // src/filter/FilterStateByTransition.ts
964
+ var FilterStateByTransition = class {
965
+ static *filter(states) {
966
+ for (const state of states) {
967
+ for (const transition of state.getTransitions()) {
968
+ if (!transition.getEventName()) {
969
+ yield state;
970
+ break;
971
+ }
972
+ }
973
+ }
974
+ }
975
+ };
976
+
977
+ // src/filter/FilterStateByFinalState.ts
978
+ var FilterStateByFinalState = class {
979
+ static *filter(states) {
980
+ for (const state of states) {
981
+ let count = 0;
982
+ for (const _transition of state.getTransitions()) {
983
+ count++;
984
+ break;
985
+ }
986
+ if (count === 0) {
987
+ yield state;
988
+ }
989
+ }
990
+ }
991
+ };
992
+
993
+ // src/filter/FilterTransitionByEvent.ts
994
+ var FilterTransitionByEvent = class {
995
+ static *filter(transitions, eventName) {
996
+ for (const transition of transitions) {
997
+ if (transition.getEventName() === eventName) {
998
+ yield transition;
999
+ }
1000
+ }
1001
+ }
1002
+ };
1003
+
1004
+ // src/selector/ScoreTransition.ts
1005
+ var ScoreTransition = class {
1006
+ innerSelector;
1007
+ constructor(innerSelector) {
1008
+ this.innerSelector = innerSelector ?? new OneOrNoneActiveTransition();
1009
+ }
1010
+ calculateScore(transition) {
1011
+ let score = 0;
1012
+ if (transition.getEventName()) {
1013
+ score += 2;
1014
+ }
1015
+ if (transition.getConditionName()) {
1016
+ score += 1;
1017
+ }
1018
+ return score;
1019
+ }
1020
+ selectTransition(transitions) {
1021
+ let bestTransitions = [];
1022
+ let bestScore = -1;
1023
+ for (const transition of transitions) {
1024
+ const score = this.calculateScore(transition);
1025
+ if (score > bestScore) {
1026
+ bestScore = score;
1027
+ bestTransitions = [transition];
1028
+ } else if (score === bestScore) {
1029
+ bestTransitions.push(transition);
1030
+ }
1031
+ }
1032
+ return this.innerSelector.selectTransition(bestTransitions);
1033
+ }
1034
+ };
1035
+
1036
+ // src/selector/WeightTransition.ts
1037
+ var WeightTransition = class {
1038
+ innerSelector;
1039
+ epsilon;
1040
+ constructor(innerSelector, epsilon = 1e-3) {
1041
+ this.innerSelector = innerSelector ?? new OneOrNoneActiveTransition();
1042
+ this.epsilon = epsilon;
1043
+ }
1044
+ selectTransition(transitions) {
1045
+ let bestTransitions = [];
1046
+ let bestWeight = null;
1047
+ for (const transition of transitions) {
1048
+ const weight = transition.getWeight();
1049
+ const diff = weight - (bestWeight ?? 0);
1050
+ if (bestWeight === null || diff >= this.epsilon) {
1051
+ bestWeight = weight;
1052
+ bestTransitions = [transition];
1053
+ } else if (Math.abs(diff) < this.epsilon) {
1054
+ bestTransitions.push(transition);
1055
+ }
1056
+ }
1057
+ return this.innerSelector.selectTransition(bestTransitions);
1058
+ }
1059
+ };
1060
+
1061
+ // src/mutex/LockAdapterMutex.ts
1062
+ var LockAdapterMutex = class {
1063
+ lockAdapter;
1064
+ resourceName;
1065
+ acquired = false;
1066
+ constructor(lockAdapter, resourceName) {
1067
+ this.lockAdapter = lockAdapter;
1068
+ this.resourceName = resourceName;
1069
+ }
1070
+ async acquireLock() {
1071
+ if (!this.acquired) {
1072
+ this.acquired = await this.lockAdapter.acquireLock(this.resourceName);
1073
+ }
1074
+ return this.acquired;
1075
+ }
1076
+ async releaseLock() {
1077
+ if (this.acquired) {
1078
+ const result = await this.lockAdapter.releaseLock(this.resourceName);
1079
+ if (result) {
1080
+ this.acquired = false;
1081
+ }
1082
+ return result;
1083
+ }
1084
+ return false;
1085
+ }
1086
+ isAcquired() {
1087
+ return this.acquired;
1088
+ }
1089
+ async isLocked() {
1090
+ return this.lockAdapter.isLocked(this.resourceName);
1091
+ }
1092
+ };
1093
+
1094
+ // src/mutex/MutexFactory.ts
1095
+ var MutexFactory = class {
1096
+ lockAdapter;
1097
+ stringConverter;
1098
+ constructor(lockAdapter, stringConverter) {
1099
+ this.lockAdapter = lockAdapter;
1100
+ this.stringConverter = stringConverter;
1101
+ }
1102
+ createMutex(subject) {
1103
+ return new LockAdapterMutex(
1104
+ this.lockAdapter,
1105
+ this.stringConverter(subject)
1106
+ );
1107
+ }
1108
+ };
1109
+
1110
+ // src/factory/Factory.ts
1111
+ var Factory = class {
1112
+ processDetector;
1113
+ stateNameDetector;
1114
+ statemachineObservers = /* @__PURE__ */ new Set();
1115
+ transitionSelector = null;
1116
+ mutexFactory = null;
1117
+ constructor(processDetector, stateNameDetector) {
1118
+ this.processDetector = processDetector;
1119
+ this.stateNameDetector = stateNameDetector ?? null;
1120
+ }
1121
+ setMutexFactory(factory) {
1122
+ this.mutexFactory = factory;
1123
+ }
1124
+ setTransitionSelector(selector) {
1125
+ this.transitionSelector = selector;
1126
+ }
1127
+ attachStatemachineObserver(observer) {
1128
+ this.statemachineObservers.add(observer);
1129
+ }
1130
+ detachStatemachineObserver(observer) {
1131
+ this.statemachineObservers.delete(observer);
1132
+ }
1133
+ getStatemachineObservers() {
1134
+ return this.statemachineObservers;
1135
+ }
1136
+ async createStatemachine(subject) {
1137
+ const process = this.processDetector.detectProcess(subject);
1138
+ const stateName = this.stateNameDetector ? this.stateNameDetector.detectCurrentStateName(subject) : null;
1139
+ const mutex = this.mutexFactory ? await this.mutexFactory.createMutex(subject) : null;
1140
+ const statemachine = new Statemachine(
1141
+ subject,
1142
+ process,
1143
+ stateName,
1144
+ this.transitionSelector,
1145
+ mutex
1146
+ );
1147
+ for (const observer of this.statemachineObservers) {
1148
+ statemachine.attach(observer);
1149
+ }
1150
+ return statemachine;
1151
+ }
1152
+ };
1153
+
1154
+ // src/factory/SingleProcessDetector.ts
1155
+ var SingleProcessDetector = class {
1156
+ process;
1157
+ constructor(process) {
1158
+ this.process = process;
1159
+ }
1160
+ detectProcess(_subject) {
1161
+ return this.process;
1162
+ }
1163
+ };
1164
+
1165
+ // src/factory/AbstractNamedProcessDetector.ts
1166
+ var AbstractNamedProcessDetector = class {
1167
+ processes = /* @__PURE__ */ new Map();
1168
+ addProcess(process) {
1169
+ this.processes.set(process.getName(), process);
1170
+ }
1171
+ hasProcess(name) {
1172
+ return this.processes.has(name);
1173
+ }
1174
+ detectProcess(subject) {
1175
+ const name = this.detectProcessName(subject);
1176
+ const process = this.processes.get(name);
1177
+ if (!process) {
1178
+ throw new Error(`Process "${name}" not found`);
1179
+ }
1180
+ return process;
1181
+ }
1182
+ };
1183
+
1184
+ // src/factory/StatefulStateNameDetector.ts
1185
+ function isStateful2(obj) {
1186
+ return typeof obj === "object" && obj !== null && "getCurrentStateName" in obj && typeof obj.getCurrentStateName === "function";
1187
+ }
1188
+ var StatefulStateNameDetector = class {
1189
+ detectCurrentStateName(subject) {
1190
+ if (isStateful2(subject)) {
1191
+ return subject.getCurrentStateName();
1192
+ }
1193
+ throw new Error("Subject has to implement the StatefulInterface!");
1194
+ }
1195
+ };
1196
+
1197
+ // src/util/SetupHelper.ts
1198
+ var SetupHelper = class {
1199
+ stateCollection;
1200
+ constructor(stateCollection) {
1201
+ this.stateCollection = stateCollection;
1202
+ }
1203
+ findOrCreateState(name) {
1204
+ if (!this.stateCollection.hasState(name)) {
1205
+ this.stateCollection.addState(new State(name));
1206
+ }
1207
+ return this.stateCollection.getState(name);
1208
+ }
1209
+ findTransition(sourceState, targetState, eventName = null, condition = null) {
1210
+ const conditionName = condition ? condition.getName() : null;
1211
+ for (const transition of sourceState.getTransitions()) {
1212
+ const hasSameTargetState = transition.getTargetState() === targetState;
1213
+ const hasSameCondition = transition.getConditionName() === conditionName;
1214
+ const hasSameEvent = transition.getEventName() === eventName;
1215
+ if (hasSameTargetState && hasSameCondition && hasSameEvent) {
1216
+ return transition;
1217
+ }
1218
+ }
1219
+ return null;
1220
+ }
1221
+ findOrCreateTransition(sourceStateName, targetStateName, eventName = null, condition = null) {
1222
+ const sourceState = this.findOrCreateState(sourceStateName);
1223
+ const targetState = this.findOrCreateState(targetStateName);
1224
+ let transition = this.findTransition(
1225
+ sourceState,
1226
+ targetState,
1227
+ eventName,
1228
+ condition
1229
+ );
1230
+ if (!transition) {
1231
+ transition = new Transition(targetState, eventName, condition);
1232
+ sourceState.addTransition(transition);
1233
+ }
1234
+ return transition;
1235
+ }
1236
+ findOrCreateEvent(sourceStateName, eventName) {
1237
+ const sourceState = this.findOrCreateState(sourceStateName);
1238
+ return sourceState.getEvent(eventName);
1239
+ }
1240
+ addCommand(sourceStateName, eventName, command) {
1241
+ this.findOrCreateEvent(sourceStateName, eventName).attach(command);
1242
+ }
1243
+ addCommandAndSelfTransition(sourceStateName, eventName, command) {
1244
+ this.addCommand(sourceStateName, eventName, command);
1245
+ this.findOrCreateTransition(sourceStateName, sourceStateName, eventName);
1246
+ }
1247
+ };
1248
+
1249
+ // src/graph/GraphBuilder.ts
1250
+ function isNamed2(obj) {
1251
+ return typeof obj === "object" && obj !== null && "getName" in obj && typeof obj.getName === "function";
1252
+ }
1253
+ function escapeDoubleQuotes(str) {
1254
+ return str.replace(/"/g, '\\"');
1255
+ }
1256
+ function toMermaidId(name) {
1257
+ return "s_" + name.replace(
1258
+ /[^a-zA-Z0-9]/g,
1259
+ (ch) => `_${ch.charCodeAt(0).toString(16).padStart(4, "0")}`
1260
+ );
1261
+ }
1262
+ function escapeMermaidLabel(str) {
1263
+ return str.replace(/"/g, "#quot;");
1264
+ }
1265
+ function convertToString2(obj) {
1266
+ if (isNamed2(obj)) {
1267
+ return obj.getName();
1268
+ }
1269
+ return String(obj);
1270
+ }
1271
+ var GraphBuilder = class {
1272
+ nodes = /* @__PURE__ */ new Map();
1273
+ edges = [];
1274
+ getOrCreateNode(state) {
1275
+ const name = state.getName();
1276
+ let node = this.nodes.get(name);
1277
+ if (!node) {
1278
+ node = { id: name, label: name, metadata: state.getMetadata() };
1279
+ this.nodes.set(name, node);
1280
+ }
1281
+ return node;
1282
+ }
1283
+ getTransitionLabel(state, transition) {
1284
+ const parts = [];
1285
+ const eventName = transition.getEventName();
1286
+ if (eventName) {
1287
+ parts.push(`E: ${eventName}`);
1288
+ const event = state.getEvent(eventName);
1289
+ const observerNames = [];
1290
+ for (const observer of event.getObservers()) {
1291
+ observerNames.push(convertToString2(observer));
1292
+ }
1293
+ if (observerNames.length > 0) {
1294
+ parts.push(`C: ${observerNames.join(", ")}`);
1295
+ }
1296
+ }
1297
+ const conditionName = transition.getConditionName();
1298
+ if (conditionName) {
1299
+ parts.push(`IF: ${conditionName}`);
1300
+ }
1301
+ parts.push(`W: ${transition.getWeight()}`);
1302
+ return parts.join("\n");
1303
+ }
1304
+ addState(state) {
1305
+ this.getOrCreateNode(state);
1306
+ for (const transition of state.getTransitions()) {
1307
+ const sourceNode = this.getOrCreateNode(state);
1308
+ const targetNode = this.getOrCreateNode(transition.getTargetState());
1309
+ const label = this.getTransitionLabel(state, transition);
1310
+ const metadata = {};
1311
+ const eventName = transition.getEventName();
1312
+ if (eventName && state.hasEvent(eventName)) {
1313
+ Object.assign(metadata, state.getEvent(eventName).getMetadata());
1314
+ }
1315
+ this.edges.push({
1316
+ source: sourceNode.id,
1317
+ target: targetNode.id,
1318
+ label,
1319
+ metadata
1320
+ });
1321
+ }
1322
+ }
1323
+ addStates(states) {
1324
+ for (const state of states) {
1325
+ this.addState(state);
1326
+ }
1327
+ }
1328
+ addStateCollection(stateCollection) {
1329
+ this.addStates(stateCollection.getStates());
1330
+ }
1331
+ getGraph() {
1332
+ return {
1333
+ nodes: Array.from(this.nodes.values()),
1334
+ edges: [...this.edges]
1335
+ };
1336
+ }
1337
+ toDot(options) {
1338
+ const graph = this.getGraph();
1339
+ const rankdir = options?.rankdir ?? "LR";
1340
+ const lines = [];
1341
+ lines.push("digraph {");
1342
+ lines.push(` rankdir=${rankdir};`);
1343
+ for (const node of graph.nodes) {
1344
+ const label = escapeDoubleQuotes(node.label);
1345
+ lines.push(` "${label}" [label="${label}"];`);
1346
+ }
1347
+ for (const edge of graph.edges) {
1348
+ const source = escapeDoubleQuotes(edge.source);
1349
+ const target = escapeDoubleQuotes(edge.target);
1350
+ const label = escapeDoubleQuotes(edge.label);
1351
+ lines.push(` "${source}" -> "${target}" [label="${label}"];`);
1352
+ }
1353
+ lines.push("}");
1354
+ return lines.join("\n");
1355
+ }
1356
+ toMermaid(options) {
1357
+ const graph = this.getGraph();
1358
+ const direction = options?.direction ?? "LR";
1359
+ const lines = [];
1360
+ lines.push(`stateDiagram-v2`);
1361
+ lines.push(` direction ${direction}`);
1362
+ const declared = /* @__PURE__ */ new Set();
1363
+ for (const node of graph.nodes) {
1364
+ const id = toMermaidId(node.id);
1365
+ if (!declared.has(id)) {
1366
+ declared.add(id);
1367
+ const label = escapeMermaidLabel(node.label);
1368
+ lines.push(` ${id} : "${label}"`);
1369
+ }
1370
+ }
1371
+ for (const edge of graph.edges) {
1372
+ const source = toMermaidId(edge.source);
1373
+ const target = toMermaidId(edge.target);
1374
+ const label = escapeMermaidLabel(edge.label.replace(/\n/g, " / "));
1375
+ lines.push(` ${source} --> ${target} : ${label}`);
1376
+ }
1377
+ return lines.join("\n");
1378
+ }
1379
+ };
1380
+ // Annotate the CommonJS export names for ESM import in node:
1381
+ 0 && (module.exports = {
1382
+ AbstractNamedProcessDetector,
1383
+ ActiveTransitionFilter,
1384
+ AndComposite,
1385
+ CallbackCondition,
1386
+ CallbackObserver,
1387
+ Contradiction,
1388
+ Dispatcher,
1389
+ DuplicateStateError,
1390
+ Event,
1391
+ Factory,
1392
+ FilterStateByEvent,
1393
+ FilterStateByFinalState,
1394
+ FilterStateByTransition,
1395
+ FilterTransitionByEvent,
1396
+ GraphBuilder,
1397
+ LockAdapterMutex,
1398
+ LockCanNotBeAcquiredError,
1399
+ MutexFactory,
1400
+ Not,
1401
+ NullMutex,
1402
+ OnEnterObserver,
1403
+ OneOrNoneActiveTransition,
1404
+ OrComposite,
1405
+ Process,
1406
+ ScoreTransition,
1407
+ SetupHelper,
1408
+ SingleProcessDetector,
1409
+ State,
1410
+ StateCollection,
1411
+ StateCollectionMerger,
1412
+ StatefulStateNameDetector,
1413
+ StatefulStatusChanger,
1414
+ Statemachine,
1415
+ Tautology,
1416
+ Timeout,
1417
+ Transition,
1418
+ TransitionLogger,
1419
+ WeightTransition,
1420
+ WrongEventForStateError
1421
+ });
1422
+ //# sourceMappingURL=index.cjs.map