@evolu/common 6.0.1-preview.9 → 7.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 (195) hide show
  1. package/README.md +27 -29
  2. package/dist/src/Array.d.ts +317 -12
  3. package/dist/src/Array.d.ts.map +1 -1
  4. package/dist/src/Array.js +219 -9
  5. package/dist/src/Assert.d.ts +0 -13
  6. package/dist/src/Assert.d.ts.map +1 -1
  7. package/dist/src/Assert.js +0 -15
  8. package/dist/src/Brand.d.ts +75 -0
  9. package/dist/src/Brand.d.ts.map +1 -0
  10. package/dist/src/Brand.js +1 -0
  11. package/dist/src/Buffer.d.ts +1 -1
  12. package/dist/src/Buffer.d.ts.map +1 -1
  13. package/dist/src/Buffer.js +8 -7
  14. package/dist/src/Cache.d.ts +39 -0
  15. package/dist/src/Cache.d.ts.map +1 -0
  16. package/dist/src/Cache.js +47 -0
  17. package/dist/src/Callbacks.d.ts +45 -12
  18. package/dist/src/Callbacks.d.ts.map +1 -1
  19. package/dist/src/Callbacks.js +14 -7
  20. package/dist/src/Console.d.ts +32 -7
  21. package/dist/src/Console.d.ts.map +1 -1
  22. package/dist/src/Console.js +73 -10
  23. package/dist/src/Crypto.d.ts +56 -42
  24. package/dist/src/Crypto.d.ts.map +1 -1
  25. package/dist/src/Crypto.js +45 -54
  26. package/dist/src/Evolu/Db.d.ts +162 -74
  27. package/dist/src/Evolu/Db.d.ts.map +1 -1
  28. package/dist/src/Evolu/Db.js +284 -702
  29. package/dist/src/Evolu/Diff.d.ts +3 -3
  30. package/dist/src/Evolu/Diff.d.ts.map +1 -1
  31. package/dist/src/Evolu/Diff.js +7 -5
  32. package/dist/src/Evolu/Evolu.d.ts +213 -133
  33. package/dist/src/Evolu/Evolu.d.ts.map +1 -1
  34. package/dist/src/Evolu/Evolu.js +189 -180
  35. package/dist/src/Evolu/Internal.d.ts +2 -4
  36. package/dist/src/Evolu/Internal.d.ts.map +1 -1
  37. package/dist/src/Evolu/Internal.js +2 -4
  38. package/dist/src/Evolu/LocalAuth.d.ts +150 -0
  39. package/dist/src/Evolu/LocalAuth.d.ts.map +1 -0
  40. package/dist/src/Evolu/LocalAuth.js +174 -0
  41. package/dist/src/Evolu/Owner.d.ts +273 -120
  42. package/dist/src/Evolu/Owner.d.ts.map +1 -1
  43. package/dist/src/Evolu/Owner.js +130 -104
  44. package/dist/src/Evolu/Platform.d.ts +9 -7
  45. package/dist/src/Evolu/Platform.d.ts.map +1 -1
  46. package/dist/src/Evolu/Protocol.d.ts +268 -240
  47. package/dist/src/Evolu/Protocol.d.ts.map +1 -1
  48. package/dist/src/Evolu/Protocol.js +595 -447
  49. package/dist/src/Evolu/Public.d.ts +7 -9
  50. package/dist/src/Evolu/Public.d.ts.map +1 -1
  51. package/dist/src/Evolu/Public.js +3 -4
  52. package/dist/src/Evolu/PublicKysely.d.ts.map +1 -1
  53. package/dist/src/Evolu/PublicKysely.js +3 -4
  54. package/dist/src/Evolu/Query.d.ts +2 -1
  55. package/dist/src/Evolu/Query.d.ts.map +1 -1
  56. package/dist/src/Evolu/Query.js +1 -1
  57. package/dist/src/Evolu/Relay.d.ts +91 -8
  58. package/dist/src/Evolu/Relay.d.ts.map +1 -1
  59. package/dist/src/Evolu/Relay.js +214 -88
  60. package/dist/src/Evolu/Schema.d.ts +125 -47
  61. package/dist/src/Evolu/Schema.d.ts.map +1 -1
  62. package/dist/src/Evolu/Schema.js +175 -31
  63. package/dist/src/Evolu/Storage.d.ts +249 -27
  64. package/dist/src/Evolu/Storage.d.ts.map +1 -1
  65. package/dist/src/Evolu/Storage.js +198 -92
  66. package/dist/src/Evolu/Sync.d.ts +68 -13
  67. package/dist/src/Evolu/Sync.d.ts.map +1 -1
  68. package/dist/src/Evolu/Sync.js +469 -20
  69. package/dist/src/Evolu/Timestamp.d.ts +83 -30
  70. package/dist/src/Evolu/Timestamp.d.ts.map +1 -1
  71. package/dist/src/Evolu/Timestamp.js +79 -34
  72. package/dist/src/Identicon.d.ts +35 -0
  73. package/dist/src/Identicon.d.ts.map +1 -0
  74. package/dist/src/Identicon.js +143 -0
  75. package/dist/src/Instances.d.ts +34 -0
  76. package/dist/src/Instances.d.ts.map +1 -0
  77. package/dist/src/Instances.js +44 -0
  78. package/dist/src/Number.d.ts +4 -3
  79. package/dist/src/Number.d.ts.map +1 -1
  80. package/dist/src/Number.js +5 -4
  81. package/dist/src/Object.d.ts +10 -4
  82. package/dist/src/Object.d.ts.map +1 -1
  83. package/dist/src/Object.js +9 -3
  84. package/dist/src/Order.d.ts +0 -5
  85. package/dist/src/Order.d.ts.map +1 -1
  86. package/dist/src/Order.js +0 -5
  87. package/dist/src/Platform.d.ts +15 -0
  88. package/dist/src/Platform.d.ts.map +1 -0
  89. package/dist/src/Platform.js +17 -0
  90. package/dist/src/Random.d.ts +3 -7
  91. package/dist/src/Random.d.ts.map +1 -1
  92. package/dist/src/Random.js +0 -5
  93. package/dist/src/Ref.d.ts.map +1 -1
  94. package/dist/src/Relation.d.ts +79 -0
  95. package/dist/src/Relation.d.ts.map +1 -0
  96. package/dist/src/Relation.js +127 -0
  97. package/dist/src/Resources.d.ts +118 -0
  98. package/dist/src/Resources.d.ts.map +1 -0
  99. package/dist/src/Resources.js +197 -0
  100. package/dist/src/Result.d.ts +189 -59
  101. package/dist/src/Result.d.ts.map +1 -1
  102. package/dist/src/Result.js +30 -241
  103. package/dist/src/Skiplist.js +2 -1
  104. package/dist/src/Sqlite.d.ts +89 -5
  105. package/dist/src/Sqlite.d.ts.map +1 -1
  106. package/dist/src/Sqlite.js +136 -9
  107. package/dist/src/Store.d.ts +0 -5
  108. package/dist/src/Store.d.ts.map +1 -1
  109. package/dist/src/Store.js +0 -5
  110. package/dist/src/Task.d.ts +580 -0
  111. package/dist/src/Task.d.ts.map +1 -0
  112. package/dist/src/Task.js +464 -0
  113. package/dist/src/Time.d.ts +66 -6
  114. package/dist/src/Time.d.ts.map +1 -1
  115. package/dist/src/Time.js +96 -7
  116. package/dist/src/Type.d.ts +677 -344
  117. package/dist/src/Type.d.ts.map +1 -1
  118. package/dist/src/Type.js +718 -467
  119. package/dist/src/Types.d.ts +38 -75
  120. package/dist/src/Types.d.ts.map +1 -1
  121. package/dist/src/WebSocket.d.ts +5 -7
  122. package/dist/src/WebSocket.d.ts.map +1 -1
  123. package/dist/src/WebSocket.js +12 -23
  124. package/dist/src/Worker.d.ts +39 -16
  125. package/dist/src/Worker.d.ts.map +1 -1
  126. package/dist/src/Worker.js +22 -9
  127. package/dist/src/index.d.ts +8 -3
  128. package/dist/src/index.d.ts.map +1 -1
  129. package/dist/src/index.js +8 -3
  130. package/package.json +14 -13
  131. package/src/Array.ts +396 -19
  132. package/src/Assert.ts +0 -35
  133. package/src/Brand.ts +75 -0
  134. package/src/Buffer.ts +7 -7
  135. package/src/Cache.ts +79 -0
  136. package/src/Callbacks.ts +62 -22
  137. package/src/Console.ts +92 -12
  138. package/src/Crypto.ts +99 -91
  139. package/src/Evolu/Db.ts +519 -1026
  140. package/src/Evolu/Diff.ts +7 -5
  141. package/src/Evolu/Evolu.ts +476 -360
  142. package/src/Evolu/Internal.ts +2 -4
  143. package/src/Evolu/LocalAuth.ts +463 -0
  144. package/src/Evolu/Owner.ts +355 -228
  145. package/src/Evolu/Platform.ts +9 -9
  146. package/src/Evolu/Protocol.ts +846 -742
  147. package/src/Evolu/Public.ts +8 -15
  148. package/src/Evolu/PublicKysely.ts +4 -5
  149. package/src/Evolu/Query.ts +3 -2
  150. package/src/Evolu/Relay.ts +406 -103
  151. package/src/Evolu/Schema.ts +323 -91
  152. package/src/Evolu/Storage.ts +559 -137
  153. package/src/Evolu/Sync.ts +819 -36
  154. package/src/Evolu/Timestamp.ts +90 -58
  155. package/src/Identicon.ts +197 -0
  156. package/src/Instances.ts +90 -0
  157. package/src/Number.ts +6 -10
  158. package/src/Object.ts +13 -5
  159. package/src/Order.ts +0 -6
  160. package/src/Platform.ts +20 -0
  161. package/src/Random.ts +3 -8
  162. package/src/Ref.ts +0 -5
  163. package/src/Relation.ts +234 -0
  164. package/src/Resources.ts +367 -0
  165. package/src/Result.ts +196 -61
  166. package/src/Skiplist.ts +1 -1
  167. package/src/Sqlite.ts +152 -17
  168. package/src/Store.ts +0 -5
  169. package/src/Task.ts +894 -0
  170. package/src/Time.ts +179 -10
  171. package/src/Type.ts +1136 -731
  172. package/src/Types.ts +43 -77
  173. package/src/WebSocket.ts +27 -31
  174. package/src/Worker.ts +72 -29
  175. package/src/index.ts +8 -3
  176. package/dist/src/Evolu/Config.d.ts +0 -69
  177. package/dist/src/Evolu/Config.d.ts.map +0 -1
  178. package/dist/src/Evolu/Config.js +0 -9
  179. package/dist/src/Evolu/Kysely.d.ts +0 -6
  180. package/dist/src/Evolu/Kysely.d.ts.map +0 -1
  181. package/dist/src/Evolu/Kysely.js +0 -21
  182. package/dist/src/ManyToManyMap.d.ts +0 -26
  183. package/dist/src/ManyToManyMap.d.ts.map +0 -1
  184. package/dist/src/ManyToManyMap.js +0 -92
  185. package/dist/src/NanoId.d.ts +0 -27
  186. package/dist/src/NanoId.d.ts.map +0 -1
  187. package/dist/src/NanoId.js +0 -6
  188. package/dist/src/Promise.d.ts +0 -180
  189. package/dist/src/Promise.d.ts.map +0 -1
  190. package/dist/src/Promise.js +0 -176
  191. package/src/Evolu/Config.ts +0 -83
  192. package/src/Evolu/Kysely.ts +0 -38
  193. package/src/ManyToManyMap.ts +0 -140
  194. package/src/NanoId.ts +0 -39
  195. package/src/Promise.ts +0 -295
