gingersnap 0.22.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 (251) hide show
  1. package/_virtual/_tslib.cjs +102 -0
  2. package/_virtual/_tslib.mjs +93 -0
  3. package/data/AtomicValue.d.ts +15 -0
  4. package/data/bus.cjs +179 -0
  5. package/data/bus.d.ts +72 -0
  6. package/data/bus.mjs +177 -0
  7. package/data/decoders/index.d.ts +4 -0
  8. package/data/decoders/json.cjs +12 -0
  9. package/data/decoders/json.d.ts +7 -0
  10. package/data/decoders/json.mjs +10 -0
  11. package/data/decoders/msgpack.cjs +14 -0
  12. package/data/decoders/msgpack.d.ts +7 -0
  13. package/data/decoders/msgpack.mjs +12 -0
  14. package/data/decoders/protobuf.d.ts +13 -0
  15. package/data/decoders/string.cjs +12 -0
  16. package/data/decoders/string.d.ts +7 -0
  17. package/data/decoders/string.mjs +10 -0
  18. package/data/decoders/type.d.ts +7 -0
  19. package/data/decoders.cjs +11 -0
  20. package/data/decoders.mjs +3 -0
  21. package/data/model/credentials.cjs +114 -0
  22. package/data/model/credentials.d.ts +61 -0
  23. package/data/model/credentials.mjs +109 -0
  24. package/data/model/extra.cjs +88 -0
  25. package/data/model/extra.d.ts +5 -0
  26. package/data/model/extra.mjs +66 -0
  27. package/data/model/index.d.ts +6 -0
  28. package/data/model/model.cjs +541 -0
  29. package/data/model/model.d.ts +207 -0
  30. package/data/model/model.mjs +518 -0
  31. package/data/model/plugin.cjs +96 -0
  32. package/data/model/plugin.d.ts +38 -0
  33. package/data/model/plugin.mjs +72 -0
  34. package/data/model/property.cjs +310 -0
  35. package/data/model/property.d.ts +83 -0
  36. package/data/model/property.mjs +278 -0
  37. package/data/model/types.cjs +32 -0
  38. package/data/model/types.d.ts +28 -0
  39. package/data/model/types.mjs +32 -0
  40. package/data/model.cjs +43 -0
  41. package/data/model.mjs +6 -0
  42. package/data/signal.cjs +47 -0
  43. package/data/signal.d.ts +17 -0
  44. package/data/signal.mjs +45 -0
  45. package/data/store/index.d.ts +4 -0
  46. package/data/store/json.cjs +58 -0
  47. package/data/store/json.d.ts +18 -0
  48. package/data/store/json.mjs +56 -0
  49. package/data/store/manager.cjs +206 -0
  50. package/data/store/manager.d.ts +44 -0
  51. package/data/store/manager.mjs +203 -0
  52. package/data/store/web.cjs +92 -0
  53. package/data/store/web.d.ts +25 -0
  54. package/data/store/web.mjs +89 -0
  55. package/data/value.cjs +66 -0
  56. package/data/value.mjs +64 -0
  57. package/data-structures/array/CyclicalList.cjs +57 -0
  58. package/data-structures/array/CyclicalList.d.ts +12 -0
  59. package/data-structures/array/CyclicalList.mjs +55 -0
  60. package/data-structures/array/Pair.cjs +30 -0
  61. package/data-structures/array/Pair.d.ts +17 -0
  62. package/data-structures/array/Pair.mjs +27 -0
  63. package/data-structures/array/Stack.cjs +96 -0
  64. package/data-structures/array/Stack.d.ts +41 -0
  65. package/data-structures/array/Stack.mjs +94 -0
  66. package/data-structures/array/Triple.cjs +34 -0
  67. package/data-structures/array/Triple.d.ts +19 -0
  68. package/data-structures/array/Triple.mjs +31 -0
  69. package/data-structures/array/Tuple.d.ts +8 -0
  70. package/data-structures/array/index.d.ts +5 -0
  71. package/data-structures/array.cjs +15 -0
  72. package/data-structures/array.mjs +4 -0
  73. package/data-structures/object/BufferQueue.cjs +98 -0
  74. package/data-structures/object/BufferQueue.d.ts +21 -0
  75. package/data-structures/object/BufferQueue.mjs +77 -0
  76. package/data-structures/object/CyclicalObject.cjs +155 -0
  77. package/data-structures/object/CyclicalObject.d.ts +74 -0
  78. package/data-structures/object/CyclicalObject.mjs +134 -0
  79. package/data-structures/object/Queue.cjs +178 -0
  80. package/data-structures/object/Queue.d.ts +31 -0
  81. package/data-structures/object/Queue.mjs +176 -0
  82. package/data-structures/object/SimpleQueue.cjs +53 -0
  83. package/data-structures/object/SimpleQueue.d.ts +13 -0
  84. package/data-structures/object/SimpleQueue.mjs +51 -0
  85. package/data-structures/object/TimeableObject.cjs +73 -0
  86. package/data-structures/object/TimeableObject.d.ts +30 -0
  87. package/data-structures/object/TimeableObject.mjs +71 -0
  88. package/data-structures/object/WaitableObject.cjs +61 -0
  89. package/data-structures/object/WaitableObject.d.ts +29 -0
  90. package/data-structures/object/WaitableObject.mjs +59 -0
  91. package/data-structures/object/WatchableObject.cjs +251 -0
  92. package/data-structures/object/WatchableObject.d.ts +88 -0
  93. package/data-structures/object/WatchableObject.mjs +230 -0
  94. package/data-structures/object/index.d.ts +7 -0
  95. package/data-structures/object.cjs +23 -0
  96. package/data-structures/object.mjs +7 -0
  97. package/errors/AbortError.cjs +9 -0
  98. package/errors/AbortError.d.ts +5 -0
  99. package/errors/AbortError.mjs +7 -0
  100. package/errors/CallExecutionError.cjs +13 -0
  101. package/errors/CallExecutionError.d.ts +7 -0
  102. package/errors/CallExecutionError.mjs +11 -0
  103. package/errors/FutureCancelled.cjs +11 -0
  104. package/errors/FutureCancelled.d.ts +6 -0
  105. package/errors/FutureCancelled.mjs +9 -0
  106. package/errors/FutureError.cjs +11 -0
  107. package/errors/FutureError.d.ts +6 -0
  108. package/errors/FutureError.mjs +9 -0
  109. package/errors/IllegalArgumentsError.cjs +13 -0
  110. package/errors/IllegalArgumentsError.d.ts +7 -0
  111. package/errors/IllegalArgumentsError.mjs +11 -0
  112. package/errors/IllegalOperationError.cjs +6 -0
  113. package/errors/IllegalOperationError.d.ts +2 -0
  114. package/errors/IllegalOperationError.mjs +4 -0
  115. package/errors/InvalidType.cjs +6 -0
  116. package/errors/InvalidType.d.ts +2 -0
  117. package/errors/InvalidType.mjs +4 -0
  118. package/errors/InvalidValue.cjs +11 -0
  119. package/errors/InvalidValue.d.ts +4 -0
  120. package/errors/InvalidValue.mjs +9 -0
  121. package/errors/MissingArgumentsError.cjs +13 -0
  122. package/errors/MissingArgumentsError.d.ts +7 -0
  123. package/errors/MissingArgumentsError.mjs +11 -0
  124. package/errors/NetworkError.cjs +13 -0
  125. package/errors/NetworkError.d.ts +8 -0
  126. package/errors/NetworkError.mjs +11 -0
  127. package/errors/NoSuchElement.cjs +6 -0
  128. package/errors/NoSuchElement.d.ts +2 -0
  129. package/errors/NoSuchElement.mjs +4 -0
  130. package/errors/NotImplemented.cjs +9 -0
  131. package/errors/NotImplemented.d.ts +5 -0
  132. package/errors/NotImplemented.mjs +7 -0
  133. package/errors/ParsingError.cjs +10 -0
  134. package/errors/ParsingError.d.ts +5 -0
  135. package/errors/ParsingError.mjs +8 -0
  136. package/errors/QueueEmptyError.cjs +6 -0
  137. package/errors/QueueEmptyError.d.ts +2 -0
  138. package/errors/QueueEmptyError.mjs +4 -0
  139. package/errors/QueueFullError.cjs +6 -0
  140. package/errors/QueueFullError.d.ts +2 -0
  141. package/errors/QueueFullError.mjs +4 -0
  142. package/errors/StackEmptyError.cjs +6 -0
  143. package/errors/StackEmptyError.d.ts +2 -0
  144. package/errors/StackEmptyError.mjs +4 -0
  145. package/errors/StackFullError.cjs +6 -0
  146. package/errors/StackFullError.d.ts +2 -0
  147. package/errors/StackFullError.mjs +4 -0
  148. package/errors/StreamEnded.cjs +6 -0
  149. package/errors/StreamEnded.d.ts +2 -0
  150. package/errors/StreamEnded.mjs +4 -0
  151. package/errors/TimeoutError.cjs +11 -0
  152. package/errors/TimeoutError.d.ts +6 -0
  153. package/errors/TimeoutError.mjs +9 -0
  154. package/errors/ValueDestroyedError.cjs +6 -0
  155. package/errors/ValueDestroyedError.d.ts +2 -0
  156. package/errors/ValueDestroyedError.mjs +4 -0
  157. package/errors/VerificationError.cjs +9 -0
  158. package/errors/VerificationError.d.ts +5 -0
  159. package/errors/VerificationError.mjs +7 -0
  160. package/errors/index.d.ts +18 -0
  161. package/errors.cjs +41 -0
  162. package/errors.mjs +18 -0
  163. package/files.cjs +201 -0
  164. package/files.d.ts +31 -0
  165. package/files.mjs +180 -0
  166. package/functools/index.d.ts +31 -0
  167. package/functools.cjs +371 -0
  168. package/functools.mjs +334 -0
  169. package/future/future.cjs +570 -0
  170. package/future/future.d.ts +208 -0
  171. package/future/future.mjs +548 -0
  172. package/future/group.cjs +180 -0
  173. package/future/group.d.ts +82 -0
  174. package/future/group.mjs +159 -0
  175. package/future/index.d.ts +3 -0
  176. package/future/result.cjs +19 -0
  177. package/future/result.d.ts +18 -0
  178. package/future/result.mjs +17 -0
  179. package/future.cjs +11 -0
  180. package/future.mjs +3 -0
  181. package/managers/context.d.ts +8 -0
  182. package/managers/index.d.ts +1 -0
  183. package/managers.cjs +2 -0
  184. package/managers.mjs +1 -0
  185. package/mocks.cjs +301 -0
  186. package/mocks.d.ts +125 -0
  187. package/mocks.mjs +293 -0
  188. package/networking/EventSourceService.cjs +104 -0
  189. package/networking/EventSourceService.d.ts +11 -0
  190. package/networking/EventSourceService.mjs +83 -0
  191. package/networking/NetworkService.cjs +394 -0
  192. package/networking/NetworkService.d.ts +97 -0
  193. package/networking/NetworkService.mjs +373 -0
  194. package/networking/SocketService.cjs +218 -0
  195. package/networking/SocketService.d.ts +23 -0
  196. package/networking/SocketService.mjs +197 -0
  197. package/networking/decorators/index.d.ts +4 -0
  198. package/networking/decorators/options.cjs +289 -0
  199. package/networking/decorators/options.d.ts +148 -0
  200. package/networking/decorators/options.mjs +242 -0
  201. package/networking/decorators/requests.cjs +80 -0
  202. package/networking/decorators/requests.d.ts +34 -0
  203. package/networking/decorators/requests.mjs +52 -0
  204. package/networking/decorators/socket.cjs +81 -0
  205. package/networking/decorators/socket.d.ts +13 -0
  206. package/networking/decorators/socket.mjs +51 -0
  207. package/networking/http.cjs +69 -0
  208. package/networking/http.d.ts +66 -0
  209. package/networking/http.mjs +69 -0
  210. package/networking/index.d.ts +39 -0
  211. package/networking/request.cjs +18 -0
  212. package/networking/request.d.ts +9 -0
  213. package/networking/request.mjs +16 -0
  214. package/networking/types.cjs +37 -0
  215. package/networking/types.d.ts +132 -0
  216. package/networking/types.mjs +35 -0
  217. package/networking.cjs +91 -0
  218. package/networking.mjs +33 -0
  219. package/package.json +1 -0
  220. package/reflection/injector.cjs +43 -0
  221. package/reflection/injector.d.ts +3 -0
  222. package/reflection/injector.mjs +40 -0
  223. package/socket.cjs +239 -0
  224. package/socket.d.ts +65 -0
  225. package/socket.mjs +237 -0
  226. package/store.cjs +12 -0
  227. package/store.mjs +3 -0
  228. package/stream/call.cjs +157 -0
  229. package/stream/call.d.ts +66 -0
  230. package/stream/call.mjs +154 -0
  231. package/stream/collector.cjs +217 -0
  232. package/stream/collector.d.ts +14 -0
  233. package/stream/collector.mjs +215 -0
  234. package/stream/index.d.ts +257 -0
  235. package/stream/observable.cjs +110 -0
  236. package/stream/observable.d.ts +65 -0
  237. package/stream/observable.mjs +106 -0
  238. package/stream/state.cjs +10 -0
  239. package/stream/state.d.ts +5 -0
  240. package/stream/state.mjs +8 -0
  241. package/stream.cjs +1153 -0
  242. package/stream.mjs +1132 -0
  243. package/synchronize.cjs +106 -0
  244. package/synchronize.d.ts +54 -0
  245. package/synchronize.mjs +103 -0
  246. package/typing/types.d.ts +24 -0
  247. package/typing.cjs +2 -0
  248. package/typing.mjs +1 -0
  249. package/utils/parser.cjs +37 -0
  250. package/utils/parser.d.ts +7 -0
  251. package/utils/parser.mjs +16 -0
