@nlozgachev/pipelined 0.20.0 → 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.
package/dist/core.js CHANGED
@@ -24,6 +24,7 @@ __export(Core_exports, {
24
24
  Lens: () => Lens,
25
25
  Logged: () => Logged,
26
26
  Maybe: () => Maybe,
27
+ Op: () => Op,
27
28
  Optional: () => Optional,
28
29
  Predicate: () => Predicate,
29
30
  Reader: () => Reader,
@@ -43,15 +44,13 @@ __export(Core_exports, {
43
44
  module.exports = __toCommonJS(Core_exports);
44
45
 
45
46
  // src/Core/Deferred.ts
46
- var _store = /* @__PURE__ */ new WeakMap();
47
47
  var Deferred;
48
48
  ((Deferred2) => {
49
- Deferred2.fromPromise = (p) => {
50
- const d = { then: ((f) => p.then(f)) };
51
- _store.set(d, p);
52
- return d;
53
- };
54
- Deferred2.toPromise = (d) => _store.get(d) ?? new Promise((resolve) => d.then(resolve));
49
+ Deferred2.fromPromise = (p) => (
50
+ // eslint-disable-next-line unicorn/no-thenable -- Deferred is intentionally thenable; it is the mechanism that makes Task awaitable
51
+ { then: ((f) => p.then(f)) }
52
+ );
53
+ Deferred2.toPromise = (d) => new Promise((resolve) => d.then(resolve));
55
54
  })(Deferred || (Deferred = {}));
56
55
 
57
56
  // src/Core/Lens.ts
@@ -161,6 +160,880 @@ var Maybe;
161
160
  Maybe2.ap = (arg) => (data) => (0, Maybe2.isSome)(data) && (0, Maybe2.isSome)(arg) ? (0, Maybe2.some)(data.value(arg.value)) : (0, Maybe2.none)();
162
161
  })(Maybe || (Maybe = {}));
163
162
 
163
+ // src/internal/Op.util.ts
164
+ var _abortedNil = { kind: "Nil", reason: "aborted" };
165
+ var _droppedNil = { kind: "Nil", reason: "dropped" };
166
+ var _replacedNil = { kind: "Nil", reason: "replaced" };
167
+ var _evictedNil = { kind: "Nil", reason: "evicted" };
168
+ var _idle = { kind: "Idle" };
169
+ var _pending = { kind: "Pending" };
170
+ var ok = (value) => ({ kind: "Ok", value });
171
+ var err = (error) => ({ kind: "Err", error });
172
+ var cancellableWait = (ms, signal) => {
173
+ if (ms <= 0) return Promise.resolve();
174
+ return new Promise((resolve) => {
175
+ const id = setTimeout(resolve, ms);
176
+ signal.addEventListener("abort", () => {
177
+ clearTimeout(id);
178
+ resolve();
179
+ }, { once: true });
180
+ });
181
+ };
182
+ var runWithRetry = (op, input, signal, options, onRetrying) => {
183
+ const { attempts, backoff, when: shouldRetry } = options;
184
+ const getDelay = (n) => backoff === void 0 ? 0 : typeof backoff === "function" ? backoff(n) : backoff;
185
+ const attempt = async (left) => {
186
+ const result = await Deferred.toPromise(op._factory(input, signal));
187
+ if (result === null || signal.aborted) return null;
188
+ if (result.kind === "Ok") return result;
189
+ if (left <= 1) return result;
190
+ if (shouldRetry !== void 0 && !shouldRetry(result.error)) return result;
191
+ const attemptNumber = attempts - left + 1;
192
+ const ms = getDelay(attemptNumber);
193
+ onRetrying({
194
+ kind: "Retrying",
195
+ attempt: attemptNumber,
196
+ lastError: result.error,
197
+ ...ms > 0 ? { nextRetryIn: ms } : {}
198
+ });
199
+ await cancellableWait(ms, signal);
200
+ if (signal.aborted) return null;
201
+ return attempt(left - 1);
202
+ };
203
+ return attempt(attempts);
204
+ };
205
+ var execute = (op, input, controller, retryOptions, timeoutOptions, onRetrying) => {
206
+ const { signal } = controller;
207
+ const toOutcome = (r) => r === null ? _abortedNil : r.kind === "Ok" ? ok(r.value) : err(r.error);
208
+ const runPromise = retryOptions !== void 0 && onRetrying !== void 0 ? runWithRetry(op, input, signal, retryOptions, onRetrying).then(toOutcome) : Deferred.toPromise(op._factory(input, signal)).then(toOutcome);
209
+ if (timeoutOptions === void 0) return Deferred.fromPromise(runPromise);
210
+ let timerId;
211
+ return Deferred.fromPromise(Promise.race([
212
+ runPromise.then((outcome) => {
213
+ clearTimeout(timerId);
214
+ return outcome;
215
+ }),
216
+ new Promise((resolve) => {
217
+ timerId = setTimeout(() => {
218
+ controller.abort();
219
+ resolve(err(timeoutOptions.onTimeout()));
220
+ }, timeoutOptions.ms);
221
+ })
222
+ ]));
223
+ };
224
+ var makeRestartable = (op, minInterval, retryOptions, timeoutOptions) => {
225
+ let currentState = _idle;
226
+ let currentController;
227
+ let currentResolve;
228
+ let waitController;
229
+ let lastStartTime = 0;
230
+ const subscribers = /* @__PURE__ */ new Set();
231
+ const emit = (state) => {
232
+ currentState = state;
233
+ subscribers.forEach((cb) => cb(state));
234
+ };
235
+ const run = (input) => Deferred.fromPromise(
236
+ new Promise((resolve) => {
237
+ waitController?.abort();
238
+ waitController = void 0;
239
+ currentController?.abort();
240
+ const prev = currentResolve;
241
+ currentResolve = resolve;
242
+ currentController = new AbortController();
243
+ const controller = currentController;
244
+ prev?.(_replacedNil);
245
+ const startExecution = () => {
246
+ if (currentController !== controller) return;
247
+ lastStartTime = Date.now();
248
+ emit(_pending);
249
+ const onRetrying = retryOptions ? (r) => {
250
+ if (currentController === controller) emit(r);
251
+ } : void 0;
252
+ execute(op, input, controller, retryOptions, timeoutOptions, onRetrying).then((outcome) => {
253
+ if (currentController !== controller) return;
254
+ const r = currentResolve;
255
+ currentResolve = void 0;
256
+ currentController = void 0;
257
+ emit(outcome);
258
+ r?.(outcome);
259
+ });
260
+ };
261
+ const gap = minInterval !== void 0 ? Math.max(0, minInterval - (Date.now() - lastStartTime)) : 0;
262
+ if (gap > 0) {
263
+ waitController = new AbortController();
264
+ const wc = waitController;
265
+ cancellableWait(gap, wc.signal).then(() => {
266
+ if (waitController === wc) waitController = void 0;
267
+ startExecution();
268
+ });
269
+ } else {
270
+ startExecution();
271
+ }
272
+ })
273
+ );
274
+ const abort = () => {
275
+ waitController?.abort();
276
+ waitController = void 0;
277
+ currentController?.abort();
278
+ currentController = void 0;
279
+ const r = currentResolve;
280
+ currentResolve = void 0;
281
+ if (currentState.kind !== "Idle") emit(_abortedNil);
282
+ r?.(_abortedNil);
283
+ };
284
+ return {
285
+ get state() {
286
+ return currentState;
287
+ },
288
+ run,
289
+ abort,
290
+ subscribe: (cb) => {
291
+ subscribers.add(cb);
292
+ if (currentState.kind !== "Idle") cb(currentState);
293
+ return () => subscribers.delete(cb);
294
+ }
295
+ };
296
+ };
297
+ var makeExclusive = (op, cooldown, retryOptions, timeoutOptions) => {
298
+ let currentState = _idle;
299
+ let currentController;
300
+ let currentResolve;
301
+ let cooldownTimer;
302
+ const subscribers = /* @__PURE__ */ new Set();
303
+ const emit = (state) => {
304
+ currentState = state;
305
+ subscribers.forEach((cb) => cb(state));
306
+ };
307
+ const run = (input) => {
308
+ if (currentController !== void 0 || cooldownTimer !== void 0) {
309
+ return Deferred.fromPromise(Promise.resolve(_droppedNil));
310
+ }
311
+ return Deferred.fromPromise(
312
+ new Promise((resolve) => {
313
+ currentResolve = resolve;
314
+ currentController = new AbortController();
315
+ const controller = currentController;
316
+ emit(_pending);
317
+ const onRetrying = retryOptions ? (r) => {
318
+ if (currentController === controller) emit(r);
319
+ } : void 0;
320
+ execute(op, input, controller, retryOptions, timeoutOptions, onRetrying).then((outcome) => {
321
+ if (currentController !== controller) return;
322
+ const r = currentResolve;
323
+ currentResolve = void 0;
324
+ currentController = void 0;
325
+ emit(outcome);
326
+ r?.(outcome);
327
+ if (cooldown !== void 0 && cooldown > 0) {
328
+ cooldownTimer = setTimeout(() => {
329
+ cooldownTimer = void 0;
330
+ }, cooldown);
331
+ }
332
+ });
333
+ })
334
+ );
335
+ };
336
+ const abort = () => {
337
+ if (cooldownTimer !== void 0) {
338
+ clearTimeout(cooldownTimer);
339
+ cooldownTimer = void 0;
340
+ }
341
+ currentController?.abort();
342
+ currentController = void 0;
343
+ const r = currentResolve;
344
+ currentResolve = void 0;
345
+ if (currentState.kind !== "Idle") emit(_abortedNil);
346
+ r?.(_abortedNil);
347
+ };
348
+ return {
349
+ get state() {
350
+ return currentState;
351
+ },
352
+ run,
353
+ abort,
354
+ subscribe: (cb) => {
355
+ subscribers.add(cb);
356
+ if (currentState.kind !== "Idle") cb(currentState);
357
+ return () => subscribers.delete(cb);
358
+ }
359
+ };
360
+ };
361
+ var makeQueue = (op, maxSize, overflow, concurrency, dedupe, retryOptions, timeoutOptions) => {
362
+ const maxConcurrency = concurrency ?? 1;
363
+ let currentState = _idle;
364
+ let generation = 0;
365
+ let inFlight = 0;
366
+ const queue = [];
367
+ const inflightControllers = /* @__PURE__ */ new Set();
368
+ const inflightResolvers = [];
369
+ const subscribers = /* @__PURE__ */ new Set();
370
+ const emit = (state) => {
371
+ currentState = state;
372
+ subscribers.forEach((cb) => cb(state));
373
+ };
374
+ const startOne = (input, resolve, myGeneration) => {
375
+ inFlight++;
376
+ const controller = new AbortController();
377
+ inflightControllers.add(controller);
378
+ inflightResolvers.push(resolve);
379
+ emit(_pending);
380
+ const onRetrying = retryOptions ? (r) => {
381
+ if (generation === myGeneration && inflightControllers.has(controller)) emit(r);
382
+ } : void 0;
383
+ execute(op, input, controller, retryOptions, timeoutOptions, onRetrying).then((outcome) => {
384
+ inflightControllers.delete(controller);
385
+ const idx = inflightResolvers.indexOf(resolve);
386
+ if (idx !== -1) inflightResolvers.splice(idx, 1);
387
+ if (generation !== myGeneration) {
388
+ resolve(_abortedNil);
389
+ return;
390
+ }
391
+ inFlight--;
392
+ emit(outcome);
393
+ resolve(outcome);
394
+ if (queue.length > 0) {
395
+ const next = queue.shift();
396
+ startOne(next.input, next.resolve, generation);
397
+ }
398
+ });
399
+ };
400
+ const run = (input) => {
401
+ const myGeneration = generation;
402
+ if (dedupe !== void 0) {
403
+ const idx = queue.findIndex((item) => dedupe(input, item.input));
404
+ if (idx !== -1) {
405
+ const dup = queue.splice(idx, 1)[0];
406
+ dup.resolve(_droppedNil);
407
+ }
408
+ }
409
+ if (inFlight < maxConcurrency) {
410
+ return Deferred.fromPromise(
411
+ new Promise((resolve) => {
412
+ startOne(input, resolve, myGeneration);
413
+ })
414
+ );
415
+ }
416
+ if (maxSize === void 0 || queue.length < maxSize) {
417
+ return Deferred.fromPromise(
418
+ new Promise((resolve) => {
419
+ queue.push({ input, resolve });
420
+ emit({ kind: "Queued", position: queue.length - 1 });
421
+ })
422
+ );
423
+ }
424
+ if (overflow === "replace-last") {
425
+ return Deferred.fromPromise(
426
+ new Promise((resolve) => {
427
+ const tail = queue.pop();
428
+ tail.resolve(_evictedNil);
429
+ queue.push({ input, resolve });
430
+ emit({ kind: "Queued", position: queue.length - 1 });
431
+ })
432
+ );
433
+ }
434
+ return Deferred.fromPromise(Promise.resolve(_droppedNil));
435
+ };
436
+ const abort = () => {
437
+ generation++;
438
+ inflightControllers.forEach((c) => c.abort());
439
+ inflightControllers.clear();
440
+ const toResolve = inflightResolvers.splice(0);
441
+ const queuedResolvers = queue.splice(0).map((item) => item.resolve);
442
+ inFlight = 0;
443
+ if (currentState.kind !== "Idle") emit(_abortedNil);
444
+ toResolve.forEach((r) => r(_abortedNil));
445
+ queuedResolvers.forEach((r) => r(_abortedNil));
446
+ };
447
+ return {
448
+ get state() {
449
+ return currentState;
450
+ },
451
+ run,
452
+ abort,
453
+ subscribe: (cb) => {
454
+ subscribers.add(cb);
455
+ if (currentState.kind !== "Idle") cb(currentState);
456
+ return () => subscribers.delete(cb);
457
+ }
458
+ };
459
+ };
460
+ var makeBuffered = (op, size, retryOptions, timeoutOptions) => {
461
+ const bufferSize = size ?? 1;
462
+ let currentState = _idle;
463
+ let currentController;
464
+ let currentResolve;
465
+ const buffer = [];
466
+ const subscribers = /* @__PURE__ */ new Set();
467
+ const emit = (state) => {
468
+ currentState = state;
469
+ subscribers.forEach((cb) => cb(state));
470
+ };
471
+ const startRun = (input, resolve) => {
472
+ currentResolve = resolve;
473
+ currentController = new AbortController();
474
+ const controller = currentController;
475
+ emit(_pending);
476
+ const onRetrying = retryOptions ? (r) => {
477
+ if (currentController === controller) emit(r);
478
+ } : void 0;
479
+ execute(op, input, controller, retryOptions, timeoutOptions, onRetrying).then((outcome) => {
480
+ if (currentController !== controller) return;
481
+ const r = currentResolve;
482
+ currentResolve = void 0;
483
+ currentController = void 0;
484
+ emit(outcome);
485
+ r?.(outcome);
486
+ if (buffer.length > 0) {
487
+ const next = buffer.shift();
488
+ startRun(next.input, next.resolve);
489
+ }
490
+ });
491
+ };
492
+ const run = (input) => Deferred.fromPromise(
493
+ new Promise((resolve) => {
494
+ if (currentController === void 0) {
495
+ startRun(input, resolve);
496
+ } else if (buffer.length < bufferSize) {
497
+ buffer.push({ input, resolve });
498
+ emit({ kind: "Queued", position: buffer.length - 1 });
499
+ } else {
500
+ const evicted = buffer.shift();
501
+ evicted.resolve(_evictedNil);
502
+ buffer.push({ input, resolve });
503
+ emit({ kind: "Queued", position: buffer.length - 1 });
504
+ }
505
+ })
506
+ );
507
+ const abort = () => {
508
+ currentController?.abort();
509
+ currentController = void 0;
510
+ const cr = currentResolve;
511
+ currentResolve = void 0;
512
+ const bufferedResolvers = buffer.splice(0).map((item) => item.resolve);
513
+ if (currentState.kind !== "Idle") emit(_abortedNil);
514
+ cr?.(_abortedNil);
515
+ bufferedResolvers.forEach((r) => r(_abortedNil));
516
+ };
517
+ return {
518
+ get state() {
519
+ return currentState;
520
+ },
521
+ run,
522
+ abort,
523
+ subscribe: (cb) => {
524
+ subscribers.add(cb);
525
+ if (currentState.kind !== "Idle") cb(currentState);
526
+ return () => subscribers.delete(cb);
527
+ }
528
+ };
529
+ };
530
+ var makeDebounced = (op, ms, leading, maxWait, retryOptions, timeoutOptions) => {
531
+ let currentState = _idle;
532
+ let currentController;
533
+ let currentResolve;
534
+ let leadingController;
535
+ let leadingResolve;
536
+ let pendingResolve;
537
+ let timerId;
538
+ let pendingInput;
539
+ let firstCallAt = 0;
540
+ const subscribers = /* @__PURE__ */ new Set();
541
+ const emit = (state) => {
542
+ currentState = state;
543
+ subscribers.forEach((cb) => cb(state));
544
+ };
545
+ const fireLeading = (input, resolve) => {
546
+ leadingController = new AbortController();
547
+ const controller = leadingController;
548
+ leadingResolve = resolve;
549
+ emit(_pending);
550
+ const onRetrying = retryOptions ? (r) => {
551
+ if (leadingController === controller) emit(r);
552
+ } : void 0;
553
+ execute(op, input, controller, retryOptions, timeoutOptions, onRetrying).then((outcome) => {
554
+ if (leadingController !== controller) return;
555
+ const r = leadingResolve;
556
+ leadingResolve = void 0;
557
+ leadingController = void 0;
558
+ emit(outcome);
559
+ r?.(outcome);
560
+ });
561
+ };
562
+ const fireTrailing = () => {
563
+ timerId = void 0;
564
+ firstCallAt = 0;
565
+ const capturedResolve = pendingResolve;
566
+ pendingResolve = void 0;
567
+ if (capturedResolve === void 0) return;
568
+ currentResolve = capturedResolve;
569
+ const toRun = pendingInput;
570
+ pendingInput = void 0;
571
+ currentController = new AbortController();
572
+ const controller = currentController;
573
+ emit(_pending);
574
+ const onRetrying = retryOptions ? (r) => {
575
+ if (currentController === controller) emit(r);
576
+ } : void 0;
577
+ execute(op, toRun, controller, retryOptions, timeoutOptions, onRetrying).then((outcome) => {
578
+ if (currentController !== controller) return;
579
+ const r = currentResolve;
580
+ currentResolve = void 0;
581
+ currentController = void 0;
582
+ emit(outcome);
583
+ r?.(outcome);
584
+ });
585
+ };
586
+ const scheduleTrailing = () => {
587
+ if (timerId !== void 0) clearTimeout(timerId);
588
+ let delay = ms;
589
+ if (maxWait !== void 0 && firstCallAt > 0) {
590
+ const maxDelay = firstCallAt + maxWait - Date.now();
591
+ delay = Math.min(ms, Math.max(0, maxDelay));
592
+ }
593
+ timerId = setTimeout(fireTrailing, delay);
594
+ };
595
+ const inDebounceWindow = () => timerId !== void 0 || leadingController !== void 0 || currentController !== void 0;
596
+ const run = (input) => Deferred.fromPromise(
597
+ new Promise((resolve) => {
598
+ if (!inDebounceWindow()) {
599
+ firstCallAt = Date.now();
600
+ if (leading) {
601
+ fireLeading(input, resolve);
602
+ scheduleTrailing();
603
+ } else {
604
+ pendingInput = input;
605
+ pendingResolve = resolve;
606
+ scheduleTrailing();
607
+ }
608
+ } else {
609
+ const prev = pendingResolve;
610
+ pendingInput = input;
611
+ pendingResolve = resolve;
612
+ prev?.(_evictedNil);
613
+ scheduleTrailing();
614
+ }
615
+ })
616
+ );
617
+ const abort = () => {
618
+ if (timerId !== void 0) {
619
+ clearTimeout(timerId);
620
+ timerId = void 0;
621
+ pendingInput = void 0;
622
+ firstCallAt = 0;
623
+ }
624
+ const pr = pendingResolve;
625
+ pendingResolve = void 0;
626
+ const cr = currentResolve;
627
+ currentResolve = void 0;
628
+ currentController?.abort();
629
+ currentController = void 0;
630
+ const lr = leadingResolve;
631
+ leadingResolve = void 0;
632
+ leadingController?.abort();
633
+ leadingController = void 0;
634
+ if (currentState.kind !== "Idle") emit(_abortedNil);
635
+ pr?.(_abortedNil);
636
+ cr?.(_abortedNil);
637
+ lr?.(_abortedNil);
638
+ };
639
+ return {
640
+ get state() {
641
+ return currentState;
642
+ },
643
+ run,
644
+ abort,
645
+ subscribe: (cb) => {
646
+ subscribers.add(cb);
647
+ if (currentState.kind !== "Idle") cb(currentState);
648
+ return () => subscribers.delete(cb);
649
+ }
650
+ };
651
+ };
652
+ var makeThrottled = (op, ms, trailing, retryOptions, timeoutOptions) => {
653
+ let currentState = _idle;
654
+ let currentController;
655
+ let currentResolve;
656
+ let cooldownTimer;
657
+ let pendingInput;
658
+ let pendingResolve;
659
+ const subscribers = /* @__PURE__ */ new Set();
660
+ const emit = (state) => {
661
+ currentState = state;
662
+ subscribers.forEach((cb) => cb(state));
663
+ };
664
+ const fireOp = (input, resolve) => {
665
+ currentResolve = resolve;
666
+ currentController = new AbortController();
667
+ const controller = currentController;
668
+ emit(_pending);
669
+ const onRetrying = retryOptions ? (r) => {
670
+ if (currentController === controller) emit(r);
671
+ } : void 0;
672
+ execute(op, input, controller, retryOptions, timeoutOptions, onRetrying).then((outcome) => {
673
+ if (currentController !== controller) return;
674
+ const r = currentResolve;
675
+ currentResolve = void 0;
676
+ currentController = void 0;
677
+ emit(outcome);
678
+ r?.(outcome);
679
+ });
680
+ };
681
+ const startCooldown = () => {
682
+ cooldownTimer = setTimeout(() => {
683
+ cooldownTimer = void 0;
684
+ if (trailing && pendingInput !== void 0) {
685
+ const input = pendingInput;
686
+ const resolve = pendingResolve;
687
+ pendingInput = void 0;
688
+ pendingResolve = void 0;
689
+ fireOp(input, resolve);
690
+ startCooldown();
691
+ }
692
+ }, ms);
693
+ };
694
+ const run = (input) => {
695
+ if (cooldownTimer !== void 0) {
696
+ if (!trailing) {
697
+ return Deferred.fromPromise(Promise.resolve(_droppedNil));
698
+ }
699
+ return Deferred.fromPromise(
700
+ new Promise((resolve) => {
701
+ const prev = pendingResolve;
702
+ pendingInput = input;
703
+ pendingResolve = resolve;
704
+ prev?.(_evictedNil);
705
+ })
706
+ );
707
+ }
708
+ return Deferred.fromPromise(
709
+ new Promise((resolve) => {
710
+ fireOp(input, resolve);
711
+ startCooldown();
712
+ })
713
+ );
714
+ };
715
+ const abort = () => {
716
+ if (cooldownTimer !== void 0) {
717
+ clearTimeout(cooldownTimer);
718
+ cooldownTimer = void 0;
719
+ }
720
+ currentController?.abort();
721
+ currentController = void 0;
722
+ const cr = currentResolve;
723
+ currentResolve = void 0;
724
+ const pr = pendingResolve;
725
+ pendingResolve = void 0;
726
+ pendingInput = void 0;
727
+ if (currentState.kind !== "Idle") emit(_abortedNil);
728
+ cr?.(_abortedNil);
729
+ pr?.(_abortedNil);
730
+ };
731
+ return {
732
+ get state() {
733
+ return currentState;
734
+ },
735
+ run,
736
+ abort,
737
+ subscribe: (cb) => {
738
+ subscribers.add(cb);
739
+ if (currentState.kind !== "Idle") cb(currentState);
740
+ return () => subscribers.delete(cb);
741
+ }
742
+ };
743
+ };
744
+ var makeConcurrent = (op, n, overflow, retryOptions, timeoutOptions) => {
745
+ let currentState = _idle;
746
+ let inflight = 0;
747
+ let generation = 0;
748
+ const controllers = /* @__PURE__ */ new Set();
749
+ const inflightResolvers = [];
750
+ const overflowQueue = [];
751
+ const subscribers = /* @__PURE__ */ new Set();
752
+ const emit = (state) => {
753
+ currentState = state;
754
+ subscribers.forEach((cb) => cb(state));
755
+ };
756
+ const startOne = (input, resolve, myGeneration) => {
757
+ inflight++;
758
+ const controller = new AbortController();
759
+ controllers.add(controller);
760
+ inflightResolvers.push(resolve);
761
+ emit(_pending);
762
+ const onRetrying = retryOptions ? (r) => {
763
+ if (generation === myGeneration && controllers.has(controller)) emit(r);
764
+ } : void 0;
765
+ execute(op, input, controller, retryOptions, timeoutOptions, onRetrying).then((outcome) => {
766
+ controllers.delete(controller);
767
+ const idx = inflightResolvers.indexOf(resolve);
768
+ if (idx !== -1) inflightResolvers.splice(idx, 1);
769
+ if (generation !== myGeneration) {
770
+ resolve(_abortedNil);
771
+ return;
772
+ }
773
+ inflight--;
774
+ emit(outcome);
775
+ resolve(outcome);
776
+ if (overflowQueue.length > 0) {
777
+ const next = overflowQueue.shift();
778
+ startOne(next.input, next.resolve, generation);
779
+ }
780
+ });
781
+ };
782
+ const run = (input) => {
783
+ const myGeneration = generation;
784
+ if (inflight < n) {
785
+ return Deferred.fromPromise(
786
+ new Promise((resolve) => {
787
+ startOne(input, resolve, myGeneration);
788
+ })
789
+ );
790
+ }
791
+ if (overflow === "drop") {
792
+ return Deferred.fromPromise(Promise.resolve(_droppedNil));
793
+ }
794
+ return Deferred.fromPromise(
795
+ new Promise((resolve) => {
796
+ overflowQueue.push({ input, resolve });
797
+ emit({ kind: "Queued", position: overflowQueue.length - 1 });
798
+ })
799
+ );
800
+ };
801
+ const abort = () => {
802
+ generation++;
803
+ controllers.forEach((c) => c.abort());
804
+ controllers.clear();
805
+ const toResolve = inflightResolvers.splice(0);
806
+ const queuedResolvers = overflowQueue.splice(0).map((item) => item.resolve);
807
+ inflight = 0;
808
+ if (currentState.kind !== "Idle") emit(_abortedNil);
809
+ toResolve.forEach((r) => r(_abortedNil));
810
+ queuedResolvers.forEach((r) => r(_abortedNil));
811
+ };
812
+ return {
813
+ get state() {
814
+ return currentState;
815
+ },
816
+ run,
817
+ abort,
818
+ subscribe: (cb) => {
819
+ subscribers.add(cb);
820
+ if (currentState.kind !== "Idle") cb(currentState);
821
+ return () => subscribers.delete(cb);
822
+ }
823
+ };
824
+ };
825
+ var makeKeyed = (op, keyFn, perKey, timeoutOptions) => {
826
+ const stateMap = /* @__PURE__ */ new Map();
827
+ const slots = /* @__PURE__ */ new Map();
828
+ const subscribers = /* @__PURE__ */ new Set();
829
+ const emitSnapshot = () => {
830
+ const snapshot = new Map(stateMap);
831
+ subscribers.forEach((cb) => cb(snapshot));
832
+ };
833
+ const run = (input) => {
834
+ const k = keyFn(input);
835
+ if (slots.has(k)) {
836
+ if (perKey === "exclusive") {
837
+ return Deferred.fromPromise(Promise.resolve(_droppedNil));
838
+ }
839
+ const existing = slots.get(k);
840
+ existing.controller.abort();
841
+ const prev = existing.resolve;
842
+ slots.delete(k);
843
+ prev(_replacedNil);
844
+ }
845
+ return Deferred.fromPromise(
846
+ new Promise((resolve) => {
847
+ const controller = new AbortController();
848
+ slots.set(k, { controller, resolve });
849
+ stateMap.set(k, _pending);
850
+ emitSnapshot();
851
+ execute(op, input, controller, void 0, timeoutOptions, void 0).then((outcome) => {
852
+ const slot = slots.get(k);
853
+ if (!slot || slot.controller !== controller) {
854
+ resolve(_abortedNil);
855
+ return;
856
+ }
857
+ slots.delete(k);
858
+ stateMap.set(k, outcome);
859
+ emitSnapshot();
860
+ resolve(outcome);
861
+ });
862
+ })
863
+ );
864
+ };
865
+ const abort = (key) => {
866
+ if (key !== void 0) {
867
+ const slot = slots.get(key);
868
+ if (slot) {
869
+ slot.controller.abort();
870
+ const r = slot.resolve;
871
+ slots.delete(key);
872
+ stateMap.set(key, _abortedNil);
873
+ emitSnapshot();
874
+ r(_abortedNil);
875
+ }
876
+ } else {
877
+ const toResolve = [];
878
+ for (const [k, slot] of slots) {
879
+ slot.controller.abort();
880
+ toResolve.push(slot.resolve);
881
+ stateMap.set(k, _abortedNil);
882
+ }
883
+ slots.clear();
884
+ if (toResolve.length > 0) emitSnapshot();
885
+ toResolve.forEach((r) => r(_abortedNil));
886
+ }
887
+ };
888
+ return {
889
+ get state() {
890
+ return new Map(stateMap);
891
+ },
892
+ run,
893
+ abort,
894
+ subscribe: (cb) => {
895
+ subscribers.add(cb);
896
+ if (stateMap.size > 0) cb(new Map(stateMap));
897
+ return () => subscribers.delete(cb);
898
+ }
899
+ };
900
+ };
901
+ var makeOnce = (op, retryOptions, timeoutOptions) => {
902
+ let currentState = _idle;
903
+ let currentController;
904
+ let currentResolve;
905
+ const subscribers = /* @__PURE__ */ new Set();
906
+ const emit = (state) => {
907
+ currentState = state;
908
+ subscribers.forEach((cb) => cb(state));
909
+ };
910
+ const run = (input) => {
911
+ if (currentState.kind !== "Idle") {
912
+ return Deferred.fromPromise(Promise.resolve(_droppedNil));
913
+ }
914
+ return Deferred.fromPromise(
915
+ new Promise((resolve) => {
916
+ currentResolve = resolve;
917
+ currentController = new AbortController();
918
+ const controller = currentController;
919
+ emit(_pending);
920
+ const onRetrying = retryOptions ? (r) => {
921
+ if (currentController === controller) emit(r);
922
+ } : void 0;
923
+ execute(op, input, controller, retryOptions, timeoutOptions, onRetrying).then((outcome) => {
924
+ if (currentController !== controller) return;
925
+ const r = currentResolve;
926
+ currentResolve = void 0;
927
+ currentController = void 0;
928
+ emit(outcome);
929
+ r?.(outcome);
930
+ });
931
+ })
932
+ );
933
+ };
934
+ const abort = () => {
935
+ currentController?.abort();
936
+ currentController = void 0;
937
+ const r = currentResolve;
938
+ currentResolve = void 0;
939
+ if (currentState.kind !== "Idle") emit(_abortedNil);
940
+ r?.(_abortedNil);
941
+ };
942
+ return {
943
+ get state() {
944
+ return currentState;
945
+ },
946
+ run,
947
+ abort,
948
+ subscribe: (cb) => {
949
+ subscribers.add(cb);
950
+ if (currentState.kind !== "Idle") cb(currentState);
951
+ return () => subscribers.delete(cb);
952
+ }
953
+ };
954
+ };
955
+
956
+ // src/Core/Op.ts
957
+ var Op;
958
+ ((Op2) => {
959
+ Op2.nil = (reason) => ({ kind: "Nil", reason });
960
+ Op2.create = (factory, onError) => ({
961
+ _factory: (input, signal) => Deferred.fromPromise(
962
+ factory(input, signal).then((value) => Result.ok(value)).catch((e) => signal.aborted ? null : Result.err(onError(e)))
963
+ )
964
+ });
965
+ Op2.ok = (value) => ({ kind: "Ok", value });
966
+ Op2.err = (error) => ({ kind: "Err", error });
967
+ Op2.isOk = (outcome) => outcome.kind === "Ok";
968
+ Op2.isErr = (outcome) => outcome.kind === "Err";
969
+ Op2.isNil = (outcome) => outcome.kind === "Nil";
970
+ Op2.match = (cases) => (outcome) => {
971
+ if (outcome.kind === "Ok") return cases.ok(outcome.value);
972
+ if (outcome.kind === "Err") return cases.err(outcome.error);
973
+ return cases.nil();
974
+ };
975
+ Op2.fold = (onErr, onOk, onNil) => (outcome) => {
976
+ if (outcome.kind === "Ok") return onOk(outcome.value);
977
+ if (outcome.kind === "Err") return onErr(outcome.error);
978
+ return onNil();
979
+ };
980
+ Op2.getOrElse = (defaultValue) => (outcome) => outcome.kind === "Ok" ? outcome.value : defaultValue();
981
+ Op2.map = (f) => (outcome) => outcome.kind === "Ok" ? (0, Op2.ok)(f(outcome.value)) : outcome;
982
+ Op2.mapError = (f) => (outcome) => outcome.kind === "Err" ? (0, Op2.err)(f(outcome.error)) : outcome;
983
+ Op2.chain = (f) => (outcome) => outcome.kind === "Ok" ? f(outcome.value) : outcome;
984
+ Op2.tap = (f) => (outcome) => {
985
+ if (outcome.kind === "Ok") f(outcome.value);
986
+ return outcome;
987
+ };
988
+ Op2.recover = (f) => (outcome) => outcome.kind === "Err" ? f(outcome.error) : outcome;
989
+ Op2.toResult = (onNil) => (outcome) => {
990
+ if (outcome.kind === "Ok") return Result.ok(outcome.value);
991
+ if (outcome.kind === "Err") return Result.err(outcome.error);
992
+ return Result.err(onNil());
993
+ };
994
+ Op2.toMaybe = (outcome) => outcome.kind === "Ok" ? Maybe.some(outcome.value) : Maybe.none();
995
+ Op2.all = (invocations) => Deferred.fromPromise(Promise.all(invocations.map(Deferred.toPromise)));
996
+ Op2.race = (invocations) => Deferred.fromPromise(Promise.race(invocations.map(Deferred.toPromise)));
997
+ function interpret(op, options) {
998
+ const { strategy, retry: retryOptions, timeout: timeoutOptions } = options;
999
+ switch (strategy) {
1000
+ case "once":
1001
+ return makeOnce(op, retryOptions, timeoutOptions);
1002
+ case "restartable":
1003
+ return makeRestartable(op, options.minInterval, retryOptions, timeoutOptions);
1004
+ case "exclusive":
1005
+ return makeExclusive(op, options.cooldown, retryOptions, timeoutOptions);
1006
+ case "queue":
1007
+ return makeQueue(
1008
+ op,
1009
+ options.maxSize,
1010
+ options.overflow,
1011
+ options.concurrency,
1012
+ options.dedupe,
1013
+ retryOptions,
1014
+ timeoutOptions
1015
+ );
1016
+ case "buffered":
1017
+ return makeBuffered(op, options.size, retryOptions, timeoutOptions);
1018
+ case "debounced":
1019
+ return makeDebounced(op, options.ms ?? 0, options.leading ?? false, options.maxWait, retryOptions, timeoutOptions);
1020
+ case "throttled":
1021
+ return makeThrottled(op, options.ms ?? 0, options.trailing ?? false, retryOptions, timeoutOptions);
1022
+ case "concurrent":
1023
+ return makeConcurrent(
1024
+ op,
1025
+ options.n ?? 1,
1026
+ options.overflow ?? "drop",
1027
+ retryOptions,
1028
+ timeoutOptions
1029
+ );
1030
+ case "keyed":
1031
+ return makeKeyed(op, options.key ?? ((i) => i), options.perKey ?? "exclusive", timeoutOptions);
1032
+ }
1033
+ }
1034
+ Op2.interpret = interpret;
1035
+ })(Op || (Op = {}));
1036
+
164
1037
  // src/Core/Optional.ts
165
1038
  var Optional;
166
1039
  ((Optional2) => {
@@ -515,17 +1388,6 @@ var TaskMaybe;
515
1388
  })(TaskMaybe || (TaskMaybe = {}));
516
1389
 
517
1390
  // src/Core/TaskResult.ts
518
- var cancellableWait = (ms, signal) => {
519
- if (ms <= 0) return Promise.resolve();
520
- if (!signal) return new Promise((r) => setTimeout(r, ms));
521
- return new Promise((resolve) => {
522
- const id = setTimeout(resolve, ms);
523
- signal.addEventListener("abort", () => {
524
- clearTimeout(id);
525
- resolve();
526
- }, { once: true });
527
- });
528
- };
529
1391
  var TaskResult;
530
1392
  ((TaskResult2) => {
531
1393
  TaskResult2.ok = (value) => Task.resolve(Result.ok(value));
@@ -545,75 +1407,6 @@ var TaskResult;
545
1407
  )(data);
546
1408
  TaskResult2.getOrElse = (defaultValue) => (data) => Task.map(Result.getOrElse(defaultValue))(data);
547
1409
  TaskResult2.tap = (f) => (data) => Task.map(Result.tap(f))(data);
548
- TaskResult2.retry = (options) => (data) => Task.from((signal) => {
549
- const { attempts, backoff, when: shouldRetry } = options;
550
- const getDelay = (n) => backoff === void 0 ? 0 : typeof backoff === "function" ? backoff(n) : backoff;
551
- const run = (left) => Deferred.toPromise(data(signal)).then((result) => {
552
- if (Result.isOk(result)) return result;
553
- if (left <= 1) return result;
554
- if (shouldRetry !== void 0 && !shouldRetry(result.error)) {
555
- return result;
556
- }
557
- if (signal?.aborted) return result;
558
- const ms = getDelay(attempts - left + 1);
559
- return cancellableWait(ms, signal).then(() => {
560
- if (signal?.aborted) return result;
561
- return run(left - 1);
562
- });
563
- });
564
- return run(attempts);
565
- });
566
- TaskResult2.pollUntil = (options) => (task) => Task.from((signal) => {
567
- const { when: predicate, delay } = options;
568
- const getDelay = (attempt) => delay === void 0 ? 0 : typeof delay === "function" ? delay(attempt) : delay;
569
- const run = (attempt) => Deferred.toPromise(task(signal)).then((result) => {
570
- if (Result.isErr(result)) return result;
571
- if (predicate(result.value)) return result;
572
- if (signal?.aborted) return result;
573
- const ms = getDelay(attempt);
574
- return cancellableWait(ms, signal).then(() => {
575
- if (signal?.aborted) return result;
576
- return run(attempt + 1);
577
- });
578
- });
579
- return run(1);
580
- });
581
- TaskResult2.timeout = (ms, onTimeout) => (data) => Task.from((outerSignal) => {
582
- const controller = new AbortController();
583
- const onOuterAbort = () => controller.abort();
584
- outerSignal?.addEventListener("abort", onOuterAbort, { once: true });
585
- let timerId;
586
- return Promise.race([
587
- Deferred.toPromise(data(controller.signal)).then((result) => {
588
- clearTimeout(timerId);
589
- outerSignal?.removeEventListener("abort", onOuterAbort);
590
- return result;
591
- }),
592
- new Promise((resolve) => {
593
- timerId = setTimeout(() => {
594
- controller.abort();
595
- outerSignal?.removeEventListener("abort", onOuterAbort);
596
- resolve(Result.err(onTimeout()));
597
- }, ms);
598
- })
599
- ]);
600
- });
601
- TaskResult2.abortable = (factory, onError) => {
602
- const controller = new AbortController();
603
- const task = (outerSignal) => {
604
- if (outerSignal) {
605
- if (outerSignal.aborted) {
606
- controller.abort(outerSignal.reason);
607
- } else {
608
- outerSignal.addEventListener("abort", () => controller.abort(outerSignal.reason), { once: true });
609
- }
610
- }
611
- return Deferred.fromPromise(
612
- factory(controller.signal).then(Result.ok).catch((e) => Result.err(onError(e)))
613
- );
614
- };
615
- return { task, abort: () => controller.abort() };
616
- };
617
1410
  })(TaskResult || (TaskResult = {}));
618
1411
 
619
1412
  // src/Core/Validation.ts
@@ -650,7 +1443,7 @@ var Validation;
650
1443
  return data;
651
1444
  };
652
1445
  Validation2.recover = (fallback) => (data) => (0, Validation2.isValid)(data) ? data : fallback(data.errors);
653
- Validation2.recoverUnless = (blockedErrors, fallback) => (data) => (0, Validation2.isInvalid)(data) && !data.errors.some((err) => blockedErrors.includes(err)) ? fallback() : data;
1446
+ Validation2.recoverUnless = (blockedErrors, fallback) => (data) => (0, Validation2.isInvalid)(data) && !data.errors.some((err2) => blockedErrors.includes(err2)) ? fallback() : data;
654
1447
  Validation2.product = (first, second) => {
655
1448
  if ((0, Validation2.isValid)(first) && (0, Validation2.isValid)(second)) return (0, Validation2.valid)([first.value, second.value]);
656
1449
  const errors = [
@@ -792,6 +1585,7 @@ var Tuple;
792
1585
  Lens,
793
1586
  Logged,
794
1587
  Maybe,
1588
+ Op,
795
1589
  Optional,
796
1590
  Predicate,
797
1591
  Reader,