package/src/Task.ts ADDED
@@ -0,0 +1,894 @@
1
+ import { isNonEmptyArray, shiftArray } from "./Array.js";
2
+ import { Result, err, ok } from "./Result.js";
3
+ import { Duration, durationToNonNegativeInt } from "./Time.js";
4
+ import { NonNegativeInt, PositiveInt } from "./Type.js";
5
+
6
+ /**
7
+ * `Task` is a function that creates and returns an optionally cancellable
8
+ * Promise using {@link Result}.
9
+ *
10
+ * The laziness allows safe composition, e.g. retry logic, because it prevents
11
+ * eager execution until the Task is actually invoked.
12
+ *
13
+ * ### Cancellation
14
+ *
15
+ * Tasks support optional cancellation via signal in {@link TaskContext}. When a
16
+ * Task is called without a signal, it cannot be cancelled and {@link AbortError}
17
+ * will never be returned. When called with a signal, the Task can be cancelled
18
+ * and AbortError is added to the error union with precise type safety.
19
+ *
20
+ * When composing Tasks, we typically have context and want to abort ASAP by
21
+ * passing it through. However, there are valid cases where we don't want to
22
+ * abort because we need some atomic unit to complete. For simple scripts and
23
+ * tests, omitting context is fine.
24
+ *
25
+ * ### Task Helpers
26
+ *
27
+ * - {@link toTask} - Convert async function to Task
28
+ * - {@link wait} - Delay execution for a specified {@link Duration}
29
+ * - {@link timeout} - Add timeout to any Task
30
+ * - {@link retry} - Retry failed Tasks with configurable backoff
31
+ *
32
+ * ### Example
33
+ *
34
+ * ```ts
35
+ * interface FetchError {
36
+ * readonly type: "FetchError";
37
+ * readonly error: unknown;
38
+ * }
39
+ *
40
+ * // Task version of fetch with proper error handling and cancellation support.
41
+ * const fetch = (url: string) =>
42
+ * toTask((context) =>
43
+ * tryAsync(
44
+ * () => globalThis.fetch(url, { signal: context?.signal ?? null }),
45
+ * (error): FetchError => ({ type: "FetchError", error }),
46
+ * ),
47
+ * );
48
+ *
49
+ * // `satisfies` shows the expected type signature.
50
+ * fetch satisfies (url: string) => Task<Response, FetchError>;
51
+ *
52
+ * // Add timeout to prevent hanging
53
+ * const fetchWithTimeout = (url: string) => timeout("30s", fetch(url));
54
+ *
55
+ * fetchWithTimeout satisfies (
56
+ * url: string,
57
+ * ) => Task<Response, TimeoutError | FetchError>;
58
+ *
59
+ * // Add retry for resilience
60
+ * const fetchWithRetry = (url: string) =>
61
+ * retry(
62
+ * {
63
+ * retries: PositiveInt.orThrow(3),
64
+ * initialDelay: "100ms",
65
+ * },
66
+ * fetchWithTimeout(url),
67
+ * );
68
+ *
69
+ * fetchWithRetry satisfies (
70
+ * url: string,
71
+ * ) => Task<
72
+ * Response,
73
+ * TimeoutError | FetchError | RetryError<TimeoutError | FetchError>
74
+ * >;
75
+ *
76
+ * const semaphore = createSemaphore(PositiveInt.orThrow(2));
77
+ *
78
+ * // Control concurrency with semaphore
79
+ * const fetchWithPermit = (url: string) =>
80
+ * semaphore.withPermit(fetchWithRetry(url));
81
+ *
82
+ * fetchWithPermit satisfies (url: string) => Task<
83
+ * Response,
84
+ * | TimeoutError
85
+ * | FetchError
86
+ * | AbortError // Semaphore dispose aborts Tasks
87
+ * | RetryError<TimeoutError | FetchError>
88
+ * >;
89
+ *
90
+ * // Usage
91
+ * const results = await Promise.all(
92
+ * [
93
+ * "https://api.example.com/users",
94
+ * "https://api.example.com/posts",
95
+ * "https://api.example.com/comments",
96
+ * ]
97
+ * .map(fetchWithPermit)
98
+ * .map((task) => task()),
99
+ * );
100
+ *
101
+ * results satisfies Array<
102
+ * Result<
103
+ * Response,
104
+ * | AbortError
105
+ * | TimeoutError
106
+ * | FetchError
107
+ * | RetryError<TimeoutError | FetchError>
108
+ * >
109
+ * >;
110
+ *
111
+ * // Handle results
112
+ * for (const result of results) {
113
+ * if (result.ok) {
114
+ * // Process successful response
115
+ * const response = result.value;
116
+ * expect(response).toBeInstanceOf(Response);
117
+ * } else {
118
+ * // Handle error (TimeoutError, FetchError, RetryError, or AbortError)
119
+ * expect(result.error).toBeDefined();
120
+ * }
121
+ * }
122
+ *
123
+ * // Cancellation support
124
+ * const controller = new AbortController();
125
+ * const cancelableTask = fetchWithPermit("https://api.example.com/data");
126
+ *
127
+ * // Start task
128
+ * const promise = cancelableTask(controller);
129
+ *
130
+ * // Cancel after some time
131
+ * setTimeout(() => {
132
+ * controller.abort("User cancelled");
133
+ * }, 1000);
134
+ *
135
+ * const _result = await promise;
136
+ * // Result will be AbortError if cancelled
137
+ * ```
138
+ *
139
+ * ### Dependency Injection Integration
140
+ *
141
+ * Tasks integrate naturally with Evolu's DI pattern. Use `deps` for static
142
+ * dependencies and `TaskContext` for execution context like cancellation. Usage
143
+ * follows the pattern: deps → arguments → execution context.
144
+ */
145
+ export interface Task<T, E> {
146
+ /**
147
+ * Invoke the Task.
148
+ *
149
+ * Provide a context with an AbortSignal to enable cancellation. When called
150
+ * without a signal, {@link AbortError} cannot occur and the error type narrows
151
+ * accordingly.
152
+ *
153
+ * ### Example
154
+ *
155
+ * ```ts
156
+ * interface FetchError {
157
+ * readonly type: "FetchError";
158
+ * readonly error: unknown;
159
+ * }
160
+ *
161
+ * // Task version of fetch with proper error handling and cancellation support.
162
+ * const fetch = (url: string) =>
163
+ * toTask((context) =>
164
+ * tryAsync(
165
+ * () => globalThis.fetch(url, { signal: context?.signal ?? null }),
166
+ * (error): FetchError => ({ type: "FetchError", error }),
167
+ * ),
168
+ * );
169
+ *
170
+ * // `satisfies` shows the expected type signature.
171
+ * fetch satisfies (url: string) => Task<Response, FetchError>;
172
+ *
173
+ * const result1 = await fetch("https://api.example.com/data")();
174
+ * expectTypeOf(result1).toEqualTypeOf<Result<Response, FetchError>>();
175
+ *
176
+ * // With AbortController
177
+ * const controller = new AbortController();
178
+ * const result2 = await fetch("https://api.example.com/data")(
179
+ * controller,
180
+ * );
181
+ * expectTypeOf(result2).toEqualTypeOf<
182
+ * Result<Response, FetchError | AbortError>
183
+ * >();
184
+ * ```
185
+ */
186
+ // eslint-disable-next-line @typescript-eslint/prefer-function-type
187
+ <TContext extends TaskContext | undefined = undefined>(
188
+ context?: TContext,
189
+ ): Promise<
190
+ Result<T, TContext extends { signal: AbortSignal } ? E | AbortError : E>
191
+ >;
192
+ }
193
+
194
+ /** Context passed to {@link Task}s for cancellation. */
195
+ export interface TaskContext {
196
+ /** Signal for cancellation */
197
+ readonly signal?: AbortSignal;
198
+ }
199
+
200
+ /** Error returned when a {@link Task} is cancelled via AbortSignal. */
201
+ export interface AbortError {
202
+ readonly type: "AbortError";
203
+ readonly reason?: unknown;
204
+ }
205
+
206
+ /** Narrower check to detect AbortError objects at runtime. */
207
+ const isAbortError = (error: unknown): error is AbortError =>
208
+ typeof error === "object" &&
209
+ error !== null &&
210
+ (error as { type?: unknown }).type === "AbortError";
211
+
212
+ // For React Native
213
+ if (typeof AbortSignal.any !== "function") {
214
+ AbortSignal.any = function (signals: Array<AbortSignal>): AbortSignal {
215
+ const controller = new AbortController();
216
+
217
+ const onAbort = (event: Event) => {
218
+ controller.abort((event.target as AbortSignal).reason);
219
+ cleanup();
220
+ };
221
+
222
+ const cleanup = () => {
223
+ for (const s of signals) s.removeEventListener("abort", onAbort);
224
+ };
225
+
226
+ for (const s of signals) {
227
+ if (s.aborted) {
228
+ controller.abort(s.reason);
229
+ return controller.signal;
230
+ }
231
+ s.addEventListener("abort", onAbort);
232
+ }
233
+
234
+ return controller.signal;
235
+ };
236
+ }
237
+
238
+ /**
239
+ * Combines user signal from context with an internal signal.
240
+ *
241
+ * If the context has a signal, combines both signals using AbortSignal.any().
242
+ * Otherwise, returns just the internal signal.
243
+ */
244
+ const combineSignal = (
245
+ context: TaskContext | undefined,
246
+ internalSignal: AbortSignal,
247
+ ): AbortSignal =>
248
+ context?.signal
249
+ ? AbortSignal.any([context.signal, internalSignal])
250
+ : internalSignal;
251
+
252
+ /**
253
+ * Converts async function returning {@link Result} to a {@link Task}.
254
+ *
255
+ * ### Example
256
+ *
257
+ * ```ts
258
+ * interface FetchError {
259
+ * readonly type: "FetchError";
260
+ * readonly error: unknown;
261
+ * }
262
+ *
263
+ * // Task version of fetch with proper error handling and cancellation support.
264
+ * const fetch = (url: string) =>
265
+ * toTask((context) =>
266
+ * tryAsync(
267
+ * () => globalThis.fetch(url, { signal: context?.signal ?? null }),
268
+ * (error): FetchError => ({ type: "FetchError", error }),
269
+ * ),
270
+ * );
271
+ *
272
+ * // `satisfies` shows the expected type signature.
273
+ * fetch satisfies (url: string) => Task<Response, FetchError>;
274
+ *
275
+ * const result1 = await fetch("https://api.example.com/data")();
276
+ * result1 satisfies Result<Response, FetchError>;
277
+ *
278
+ * // With AbortController
279
+ * const controller = new AbortController();
280
+ * const result2 = await fetch("https://api.example.com/data")(controller);
281
+ * result2 satisfies Result<Response, FetchError | AbortError>;
282
+ * ```
283
+ */
284
+ export const toTask = <T, E>(
285
+ fn: (context?: TaskContext) => Promise<Result<T, E>>,
286
+ ): Task<T, E> =>
287
+ // Note: Not using async to avoid Promise wrapper overhead in fast path
288
+ ((context) => {
289
+ const signal = context?.signal;
290
+
291
+ // Fast path when no signal – return promise directly
292
+ if (!signal) {
293
+ // Preserve future context fields (e.g., tracing) even without a signal
294
+ return fn(context);
295
+ }
296
+
297
+ if (signal.aborted) {
298
+ return Promise.resolve(
299
+ err({ type: "AbortError", reason: signal.reason as unknown }),
300
+ );
301
+ }
302
+
303
+ // Use Promise.withResolvers for clean abort handling and cleanup
304
+ const { promise: abortPromise, resolve: resolveAbort } =
305
+ Promise.withResolvers<Result<never, AbortError>>();
306
+
307
+ const handleAbort = () => {
308
+ resolveAbort(
309
+ err({ type: "AbortError", reason: signal.reason as unknown }),
310
+ );
311
+ };
312
+
313
+ signal.addEventListener("abort", handleAbort, { once: true });
314
+
315
+ // No finally: we expect no throws in normal flow; Result path removes listener.
316
+ // Unexpected throws indicate a bug and are allowed to crash (no recovery here).
317
+ return Promise.race([
318
+ abortPromise,
319
+ fn(context).then((result) => {
320
+ signal.removeEventListener("abort", handleAbort);
321
+ return result;
322
+ }),
323
+ ]);
324
+ }) as Task<T, E>;
325
+
326
+ // For React Native
327
+ if (typeof AbortSignal.timeout !== "function") {
328
+ AbortSignal.timeout = function (ms: number): AbortSignal {
329
+ const controller = new AbortController();
330
+ const id = setTimeout(() => {
331
+ controller.abort();
332
+ }, ms);
333
+ // clear timeout if aborted early
334
+ controller.signal.addEventListener("abort", () => {
335
+ clearTimeout(id);
336
+ });
337
+ return controller.signal;
338
+ };
339
+ }
340
+
341
+ /**
342
+ * Creates a {@link Task} that waits for the specified duration.
343
+ *
344
+ * ### Example
345
+ *
346
+ * ```ts
347
+ * const result1 = await wait("10ms")();
348
+ * result1 satisfies Result<void, never>;
349
+ *
350
+ * // With AbortController
351
+ * const controller = new AbortController();
352
+ * const result2 = await wait("10ms")(controller);
353
+ * result2 satisfies Result<void, AbortError>;
354
+ * ```
355
+ */
356
+ export const wait = (duration: Duration): Task<void, never> =>
357
+ toTask(
358
+ (context) =>
359
+ new Promise<Result<void, never>>((resolve) => {
360
+ const ms = durationToNonNegativeInt(duration);
361
+ const timeoutSignal = AbortSignal.timeout(ms);
362
+
363
+ const signal = combineSignal(context, timeoutSignal);
364
+
365
+ // Listen for abort - either from timeout completion or external abort
366
+ signal.addEventListener(
367
+ "abort",
368
+ () => {
369
+ resolve(ok());
370
+ },
371
+ { once: true },
372
+ );
373
+ }),
374
+ );
375
+
376
+ /** Error returned when {@link timeout} exceeds the specified duration. */
377
+ export interface TimeoutError {
378
+ readonly type: "TimeoutError";
379
+ readonly timeoutMs: number;
380
+ }
381
+
382
+ /**
383
+ * Adds timeout behavior to a {@link Task}.
384
+ *
385
+ * ### Example
386
+ *
387
+ * ```ts
388
+ * interface FetchError {
389
+ * readonly type: "FetchError";
390
+ * readonly error: unknown;
391
+ * }
392
+ *
393
+ * // Task version of fetch with proper error handling and cancellation support.
394
+ * const fetch = (url: string) =>
395
+ * toTask((context) =>
396
+ * tryAsync(
397
+ * () => globalThis.fetch(url, { signal: context?.signal ?? null }),
398
+ * (error): FetchError => ({ type: "FetchError", error }),
399
+ * ),
400
+ * );
401
+ *
402
+ * // `satisfies` shows the expected type signature.
403
+ * fetch satisfies (url: string) => Task<Response, FetchError>;
404
+ *
405
+ * const fetchWithTimeout = (url: string) => timeout("2m", fetch(url));
406
+ *
407
+ * const result1 = await fetchWithTimeout("https://api.example.com/data")();
408
+ * result1 satisfies Result<Response, FetchError | TimeoutError>;
409
+ *
410
+ * // With AbortController
411
+ * const controller = new AbortController();
412
+ * const result2 = await fetchWithTimeout("https://api.example.com/data")(
413
+ * controller,
414
+ * );
415
+ * result2 satisfies Result<
416
+ * Response,
417
+ * FetchError | TimeoutError | AbortError
418
+ * >;
419
+ * ```
420
+ */
421
+ export const timeout = <T, E>(
422
+ duration: Duration,
423
+ task: Task<T, E>,
424
+ ): Task<T, E | TimeoutError> =>
425
+ toTask(async (context) => {
426
+ const timeoutMs = durationToNonNegativeInt(duration);
427
+ const timeoutSignal = AbortSignal.timeout(timeoutMs);
428
+
429
+ const signal = combineSignal(context, timeoutSignal);
430
+
431
+ const result = await task({ signal });
432
+
433
+ if (timeoutSignal.aborted) {
434
+ return err({ type: "TimeoutError", timeoutMs });
435
+ }
436
+
437
+ return result as Result<T, E | TimeoutError>;
438
+ });
439
+
440
+ /** Options for configuring {@link retry} behavior. */
441
+ export interface RetryOptions<E> {
442
+ /** Number of retry attempts after the initial failure. */
443
+ readonly retries: PositiveInt;
444
+
445
+ /**
446
+ * Initial delay for exponential backoff (1st retry uses this, 2nd uses
447
+ * this×factor, 3rd uses this×factor², etc.). Actual delays are randomized by
448
+ * {@link RetryOptions.jitter}.
449
+ */
450
+ readonly initialDelay?: Duration;
451
+
452
+ /** Maximum delay between retries. */
453
+ readonly maxDelay?: Duration;
454
+
455
+ /** Exponential backoff multiplier. */
456
+ readonly factor?: number;
457
+
458
+ /** Random jitter factor (0-1) to prevent thundering herd. */
459
+ readonly jitter?: number;
460
+
461
+ /**
462
+ * Predicate to determine if error should trigger retry. Receives AbortError
463
+ * too.
464
+ */
465
+ readonly retryable?: (error: E | AbortError) => boolean;
466
+
467
+ /** Callback invoked before each retry attempt. */
468
+ readonly onRetry?: (error: E, attempt: number, delay: number) => void;
469
+ }
470
+
471
+ /** Error returned when {@link retry} exhausts all retry attempts. */
472
+ export interface RetryError<E> {
473
+ readonly type: "RetryError";
474
+ readonly cause: E;
475
+ readonly attempts: number;
476
+ }
477
+
478
+ /**
479
+ * Adds retry logic with exponential backoff and jitter to a {@link Task}.
480
+ *
481
+ * ### Example
482
+ *
483
+ * ```ts
484
+ * interface FetchError {
485
+ * readonly type: "FetchError";
486
+ * readonly error: unknown;
487
+ * }
488
+ *
489
+ * // Task version of fetch with proper error handling and cancellation support.
490
+ * const fetch = (url: string) =>
491
+ * toTask((context) =>
492
+ * tryAsync(
493
+ * () => globalThis.fetch(url, { signal: context?.signal ?? null }),
494
+ * (error): FetchError => ({ type: "FetchError", error }),
495
+ * ),
496
+ * );
497
+ *
498
+ * // `satisfies` shows the expected type signature.
499
+ * fetch satisfies (url: string) => Task<Response, FetchError>;
500
+ *
501
+ * const fetchWithRetry = (url: string) =>
502
+ * retry({ retries: PositiveInt.orThrow(3) }, fetch(url));
503
+ *
504
+ * const result1 = await fetchWithRetry("https://api.example.com/data")();
505
+ * result1 satisfies Result<Response, FetchError | RetryError<FetchError>>;
506
+ *
507
+ * // With AbortController
508
+ * const controller = new AbortController();
509
+ * const result2 = await fetchWithRetry("https://api.example.com/data")(
510
+ * controller,
511
+ * );
512
+ * result2 satisfies Result<
513
+ * Response,
514
+ * FetchError | RetryError<FetchError> | AbortError
515
+ * >;
516
+ * ```
517
+ */
518
+ export const retry = <T, E>(
519
+ {
520
+ retries,
521
+ initialDelay = "1s",
522
+ maxDelay = "30s",
523
+ factor = 2,
524
+ jitter = 0.5,
525
+ retryable = (error: E | AbortError) => !isAbortError(error),
526
+ onRetry,
527
+ }: RetryOptions<E>,
528
+ task: Task<T, E>,
529
+ ): Task<T, E | RetryError<E>> =>
530
+ toTask(async (context): Promise<Result<T, E | RetryError<E>>> => {
531
+ const initialDelayMs = durationToNonNegativeInt(initialDelay);
532
+ const maxDelayMs = durationToNonNegativeInt(maxDelay);
533
+ const maxRetries = PositiveInt.orThrow(retries);
534
+
535
+ let attempt = 0;
536
+
537
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
538
+ while (true) {
539
+ const result = await task(context);
540
+
541
+ if (result.ok) {
542
+ return result;
543
+ }
544
+
545
+ // Never retry on AbortError; propagate it directly
546
+ if (isAbortError(result.error)) {
547
+ return err(result.error) as Result<T, E | RetryError<E>>;
548
+ }
549
+
550
+ attempt += 1;
551
+
552
+ if (attempt > maxRetries || !retryable(result.error)) {
553
+ return err({
554
+ type: "RetryError",
555
+ cause: result.error,
556
+ attempts: attempt,
557
+ });
558
+ }
559
+
560
+ // Calculate delay with exponential backoff
561
+ const exponentialDelay = initialDelayMs * Math.pow(factor, attempt - 1);
562
+ const cappedDelay = Math.min(exponentialDelay, maxDelayMs);
563
+
564
+ // Apply jitter to prevent thundering herd problem
565
+ const randomFactor = 1 - jitter + Math.random() * jitter * 2;
566
+ const delay = Math.floor(cappedDelay * randomFactor);
567
+
568
+ if (onRetry) {
569
+ onRetry(result.error, attempt, delay);
570
+ }
571
+
572
+ // Wait before retry
573
+ const delayResult = await wait(NonNegativeInt.orThrow(delay))(context);
574
+ if (!delayResult.ok) {
575
+ // If delay was aborted, return AbortError (will be handled by toTask)
576
+ return delayResult;
577
+ }
578
+ }
579
+ });
580
+
581
+ /**
582
+ * A semaphore that limits the number of concurrent async Tasks.
583
+ *
584
+ * For mutual exclusion (limiting to exactly one Task), consider using
585
+ * {@link Mutex} instead.
586
+ *
587
+ * @see {@link createSemaphore} to create a semaphore instance.
588
+ */
589
+ export interface Semaphore extends Disposable {
590
+ /**
591
+ * Executes a Task while holding a semaphore permit.
592
+ *
593
+ * The Task will wait until a permit is available before executing. Supports
594
+ * cancellation via AbortSignal - if the signal is aborted while waiting for a
595
+ * permit or during execution, the Task is cancelled and permits are properly
596
+ * released.
597
+ */
598
+ readonly withPermit: <T, E>(task: Task<T, E>) => Task<T, E | AbortError>;
599
+ }
600
+
601
+ /**
602
+ * Creates a semaphore that limits concurrent async Tasks to the specified
603
+ * count.
604
+ *
605
+ * A semaphore controls access to a resource by maintaining a count of available
606
+ * permits. Tasks acquire a permit before executing and release it when
607
+ * complete.
608
+ *
609
+ * For mutual exclusion (exactly one Task at a time), consider using
610
+ * {@link createMutex} instead.
611
+ *
612
+ * ### Example
613
+ *
614
+ * ```ts
615
+ * // Allow maximum 3 concurrent Tasks
616
+ * const semaphore = createSemaphore(PositiveInt.orThrow(3));
617
+ *
618
+ * let currentConcurrent = 0;
619
+ * const events: Array<string> = [];
620
+ *
621
+ * const fetchData = (id: number) =>
622
+ * toTask<number, never>(async (context) => {
623
+ * currentConcurrent++;
624
+ * events.push(`start ${id} (concurrent: ${currentConcurrent})`);
625
+ *
626
+ * await wait("10ms")(context);
627
+ *
628
+ * currentConcurrent--;
629
+ * events.push(`end ${id} (concurrent: ${currentConcurrent})`);
630
+ * return ok(id * 10);
631
+ * });
632
+ *
633
+ * // These will execute with at most 3 running concurrently
634
+ * const results = await Promise.all([
635
+ * semaphore.withPermit(fetchData(1))(),
636
+ * semaphore.withPermit(fetchData(2))(),
637
+ * semaphore.withPermit(fetchData(3))(),
638
+ * semaphore.withPermit(fetchData(4))(), // waits for one above to complete
639
+ * semaphore.withPermit(fetchData(5))(), // waits for permit
640
+ * ]);
641
+ *
642
+ * expect(results.map(getOrThrow)).toEqual([10, 20, 30, 40, 50]);
643
+ * expect(events).toMatchInlineSnapshot(`
644
+ * [
645
+ * "start 1 (concurrent: 1)",
646
+ * "start 2 (concurrent: 2)",
647
+ * "start 3 (concurrent: 3)",
648
+ * "end 1 (concurrent: 2)",
649
+ * "start 4 (concurrent: 3)",
650
+ * "end 2 (concurrent: 2)",
651
+ * "start 5 (concurrent: 3)",
652
+ * "end 3 (concurrent: 2)",
653
+ * "end 4 (concurrent: 1)",
654
+ * "end 5 (concurrent: 0)",
655
+ * ]
656
+ * `);
657
+ * ```
658
+ */
659
+ export const createSemaphore = (maxConcurrent: PositiveInt): Semaphore => {
660
+ let isDisposed = false;
661
+ let availablePermits = maxConcurrent;
662
+ const waitingQueue: Array<() => void> = [];
663
+ const semaphoreController = new AbortController();
664
+
665
+ const acquire = (): Promise<void> => {
666
+ if (availablePermits > 0) {
667
+ availablePermits--;
668
+ return Promise.resolve();
669
+ }
670
+
671
+ return new Promise<void>((resolve) => {
672
+ waitingQueue.push(resolve);
673
+ });
674
+ };
675
+
676
+ const release = (): void => {
677
+ if (isNonEmptyArray(waitingQueue)) {
678
+ shiftArray(waitingQueue)();
679
+ } else {
680
+ availablePermits++;
681
+ }
682
+ };
683
+
684
+ return {
685
+ withPermit: <T, E>(task: Task<T, E>): Task<T, E | AbortError> =>
686
+ toTask(async (context): Promise<Result<T, E | AbortError>> => {
687
+ await acquire();
688
+
689
+ // Check if semaphore was disposed while waiting
690
+ if (isDisposed) {
691
+ return err({
692
+ type: "AbortError",
693
+ reason: "Semaphore disposed",
694
+ });
695
+ }
696
+
697
+ const signal = combineSignal(context, semaphoreController.signal);
698
+
699
+ const result = await task({ signal });
700
+
701
+ release();
702
+
703
+ return result;
704
+ }),
705
+
706
+ [Symbol.dispose]: () => {
707
+ if (isDisposed) return;
708
+ isDisposed = true;
709
+
710
+ // Cancel all running and waiting tasks
711
+ semaphoreController.abort("Semaphore disposed");
712
+
713
+ // Release all waiting tasks so they can continue and check isDisposed
714
+ while (isNonEmptyArray(waitingQueue)) {
715
+ shiftArray(waitingQueue)();
716
+ }
717
+ },
718
+ };
719
+ };
720
+
721
+ /**
722
+ * A mutex (mutual exclusion) that ensures only one Task runs at a time.
723
+ *
724
+ * This is a specialized version of a {@link Semaphore} with a permit count of 1.
725
+ *
726
+ * @see {@link createMutex} to create a mutex instance.
727
+ */
728
+ export interface Mutex extends Disposable {
729
+ /**
730
+ * Executes a Task while holding the mutex lock.
731
+ *
732
+ * Only one Task can hold the lock at a time. Other Tasks will wait until the
733
+ * lock is released. Supports cancellation via AbortSignal.
734
+ */
735
+ readonly withLock: <T, E>(task: Task<T, E>) => Task<T, E | AbortError>;
736
+ }
737
+
738
+ /**
739
+ * Creates a new mutex for ensuring mutual exclusion.
740
+ *
741
+ * A mutex is a {@link createSemaphore} with exactly one permit, ensuring that
742
+ * only one Task can execute at a time.
743
+ *
744
+ * ### Example
745
+ *
746
+ * ```ts
747
+ * const mutex = createMutex();
748
+ *
749
+ * const updateTask = (id: number) =>
750
+ * toTask((context) =>
751
+ * tryAsync(
752
+ * () => updateSharedResource(id, context),
753
+ * (error): UpdateError => ({ type: "UpdateError", error }),
754
+ * ),
755
+ * );
756
+ *
757
+ * // These Tasks will execute one at a time
758
+ * const results = await Promise.all([
759
+ * mutex.withLock(updateTask(1))(),
760
+ * mutex.withLock(updateTask(2))(),
761
+ * mutex.withLock(updateTask(3))(),
762
+ * ]);
763
+ * ```
764
+ */
765
+ export const createMutex = (): Mutex => {
766
+ const mutex = createSemaphore(PositiveInt.orThrow(1));
767
+
768
+ return {
769
+ withLock: mutex.withPermit,
770
+ [Symbol.dispose]: mutex[Symbol.dispose],
771
+ };
772
+ };
773
+
774
+ /**
775
+ * Schedule a task to run after all interactions (animations, gestures,
776
+ * navigation) have completed.
777
+ *
778
+ * This uses `requestIdleCallback` when available, otherwise falls back to
779
+ * `setTimeout(0)` for cross-platform compatibility.
780
+ *
781
+ * ### Example
782
+ *
783
+ * ```ts
784
+ * const processDataTask: Task<void, ProcessError> = toTask(async () => {
785
+ * // Heavy processing work
786
+ * return ok();
787
+ * });
788
+ *
789
+ * // Schedule the task to run when idle
790
+ * void requestIdleTask(processDataTask)();
791
+ * ```
792
+ */
793
+ export const requestIdleTask = <T, E>(task: Task<T, E>): Task<T, E> =>
794
+ toTask(
795
+ async (context?: TaskContext) =>
796
+ new Promise<Result<T, E>>((resolve) => {
797
+ idleCallback(() => {
798
+ void task(context).then(resolve);
799
+ });
800
+ }),
801
+ );
802
+
803
+ const idleCallback: (callback: () => void) => void =
804
+ typeof globalThis.requestIdleCallback === "function"
805
+ ? globalThis.requestIdleCallback
806
+ : (callback) => setTimeout(callback, 0);
807
+
808
+ /**
809
+ * Represents a value that can be either synchronous or asynchronous.
810
+ *
811
+ * This type is useful for functions that may complete synchronously or
812
+ * asynchronously depending on runtime conditions (e.g., cache hit vs network
813
+ * fetch).
814
+ *
815
+ * ### Why MaybeAsync?
816
+ *
817
+ * When a function can be sync or async, the typical approaches are:
818
+ *
819
+ * 1. **Always return Promise** - Simple but forces microtask overhead even for
820
+ * sync values (see "await always adds microtask" test in Task.test.ts)
821
+ * 2. **Use callbacks** - Can avoid microtask, but calling code must still `await`
822
+ * for sane composition, which adds microtask anyway
823
+ * 3. **Return `T | PromiseLike<T>`** - Calling code can check the value and only
824
+ * `await` when needed, avoiding microtask overhead for sync cases
825
+ *
826
+ * The third approach (MaybeAsync) provides:
827
+ *
828
+ * - **Performance**: No microtask overhead for synchronous operations
829
+ * - **Reliability**: No interleaving via microtask queue when operations are
830
+ * _synchronous_, reducing need for mutexes to protect shared state
831
+ *
832
+ * ### Example
833
+ *
834
+ * ```ts
835
+ * // Function that may be sync or async
836
+ * const getData = (id: string): MaybeAsync<Data> => {
837
+ * const cached = cache.get(id);
838
+ * if (cached) return cached; // Sync path
839
+ * return fetchData(id); // Async path
840
+ * };
841
+ *
842
+ * // Caller can optimize based on actual behavior
843
+ * const result = getData(id);
844
+ * const data = isAsync(result) ? await result : result;
845
+ * ```
846
+ *
847
+ * ### Alternative Approaches
848
+ *
849
+ * It's possible to eliminate the sync/async distinction using complex
850
+ * frameworks with custom schedulers. However, such frameworks require depending
851
+ * on other people's code that controls how your code executes, resulting in
852
+ * more complex stack traces and debugging experiences. With MaybeAsync, we
853
+ * don't need that machinery - it works directly with JavaScript's native
854
+ * primitives and TypeScript's type system.
855
+ *
856
+ * ### TODO: Consider
857
+ *
858
+ * Use MaybeAsync in Task and Task helpers to preserve synchronous execution
859
+ * when possible (e.g., mutex with available permit, retry on first success).
860
+ */
861
+ export type MaybeAsync<T> = T | PromiseLike<T>;
862
+
863
+ /**
864
+ * Type guard to check if a {@link MaybeAsync} value is async (a promise).
865
+ *
866
+ * This function narrows the type of a {@link MaybeAsync} value, allowing you to
867
+ * conditionally `await` only when necessary.
868
+ *
869
+ * ### Example
870
+ *
871
+ * ```ts
872
+ * const getData = (id: string): MaybeAsync<Data> => {
873
+ * const cached = cache.get(id);
874
+ * if (cached) return cached; // Sync path
875
+ * return fetchData(id); // Async path
876
+ * };
877
+ *
878
+ * const result = getData(id);
879
+ * const data = isAsync(result) ? await result : result;
880
+ * // No microtask overhead when cached!
881
+ * ```
882
+ */
883
+ export const isAsync = <T>(
884
+ value: MaybeAsync<T>,
885
+ ): value is T extends PromiseLike<unknown> ? never : PromiseLike<T> =>
886
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
887
+ typeof (value as any)?.then === "function";
888
+
889
+ // TODO: Add tracing support
890
+ // - Extend TaskContext with optional tracing field
891
+ // - Add traced(name, task) helper that wraps Task execution
892
+ // - Collect span data (name, timing, parent-child relationships, status)
893
+ // - Support OpenTelemetry export format with proper traceId/spanId generation
894
+ // - Automatic parent-child span relationships through context propagation