@@ -0,0 +1,548 @@
1
+ import { __awaiter } from '../_virtual/_tslib.mjs';
2
+ import { FutureCancelled } from '../errors/FutureCancelled.mjs';
3
+ import { FutureError } from '../errors/FutureError.mjs';
4
+ import { InvalidValue } from '../errors/InvalidValue.mjs';
5
+ import { TimeoutError } from '../errors/TimeoutError.mjs';
6
+ import * as R from 'ramda';
7
+ import { SimpleQueue } from '../data-structures/object/SimpleQueue.mjs';
8
+ import { v4 } from 'uuid';
9
+ import { FutureResult } from './result.mjs';
10
+ import { Stream } from '../stream.mjs';
11
+
12
+ const calculatePeriodValue = (period) => {
13
+ var _a, _b, _c, _d;
14
+ return ((_a = period.hours) !== null && _a !== void 0 ? _a : 0) * 60 * 60 * 1000 +
15
+ ((_b = period.minutes) !== null && _b !== void 0 ? _b : 0) * 60 * 1000 +
16
+ ((_c = period.seconds) !== null && _c !== void 0 ? _c : 0) * 1000 +
17
+ ((_d = period.milliseconds) !== null && _d !== void 0 ? _d : 0);
18
+ };
19
+ /**
20
+ * Represents an eventual result of some asynchronous operation. Futures are quite similar to Promise, and can be
21
+ * awaited as they are **Thenable** objects
22
+ */
23
+ class Future {
24
+ constructor(executor, signal) {
25
+ this.guid = v4();
26
+ this.executor = executor;
27
+ this.defaultSignal = signal !== null && signal !== void 0 ? signal : new AbortController().signal;
28
+ this.signals = new Set([this.defaultSignal]);
29
+ this.fulfilled = false;
30
+ this.isRunning = false;
31
+ this.processors = new SimpleQueue();
32
+ this.finallyHandlers = new SimpleQueue();
33
+ }
34
+ /**
35
+ * Creates a future that wraps the given future, and prevents it from being cancellable on the call to "cancel" method
36
+ * @param future
37
+ */
38
+ static shield(future) {
39
+ return Future.of((resolve, reject) => {
40
+ future
41
+ .thenApply(({ value }) => resolve(value))
42
+ .catch(reject)
43
+ .schedule();
44
+ });
45
+ }
46
+ /**
47
+ * Creates a future from the value provided
48
+ * @param value an Executor function (callback for the new Future constructor)
49
+ * @param signal Abort Signal to establish the future with. If not provided, the future will only have the default
50
+ * signals
51
+ */
52
+ static of(value, signal) {
53
+ return new Future(value, signal);
54
+ }
55
+ /**
56
+ * Wraps a promise as a future
57
+ * @param value
58
+ */
59
+ static wrap(value) {
60
+ return new Future((resolve, reject) => {
61
+ value.then(resolve).catch(reject);
62
+ });
63
+ }
64
+ /**
65
+ * Waits for the given future to complete. If not completed within the given timeframe, the given future is cancelled
66
+ * @param value
67
+ * @param timeout wait period object or the number of milliseconds to wait
68
+ */
69
+ static waitFor(value, timeout) {
70
+ const timeableFuture = Future.sleep(timeout)
71
+ .registerSignal(value.defaultSignal)
72
+ .catch(() => { });
73
+ return Future.of((resolve, reject) => Promise.race([timeableFuture, value.run()])
74
+ .then((v) => {
75
+ if (value.done) {
76
+ timeableFuture.cancel();
77
+ resolve(v);
78
+ return;
79
+ }
80
+ value.cancel();
81
+ reject(new TimeoutError());
82
+ })
83
+ .catch((error) => {
84
+ if (!timeableFuture.failed) {
85
+ timeableFuture.cancel();
86
+ }
87
+ reject(error);
88
+ }), value.defaultSignal);
89
+ }
90
+ /**
91
+ * Sleeps for the given period. If period is a number, then it's the sleep duration in seconds
92
+ * @param period
93
+ * @param signal
94
+ */
95
+ static sleep(period, signal) {
96
+ return new Future((resolve, reject, futureSignal) => {
97
+ const totalTime = typeof period === "number" ? period * 1000 : calculatePeriodValue(period);
98
+ const timer = setTimeout(resolve, totalTime);
99
+ futureSignal.addEventListener("abort", () => {
100
+ clearTimeout(timer);
101
+ reject(new FutureCancelled());
102
+ }, { once: true });
103
+ }, signal);
104
+ }
105
+ /**
106
+ * Returns a future that completes with the given value.
107
+ * Important Note:
108
+ * Passing a Future or Stream to this function will execute it once and yield the result.
109
+ * @param value
110
+ */
111
+ static completed(value) {
112
+ return new Future((resolve) => resolve(value));
113
+ }
114
+ /**
115
+ * Returns a future that fails with the given value
116
+ * @param value
117
+ */
118
+ static exceptionally(value) {
119
+ return new Future((_, reject) => reject(value));
120
+ }
121
+ /**
122
+ * Returns the first completed or failed. If this is cancelled, then all futures provided will also be cancelled
123
+ * @param futures list of futures
124
+ * @param signal optinal abort signal
125
+ */
126
+ static firstCompleted(futures, signal) {
127
+ return Future.of((resolve, reject, signal) => {
128
+ futures.forEach((future) => {
129
+ future.registerSignal(signal);
130
+ });
131
+ Promise.race(futures)
132
+ .then(resolve)
133
+ .catch(reject)
134
+ .finally(() => {
135
+ futures.forEach((future) => {
136
+ future.unregisterSignal(signal);
137
+ });
138
+ });
139
+ }, signal);
140
+ }
141
+ /**
142
+ * Awaits all futures completion, and collects the results in an array. If this future is cancelled, then all provided
143
+ * futures will also be cancelled.
144
+ * @param futures list of futures
145
+ * @param signal optional abort signal
146
+ */
147
+ static collect(futures, signal) {
148
+ return Future.of((resolve, reject, signal) => {
149
+ futures.forEach((future) => {
150
+ future.registerSignal(signal);
151
+ });
152
+ Promise.all(futures.map((f) => f.run()))
153
+ .then(resolve)
154
+ .catch(reject)
155
+ .finally(() => {
156
+ futures.forEach((future) => {
157
+ future.unregisterSignal(signal);
158
+ });
159
+ });
160
+ }, signal);
161
+ }
162
+ /**
163
+ * Awaits futures finishing all possible executions, and returns the same list of futures. Whether each future
164
+ * completed or failed, the future is returned in the array
165
+ * @param futures
166
+ */
167
+ static collectSettled(futures) {
168
+ return Future.of((resolve, reject, signal) => {
169
+ futures.forEach((future) => {
170
+ future.registerSignal(signal);
171
+ });
172
+ Promise.allSettled(futures.map((f) => f.run()))
173
+ .then(() => resolve(futures))
174
+ .catch(reject)
175
+ .finally(() => {
176
+ futures.forEach((future) => {
177
+ future.unregisterSignal(signal);
178
+ });
179
+ });
180
+ });
181
+ }
182
+ /**
183
+ * Creates a future that schedules the provided functor at the given frequency intervals
184
+ * @param functor function to be executed at specified intervals
185
+ * @param frequency interval used to schedule the functor's call
186
+ */
187
+ static periodic(functor, frequency) {
188
+ return Future.of((resolve, reject, signal) => {
189
+ // eslint-disable-next-line @typescript-eslint/no-misused-promises
190
+ const cancel = setInterval(() => __awaiter(this, void 0, void 0, function* () {
191
+ const result = functor(signal);
192
+ if (result instanceof Promise || result instanceof Future) {
193
+ yield result;
194
+ }
195
+ }), calculatePeriodValue(frequency));
196
+ signal.addEventListener("abort", () => {
197
+ clearInterval(cancel);
198
+ resolve(undefined);
199
+ }, { once: true });
200
+ });
201
+ }
202
+ /**
203
+ * Unique ID of the future
204
+ */
205
+ get id() {
206
+ return this.guid;
207
+ }
208
+ /**
209
+ * Changes the future ID
210
+ * @param value
211
+ */
212
+ set id(value) {
213
+ this.guid = value;
214
+ }
215
+ /**
216
+ * Checks if the future completed. A completed future is one that ran successfully without termination.
217
+ */
218
+ get done() {
219
+ return this.fulfilled;
220
+ }
221
+ /**
222
+ * Checks if the future failed
223
+ */
224
+ get failed() {
225
+ return this.error instanceof Error;
226
+ }
227
+ /**
228
+ * Retrieves the result of the future, if there is any
229
+ */
230
+ get result() {
231
+ return this.completedResult;
232
+ }
233
+ /**
234
+ * Checks if the future is running
235
+ */
236
+ get running() {
237
+ return this.isRunning;
238
+ }
239
+ /**
240
+ * Retrieves the error if any occurred
241
+ */
242
+ get error() {
243
+ return this.failureResult;
244
+ }
245
+ /**
246
+ * Convert the future to a stream
247
+ */
248
+ get stream() {
249
+ return Stream.of(this);
250
+ }
251
+ /**
252
+ * Registers additional signal to the current future
253
+ * @param signal
254
+ */
255
+ registerSignal(signal) {
256
+ if (!this.done && !this.failed) {
257
+ this.signals.add(signal);
258
+ if (this.signalRegisteredCallback) {
259
+ this.signalRegisteredCallback(signal);
260
+ }
261
+ }
262
+ return this;
263
+ }
264
+ /**
265
+ * Removes the given signal from the future
266
+ * @param signal
267
+ */
268
+ unregisterSignal(signal) {
269
+ if (signal === this.defaultSignal) {
270
+ throw new InvalidValue("Cannot deregister default signal");
271
+ }
272
+ this.signals.delete(signal);
273
+ return this;
274
+ }
275
+ /**
276
+ * Runs the future in the background
277
+ */
278
+ schedule() {
279
+ this.run().catch(() => { });
280
+ return this;
281
+ }
282
+ /**
283
+ * Launches the future
284
+ */
285
+ run() {
286
+ return this.__run__();
287
+ }
288
+ /**
289
+ * Cancels the future if it is currently running
290
+ */
291
+ cancel() {
292
+ if (this.running) {
293
+ this.cancelWithSignal(this.defaultSignal);
294
+ }
295
+ }
296
+ /**
297
+ * Used to chain additional steps to be executed. This creates a new future
298
+ * @param callback
299
+ * @param clone whether the future should be cloned or not.Defaults to true
300
+ */
301
+ thenApply(callback, clone = false) {
302
+ if (this.running) {
303
+ const newFuture = Future.wrap(this.underLyingPromise)
304
+ .thenApply(callback)
305
+ .registerSignal(this.defaultSignal);
306
+ this.signals.forEach((signal) => newFuture.registerSignal(signal));
307
+ return newFuture;
308
+ }
309
+ else if (this.done) {
310
+ const newFuture = Future.wrap(this.underLyingPromise).thenApply(callback);
311
+ return newFuture;
312
+ }
313
+ const newFuture = (clone ? this.clone() : this);
314
+ newFuture.processors.enqueue({ success: callback });
315
+ return newFuture;
316
+ }
317
+ /**
318
+ * Used to run callback irrespective of the future completing or failing
319
+ * @param callback
320
+ * @param clone whether the future should be cloned or not.Defaults to true
321
+ */
322
+ finally(callback, clone = false) {
323
+ const newFuture = clone ? this.clone() : this;
324
+ newFuture.finallyHandlers.enqueue(callback);
325
+ return newFuture;
326
+ }
327
+ /**
328
+ * Handles any error that occurs in the previous steps inside the future
329
+ * @param callback
330
+ * @param clone whether the future should be cloned or not.Defaults to true
331
+ */
332
+ catch(callback, clone = false) {
333
+ const newFuture = (clone ? this.clone() : this);
334
+ newFuture.processors.enqueue({ failure: callback });
335
+ return newFuture;
336
+ }
337
+ /**
338
+ * Clones the current future
339
+ */
340
+ clone() {
341
+ const future = new Future(this.executor, this.defaultSignal);
342
+ future.signals = new Set(this.signals);
343
+ future.defaultSignal = this.defaultSignal;
344
+ future.processors = this.processors.clone();
345
+ future.fulfilled = this.fulfilled;
346
+ return future;
347
+ }
348
+ /**
349
+ * Internal. Only to be called by the internal JS runtime during await
350
+ * @private
351
+ */
352
+ then(onFulfilled, onRejected) {
353
+ return this.__run__(onFulfilled, onRejected);
354
+ }
355
+ /**
356
+ * Executes the future. Should only be triggered by the JS runtime via then(), or the user via run()
357
+ * @param onFulfilled
358
+ * @param onRejected
359
+ * @private
360
+ */
361
+ __run__(onFulfilled, onRejected) {
362
+ if (this.underLyingPromise) {
363
+ return this.underLyingPromise
364
+ .then((v) => {
365
+ onFulfilled === null || onFulfilled === void 0 ? void 0 : onFulfilled(v);
366
+ return v;
367
+ })
368
+ .catch((error) => {
369
+ if (!(error instanceof Error)) {
370
+ error = new FutureError(error);
371
+ }
372
+ onRejected === null || onRejected === void 0 ? void 0 : onRejected(error);
373
+ throw error;
374
+ });
375
+ }
376
+ this.isRunning = true;
377
+ const resolvePromise = (promise) => {
378
+ return promise
379
+ .then((result) => __awaiter(this, void 0, void 0, function* () {
380
+ while (!this.processors.empty) {
381
+ const { success } = this.processors.dequeue();
382
+ if (!success)
383
+ continue;
384
+ try {
385
+ result = yield this.postResultProcessing(success(new FutureResult(result, this.defaultSignal)));
386
+ }
387
+ catch (error) {
388
+ const handler = this.findFailureHandler();
389
+ if (!handler) {
390
+ throw error;
391
+ }
392
+ result = yield this.postResultProcessing(handler(error instanceof Error ? error : new Error(String(error))));
393
+ }
394
+ }
395
+ return result;
396
+ }))
397
+ .then((v) => {
398
+ onFulfilled === null || onFulfilled === void 0 ? void 0 : onFulfilled(v);
399
+ return v;
400
+ })
401
+ .catch((error) => __awaiter(this, void 0, void 0, function* () {
402
+ const handler = this.findFailureHandler();
403
+ if (!handler) {
404
+ if (!(error instanceof Error)) {
405
+ error = new FutureError(error);
406
+ }
407
+ onRejected === null || onRejected === void 0 ? void 0 : onRejected(error);
408
+ throw error;
409
+ }
410
+ try {
411
+ const result = yield this.postResultProcessing(handler(error));
412
+ return yield resolvePromise(Promise.resolve(result));
413
+ }
414
+ catch (e) {
415
+ onRejected === null || onRejected === void 0 ? void 0 : onRejected(e);
416
+ throw e;
417
+ }
418
+ }));
419
+ };
420
+ this.underLyingPromise = resolvePromise(new Promise((resolve, reject) => {
421
+ if (Array.from(this.signals).some((v) => v.aborted)) {
422
+ reject(new FutureCancelled());
423
+ return;
424
+ }
425
+ let rejected = false;
426
+ const timeouts = [];
427
+ const abort = R.once(() => this.cancelWithSignal(this.defaultSignal));
428
+ const resolver = (v) => {
429
+ if (v instanceof Promise) {
430
+ v.then((v) => {
431
+ this.fulfilled = true;
432
+ resolve(v);
433
+ }).catch(reject);
434
+ }
435
+ else if (v instanceof Future) {
436
+ v.run()
437
+ .then((v) => {
438
+ this.fulfilled = true;
439
+ resolve(v);
440
+ })
441
+ .catch(reject);
442
+ }
443
+ else if (v instanceof FutureResult) {
444
+ this.fulfilled = true;
445
+ resolve(v.value);
446
+ }
447
+ else {
448
+ this.fulfilled = true;
449
+ resolve(v);
450
+ }
451
+ };
452
+ const rejecter = (reason) => {
453
+ rejected = true;
454
+ timeouts.forEach((v) => clearTimeout(v));
455
+ reject(reason);
456
+ };
457
+ this.signalRegisteredCallback = (v) => v.addEventListener("abort", () => {
458
+ abort();
459
+ if (!rejected)
460
+ timeouts.push(setTimeout(() => reject(new FutureCancelled()), 1000));
461
+ }, { once: true });
462
+ this.signals.forEach((v) => {
463
+ v.addEventListener("abort", () => {
464
+ abort();
465
+ if (!rejected) {
466
+ timeouts.push(setTimeout(() => reject(new FutureCancelled()), 1000));
467
+ }
468
+ }, { once: true });
469
+ });
470
+ const result = this.executor(resolver, rejecter, this.defaultSignal);
471
+ if (result instanceof Promise) {
472
+ result
473
+ .then(() => {
474
+ if (!this.fulfilled) {
475
+ this.fulfilled = true;
476
+ resolve(null);
477
+ }
478
+ })
479
+ .catch(rejecter);
480
+ }
481
+ }))
482
+ .then((v) => {
483
+ this.completedResult = v;
484
+ return v;
485
+ })
486
+ .catch((e) => {
487
+ this.failureResult = e instanceof Error ? e : new Error(String(e));
488
+ throw this.failureResult;
489
+ })
490
+ .finally(() => {
491
+ this.finallyHandlers.forEach((handler) => handler(this));
492
+ })
493
+ .catch((e) => {
494
+ this.failureResult = e instanceof Error ? e : new Error(String(e));
495
+ throw this.failureResult;
496
+ })
497
+ .finally(() => {
498
+ this.signals = new Set();
499
+ this.isRunning = false;
500
+ });
501
+ return this.underLyingPromise;
502
+ }
503
+ /**
504
+ * Fires the abort signal
505
+ * @param signal
506
+ * @private
507
+ */
508
+ cancelWithSignal(signal) {
509
+ if (!signal.aborted) {
510
+ signal.dispatchEvent(new CustomEvent("abort"));
511
+ }
512
+ }
513
+ /**
514
+ * Checks if any handler exist to process errors
515
+ * @private
516
+ */
517
+ findFailureHandler() {
518
+ while (!this.processors.empty) {
519
+ const { failure } = this.processors.dequeue();
520
+ if (failure)
521
+ return failure;
522
+ }
523
+ }
524
+ /**
525
+ * Nested processing of a future result
526
+ * @param result
527
+ * @private
528
+ */
529
+ postResultProcessing(result) {
530
+ return __awaiter(this, void 0, void 0, function* () {
531
+ if (result instanceof FutureResult) {
532
+ result = result.value;
533
+ }
534
+ else if (result instanceof Future) {
535
+ result = yield result.registerSignal(this.defaultSignal).run();
536
+ }
537
+ else if (result instanceof Promise) {
538
+ result = yield result;
539
+ }
540
+ else if (result instanceof Stream) {
541
+ result = yield result.execute();
542
+ }
543
+ return result;
544
+ });
545
+ }
546
+ }
547
+
548
+ export { Future, calculatePeriodValue };