@noego/trust 0.5.1-dev.4 → 0.5.1-dev.5

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/index.js CHANGED
@@ -57,6 +57,967 @@ function match(result, handlers) {
57
57
  const value = handler(result.value);
58
58
  return isResult(value) ? value : ok(value);
59
59
  }
60
+ var MAX_TIMER_MS = 2147483647;
61
+ function startBoundedTimer(callback, totalMs) {
62
+ let remaining = Math.max(0, totalMs);
63
+ let handle;
64
+ let cancelled = false;
65
+ const step = () => {
66
+ if (cancelled) return;
67
+ if (remaining > MAX_TIMER_MS) {
68
+ remaining -= MAX_TIMER_MS;
69
+ handle = setTimeout(step, MAX_TIMER_MS);
70
+ return;
71
+ }
72
+ handle = setTimeout(() => {
73
+ if (!cancelled) callback();
74
+ }, remaining);
75
+ };
76
+ step();
77
+ return () => {
78
+ cancelled = true;
79
+ if (handle !== void 0) clearTimeout(handle);
80
+ };
81
+ }
82
+ function watchSignal(signal, initiallyReferenced) {
83
+ if (signal === void 0) return void 0;
84
+ if (typeof AbortSignal === "function" && typeof AbortSignal.any === "function") {
85
+ const dependent = AbortSignal.any([signal]);
86
+ return { signal: dependent, sync: () => dependent.aborted, setRef: () => {
87
+ }, cleanup: () => {
88
+ } };
89
+ }
90
+ const controller = new AbortController();
91
+ if (signal.aborted) {
92
+ controller.abort(signal.reason);
93
+ return { signal: controller.signal, sync: () => true, setRef: () => {
94
+ }, cleanup: () => {
95
+ } };
96
+ }
97
+ let pollHandle;
98
+ const setRef = (referenced) => {
99
+ if (typeof pollHandle !== "object" || pollHandle === null) return;
100
+ const method = referenced ? pollHandle.ref : pollHandle.unref;
101
+ if (typeof method === "function") method.call(pollHandle);
102
+ };
103
+ const cleanup = () => {
104
+ signal.removeEventListener("abort", forward, true);
105
+ if (pollHandle !== void 0) {
106
+ clearInterval(pollHandle);
107
+ pollHandle = void 0;
108
+ }
109
+ };
110
+ const forward = () => {
111
+ if (!signal.aborted) return;
112
+ cleanup();
113
+ if (!controller.signal.aborted) controller.abort(signal.reason);
114
+ };
115
+ const sync = () => {
116
+ if (signal.aborted && !controller.signal.aborted) forward();
117
+ return controller.signal.aborted;
118
+ };
119
+ signal.addEventListener("abort", forward, true);
120
+ pollHandle = setInterval(forward, 10);
121
+ setRef(initiallyReferenced);
122
+ return { signal: controller.signal, sync, setRef, cleanup };
123
+ }
124
+ async function runAttempt(fn, attempt, outerWatch, timeoutMs) {
125
+ outerWatch?.sync();
126
+ const outerSignal = outerWatch?.signal;
127
+ const controller = new AbortController();
128
+ let cancelTimer;
129
+ const onAbort = () => {
130
+ if (cancelTimer !== void 0) {
131
+ cancelTimer();
132
+ cancelTimer = void 0;
133
+ }
134
+ outerWatch?.setRef(false);
135
+ controller.abort(outerSignal?.reason);
136
+ };
137
+ if (outerSignal) {
138
+ if (outerSignal.aborted) {
139
+ outerWatch?.setRef(false);
140
+ controller.abort(outerSignal.reason);
141
+ } else {
142
+ outerSignal.addEventListener("abort", onAbort, { once: true });
143
+ }
144
+ }
145
+ if (timeoutMs !== void 0 && !controller.signal.aborted) {
146
+ cancelTimer = startBoundedTimer(() => {
147
+ cancelTimer = void 0;
148
+ if (outerWatch?.sync()) return;
149
+ if (outerSignal) outerSignal.removeEventListener("abort", onAbort);
150
+ outerWatch?.setRef(false);
151
+ const reason = typeof DOMException === "function" ? new DOMException("The operation was aborted due to timeout", "TimeoutError") : new Error("The operation was aborted due to timeout");
152
+ controller.abort(reason);
153
+ }, timeoutMs);
154
+ }
155
+ try {
156
+ const out = fn(attempt, controller.signal);
157
+ if ("ok" in out && (out.ok === true ? "value" in out : out.ok === false && "error" in out)) {
158
+ return { result: out };
159
+ }
160
+ if (out !== null && (typeof out === "object" || typeof out === "function")) {
161
+ const then = out.then;
162
+ if (typeof then === "function") {
163
+ const result = await Promise.resolve({
164
+ then: (resolve, reject) => Reflect.apply(then, out, [resolve, reject])
165
+ });
166
+ return { result };
167
+ }
168
+ }
169
+ return { result: out };
170
+ } finally {
171
+ if (cancelTimer !== void 0) cancelTimer();
172
+ if (outerSignal) outerSignal.removeEventListener("abort", onAbort);
173
+ }
174
+ }
175
+ function sleepWithSignal(ms, signal) {
176
+ if (signal?.aborted) return Promise.resolve(false);
177
+ return new Promise((resolve) => {
178
+ const onAbort = () => {
179
+ cancelTimer();
180
+ resolve(false);
181
+ };
182
+ const cancelTimer = startBoundedTimer(() => {
183
+ if (signal) signal.removeEventListener("abort", onAbort);
184
+ resolve(true);
185
+ }, ms);
186
+ if (signal) signal.addEventListener("abort", onAbort, { once: true });
187
+ });
188
+ }
189
+ async function retry(fn, options) {
190
+ const { times, on, signal, timeoutMs } = options;
191
+ const typedFn = fn;
192
+ if (!Number.isSafeInteger(times) || times < 1) {
193
+ throw new RangeError("Trust.retry: `times` must be a safe integer >= 1");
194
+ }
195
+ if (timeoutMs !== void 0 && (!Number.isFinite(timeoutMs) || timeoutMs < 0 || timeoutMs > Number.MAX_SAFE_INTEGER)) {
196
+ throw new RangeError("Trust.retry: `timeoutMs` must be a non-negative safe duration");
197
+ }
198
+ const outerWatch = watchSignal(signal, true);
199
+ const isolatedSignal = outerWatch?.signal;
200
+ const isCancelled = () => Boolean(signal?.aborted || isolatedSignal?.aborted);
201
+ try {
202
+ let attempt = 1;
203
+ while (true) {
204
+ outerWatch?.setRef(true);
205
+ const { result } = await runAttempt(typedFn, attempt, outerWatch, timeoutMs);
206
+ if (result.ok || attempt >= times || isCancelled()) return result;
207
+ const handler = pick(on, result.error?.kind);
208
+ if (handler === void 0) return result;
209
+ const delay = handler(result.error, attempt);
210
+ if (delay === false || delay === null || delay === void 0) return result;
211
+ if (typeof delay !== "number" || !Number.isFinite(delay) || delay > Number.MAX_SAFE_INTEGER) {
212
+ throw new RangeError("Trust.retry: backoff delay must be a finite safe duration");
213
+ }
214
+ outerWatch?.setRef(false);
215
+ if (isCancelled() || !await sleepWithSignal(Math.max(0, delay), isolatedSignal) || isCancelled()) return result;
216
+ attempt++;
217
+ }
218
+ } finally {
219
+ outerWatch?.cleanup();
220
+ }
221
+ }
222
+ function ensureBrandedErr(failure) {
223
+ if (isResult(failure)) return failure;
224
+ return err(failure.error);
225
+ }
226
+ function readOutcome(value) {
227
+ if ((typeof value !== "object" || value === null) && typeof value !== "function") {
228
+ throw new TypeError("Expected task to resolve to a Result");
229
+ }
230
+ const okFlag = value.ok;
231
+ if (typeof okFlag !== "boolean") {
232
+ throw new TypeError("Expected task to resolve to a Result");
233
+ }
234
+ if (okFlag) {
235
+ if (typeof value.state === "string") {
236
+ throw new TypeError("Cannot unwrap a stated Result; match states first");
237
+ }
238
+ return { ok: true, value: value.value };
239
+ }
240
+ return { ok: false, failure: ensureBrandedErr(value) };
241
+ }
242
+ var INTRINSIC_PROMISE_THEN = Promise.prototype.then;
243
+ var PROMISE_THEN_SOURCE = Function.prototype.toString.call(INTRINSIC_PROMISE_THEN);
244
+ var noop = () => {
245
+ };
246
+ function silenceIntrinsicPromise(value) {
247
+ if (typeof value !== "object" || value === null) return;
248
+ try {
249
+ Reflect.apply(INTRINSIC_PROMISE_THEN, value, [noop, noop]);
250
+ } catch {
251
+ }
252
+ }
253
+ function isNativePromiseThen(thenProp) {
254
+ if (thenProp === INTRINSIC_PROMISE_THEN) return true;
255
+ if (typeof thenProp !== "function") return false;
256
+ try {
257
+ return Reflect.apply(Function.prototype.toString, thenProp, []) === PROMISE_THEN_SOURCE;
258
+ } catch {
259
+ return false;
260
+ }
261
+ }
262
+ function subscribeThenable(value, thenProp, onFulfilled, onRejected, visited) {
263
+ if (isNativePromiseThen(thenProp)) {
264
+ Reflect.apply(thenProp, value, [onFulfilled, onRejected]);
265
+ return;
266
+ }
267
+ Promise.resolve().then(() => {
268
+ let settledThenable = false;
269
+ const resolveOnce = (nextValue) => {
270
+ if (settledThenable) return;
271
+ settledThenable = true;
272
+ if (nextValue === value || visited?.has(nextValue)) {
273
+ onRejected(new TypeError("Chaining cycle detected for PromiseLike"));
274
+ return;
275
+ }
276
+ if (typeof nextValue === "object" && nextValue !== null || typeof nextValue === "function") {
277
+ let nextThen;
278
+ try {
279
+ nextThen = nextValue.then;
280
+ } catch (cause) {
281
+ silenceIntrinsicPromise(nextValue);
282
+ onRejected(cause);
283
+ return;
284
+ }
285
+ if (typeof nextThen === "function") {
286
+ const nextVisited = visited ?? /* @__PURE__ */ new Set([value]);
287
+ nextVisited.add(nextValue);
288
+ try {
289
+ subscribeThenable(nextValue, nextThen, onFulfilled, onRejected, nextVisited);
290
+ } catch (cause) {
291
+ silenceIntrinsicPromise(nextValue);
292
+ onRejected(cause);
293
+ }
294
+ return;
295
+ }
296
+ try {
297
+ if (!isResult(nextValue) && nextValue instanceof Promise) {
298
+ silenceIntrinsicPromise(nextValue);
299
+ }
300
+ } catch (cause) {
301
+ silenceIntrinsicPromise(nextValue);
302
+ onRejected(cause);
303
+ return;
304
+ }
305
+ }
306
+ onFulfilled(nextValue);
307
+ };
308
+ const rejectThenable = (cause) => {
309
+ if (settledThenable) return;
310
+ settledThenable = true;
311
+ onRejected(cause);
312
+ };
313
+ try {
314
+ Reflect.apply(thenProp, value, [resolveOnce, rejectThenable]);
315
+ } catch (cause) {
316
+ silenceIntrinsicPromise(value);
317
+ rejectThenable(cause);
318
+ }
319
+ });
320
+ }
321
+ function normalizeTask(value) {
322
+ if (typeof value === "object" && value !== null || typeof value === "function") {
323
+ try {
324
+ const thenProp = value.then;
325
+ if (typeof thenProp === "function") {
326
+ return {
327
+ kind: "async",
328
+ target: value,
329
+ then: thenProp
330
+ };
331
+ }
332
+ const outcome = readOutcome(value);
333
+ if (!isResult(value) && value instanceof Promise) {
334
+ silenceIntrinsicPromise(value);
335
+ }
336
+ return { kind: "sync", outcome };
337
+ } catch (cause) {
338
+ silenceIntrinsicPromise(value);
339
+ return { kind: "reject", cause };
340
+ }
341
+ }
342
+ return { kind: "reject", cause: new TypeError("Expected a Result or PromiseLike<Result>") };
343
+ }
344
+ var OBJECT_CTOR_SOURCE = Function.prototype.toString.call(Object);
345
+ function isObjectRootPrototype(proto) {
346
+ if (proto === Object.prototype) return true;
347
+ if (Object.getPrototypeOf(proto) !== null) return false;
348
+ const ctor = proto.constructor;
349
+ return typeof ctor === "function" && ctor.prototype === proto && Function.prototype.toString.call(ctor) === OBJECT_CTOR_SOURCE;
350
+ }
351
+ function silenceThenable(value) {
352
+ if ((typeof value !== "object" || value === null) && typeof value !== "function") return;
353
+ try {
354
+ const thenProp = value.then;
355
+ if (typeof thenProp === "function") {
356
+ if (isNativePromiseThen(thenProp)) {
357
+ Reflect.apply(thenProp, value, [noop, noop]);
358
+ } else {
359
+ Promise.resolve().then(() => {
360
+ try {
361
+ Reflect.apply(thenProp, value, [noop, noop]);
362
+ } catch {
363
+ silenceIntrinsicPromise(value);
364
+ }
365
+ });
366
+ }
367
+ } else if (!isResult(value)) {
368
+ silenceIntrinsicPromise(value);
369
+ }
370
+ } catch {
371
+ silenceIntrinsicPromise(value);
372
+ }
373
+ }
374
+ var MAX_INDEXED_CLEANUP_SCAN = 1024;
375
+ var MAX_OPAQUE_INDEX_PROBE = 65536;
376
+ function observeContainerPromises(target) {
377
+ if (typeof target !== "object" || target === null) return;
378
+ const candidates = [target];
379
+ const accessorIndices = /* @__PURE__ */ new Set();
380
+ const visitedProtos = /* @__PURE__ */ new Set();
381
+ let current = target;
382
+ let depth = 0;
383
+ let targetKeysFailed = false;
384
+ while (current !== null && depth < 64 && !visitedProtos.has(current)) {
385
+ visitedProtos.add(current);
386
+ depth += 1;
387
+ try {
388
+ let ownKeys;
389
+ try {
390
+ ownKeys = Reflect.ownKeys(current);
391
+ } catch (cause) {
392
+ if (current === target) targetKeysFailed = true;
393
+ throw cause;
394
+ }
395
+ for (const key of ownKeys) {
396
+ try {
397
+ const desc = Object.getOwnPropertyDescriptor(current, key);
398
+ if (desc && "value" in desc) candidates.push(desc.value);
399
+ else if (desc?.get && typeof key === "string") {
400
+ const i = Number(key);
401
+ if (Number.isInteger(i) && i >= 0 && i < 2 ** 32 - 1 && String(i) === key) accessorIndices.add(i);
402
+ }
403
+ } catch {
404
+ }
405
+ }
406
+ } catch {
407
+ }
408
+ try {
409
+ const nextProto = Object.getPrototypeOf(current);
410
+ if (nextProto === null || isObjectRootPrototype(nextProto)) break;
411
+ current = nextProto;
412
+ } catch {
413
+ break;
414
+ }
415
+ }
416
+ try {
417
+ if (Array.isArray(target)) {
418
+ const len = target.length;
419
+ const limit = targetKeysFailed ? MAX_OPAQUE_INDEX_PROBE : MAX_INDEXED_CLEANUP_SCAN;
420
+ if (Number.isSafeInteger(len) && len >= 0 && (len <= limit || targetKeysFailed)) {
421
+ const end = Math.min(len, limit);
422
+ for (let i = 0; i < end; i += 1) {
423
+ try {
424
+ candidates.push(target[i]);
425
+ } catch {
426
+ }
427
+ }
428
+ } else {
429
+ for (const i of accessorIndices) {
430
+ try {
431
+ candidates.push(target[i]);
432
+ } catch {
433
+ }
434
+ }
435
+ }
436
+ }
437
+ } catch {
438
+ }
439
+ const seen = /* @__PURE__ */ new Set();
440
+ for (let i = 0; i < candidates.length; i += 1) {
441
+ const candidate = candidates[i];
442
+ if ((typeof candidate !== "object" || candidate === null) && typeof candidate !== "function") continue;
443
+ if (seen.has(candidate)) continue;
444
+ seen.add(candidate);
445
+ silenceThenable(candidate);
446
+ }
447
+ }
448
+ function linkSignal(parent) {
449
+ const controller = new AbortController();
450
+ if (parent === void 0) {
451
+ return { controller, unlink: noop };
452
+ }
453
+ if (typeof parent !== "object" || parent === null || typeof parent.aborted !== "boolean" || typeof parent.addEventListener !== "function" || typeof parent.removeEventListener !== "function") {
454
+ throw new TypeError("Expected options.signal to be an AbortSignal");
455
+ }
456
+ if (parent.aborted) {
457
+ controller.abort(parent.reason);
458
+ return { controller, unlink: noop };
459
+ }
460
+ let source = parent;
461
+ const abortAny = AbortSignal.any;
462
+ if (typeof abortAny === "function") {
463
+ try {
464
+ source = abortAny.call(AbortSignal, [parent]);
465
+ } catch {
466
+ }
467
+ }
468
+ if (source.aborted) {
469
+ controller.abort(source.reason);
470
+ return { controller, unlink: noop };
471
+ }
472
+ const onAbort = () => controller.abort(source.reason);
473
+ source.addEventListener("abort", onAbort, { once: true });
474
+ return {
475
+ controller,
476
+ unlink: () => source.removeEventListener("abort", onAbort)
477
+ };
478
+ }
479
+ function all(tasks, options) {
480
+ let linked;
481
+ try {
482
+ if (options !== void 0 && (typeof options !== "object" || options === null)) {
483
+ throw new TypeError("Trust.all options must be an object");
484
+ }
485
+ linked = linkSignal(options?.signal);
486
+ } catch (cause) {
487
+ if (typeof tasks !== "function") observeContainerPromises(tasks);
488
+ return Promise.reject(cause);
489
+ }
490
+ const { controller, unlink } = linked;
491
+ let collection;
492
+ try {
493
+ collection = typeof tasks === "function" ? tasks(controller.signal) : tasks;
494
+ } catch (cause) {
495
+ unlink();
496
+ controller.abort();
497
+ return Promise.reject(cause);
498
+ }
499
+ let isArray = false;
500
+ try {
501
+ isArray = Array.isArray(collection);
502
+ } catch (cause) {
503
+ observeContainerPromises(collection);
504
+ unlink();
505
+ controller.abort();
506
+ return Promise.reject(cause);
507
+ }
508
+ if (!isArray) {
509
+ observeContainerPromises(collection);
510
+ unlink();
511
+ controller.abort();
512
+ return Promise.reject(new TypeError("Trust.all expects an array of Result tasks"));
513
+ }
514
+ const arraySource = collection;
515
+ let total;
516
+ let sparseIndices;
517
+ try {
518
+ total = arraySource.length;
519
+ if (!Number.isSafeInteger(total) || total < 0 || total > 2 ** 32 - 1) {
520
+ throw new RangeError(`Invalid array length: ${String(total)}`);
521
+ }
522
+ if (total > MAX_INDEXED_CLEANUP_SCAN) {
523
+ const present = [];
524
+ let keys;
525
+ try {
526
+ keys = Reflect.ownKeys(arraySource);
527
+ } catch {
528
+ keys = Array.from({ length: Math.min(total, MAX_OPAQUE_INDEX_PROBE) }, (_, i) => String(i));
529
+ }
530
+ for (const key of keys) {
531
+ if (typeof key !== "string") continue;
532
+ const index = Number(key);
533
+ if (Number.isInteger(index) && index >= 0 && index < total && String(index) === key) present.push(index);
534
+ }
535
+ if (present.length !== total) {
536
+ const indices = new Set(present);
537
+ const seen = /* @__PURE__ */ new Set([arraySource]);
538
+ let current = arraySource;
539
+ for (let depth = 0; depth < 64; depth++) {
540
+ try {
541
+ const proto = Object.getPrototypeOf(current);
542
+ if (!proto || seen.has(proto)) break;
543
+ seen.add(proto);
544
+ current = proto;
545
+ for (const key of Reflect.ownKeys(proto)) {
546
+ if (typeof key !== "string") continue;
547
+ const index = Number(key);
548
+ if (Number.isInteger(index) && index >= 0 && index < total && String(index) === key) indices.add(index);
549
+ }
550
+ } catch {
551
+ break;
552
+ }
553
+ }
554
+ sparseIndices = [...indices].sort((a, b) => a - b);
555
+ }
556
+ }
557
+ } catch (cause) {
558
+ observeContainerPromises(arraySource);
559
+ unlink();
560
+ controller.abort();
561
+ return Promise.reject(cause);
562
+ }
563
+ if (total === 0) {
564
+ unlink();
565
+ return Promise.resolve(ok([]));
566
+ }
567
+ return new Promise((resolve, reject) => {
568
+ let values = [];
569
+ let remaining = total;
570
+ let settled = false;
571
+ let syncTerminal;
572
+ const fail = (brandedFailure) => {
573
+ if (settled) return;
574
+ settled = true;
575
+ if (values !== null) {
576
+ values.length = 0;
577
+ values = null;
578
+ }
579
+ unlink();
580
+ controller.abort();
581
+ resolve(brandedFailure);
582
+ };
583
+ const rejectOnce = (cause) => {
584
+ if (settled) return;
585
+ settled = true;
586
+ if (values !== null) {
587
+ values.length = 0;
588
+ values = null;
589
+ }
590
+ unlink();
591
+ controller.abort();
592
+ reject(cause);
593
+ };
594
+ const deferFail = (brandedFailure) => {
595
+ if (syncTerminal === void 0) {
596
+ syncTerminal = { kind: "fail", failure: brandedFailure };
597
+ }
598
+ };
599
+ const deferReject = (cause) => {
600
+ if (syncTerminal === void 0) {
601
+ syncTerminal = { kind: "reject", cause };
602
+ }
603
+ };
604
+ const succeed = (index, value) => {
605
+ if (settled || syncTerminal !== void 0 || values === null) return;
606
+ values[index] = value;
607
+ remaining -= 1;
608
+ if (remaining === 0) {
609
+ settled = true;
610
+ const completed = values;
611
+ values = null;
612
+ unlink();
613
+ resolve(ok(completed));
614
+ }
615
+ };
616
+ const originalSlots = /* @__PURE__ */ new Map();
617
+ const captureDataSlot = (i) => {
618
+ const seenProtos = /* @__PURE__ */ new Set();
619
+ let current = arraySource;
620
+ for (let depth = 0; current !== null && depth < 64 && !seenProtos.has(current); depth += 1) {
621
+ seenProtos.add(current);
622
+ try {
623
+ const desc = Object.getOwnPropertyDescriptor(current, i);
624
+ if (desc) {
625
+ if ("value" in desc) originalSlots.set(i, desc.value);
626
+ return;
627
+ }
628
+ current = Object.getPrototypeOf(current);
629
+ } catch {
630
+ return;
631
+ }
632
+ }
633
+ };
634
+ for (let pos = 0; pos < (sparseIndices?.length ?? total); pos += 1) {
635
+ captureDataSlot(sparseIndices?.[pos] ?? pos);
636
+ }
637
+ const slotEntries = [];
638
+ const slotErrors = [];
639
+ const slotReadable = [];
640
+ const visited = sparseIndices ? [] : void 0;
641
+ let nextOwn = 0;
642
+ let foundHole = false;
643
+ for (let i = 0; i < total; i += 1) {
644
+ if (sparseIndices && foundHole) {
645
+ if (nextOwn === sparseIndices.length) break;
646
+ i = sparseIndices[nextOwn];
647
+ }
648
+ if (sparseIndices?.[nextOwn] === i) nextOwn++;
649
+ visited?.push(i);
650
+ try {
651
+ slotEntries[i] = arraySource[i];
652
+ if (slotEntries[i] === void 0) foundHole = true;
653
+ slotReadable[i] = true;
654
+ } catch (cause) {
655
+ foundHole = true;
656
+ slotReadable[i] = false;
657
+ slotErrors[i] = cause;
658
+ if (!originalSlots.has(i)) captureDataSlot(i);
659
+ }
660
+ }
661
+ for (const [index, original] of originalSlots) {
662
+ if (!slotReadable[index] || original !== slotEntries[index]) silenceThenable(original);
663
+ }
664
+ for (let pos = 0; pos < (visited?.length ?? total); pos += 1) {
665
+ const i = visited?.[pos] ?? pos;
666
+ if (!slotReadable[i]) {
667
+ deferReject(slotErrors[i]);
668
+ continue;
669
+ }
670
+ const entry = slotEntries[i];
671
+ const normalized = normalizeTask(entry);
672
+ if (normalized.kind === "async") {
673
+ const index = i;
674
+ try {
675
+ subscribeThenable(
676
+ normalized.target,
677
+ normalized.then,
678
+ (res) => {
679
+ if (settled) return;
680
+ let outcome;
681
+ try {
682
+ outcome = readOutcome(res);
683
+ } catch (cause) {
684
+ rejectOnce(cause);
685
+ return;
686
+ }
687
+ if (outcome.ok) succeed(index, outcome.value);
688
+ else fail(outcome.failure);
689
+ },
690
+ rejectOnce
691
+ );
692
+ } catch (cause) {
693
+ deferReject(cause);
694
+ }
695
+ } else if (normalized.kind === "reject") {
696
+ try {
697
+ const desc = Object.getOwnPropertyDescriptor(arraySource, i);
698
+ if (desc && "value" in desc && desc.value !== entry) silenceThenable(desc.value);
699
+ } catch {
700
+ }
701
+ deferReject(normalized.cause);
702
+ } else if (normalized.outcome.ok) {
703
+ succeed(i, normalized.outcome.value);
704
+ } else {
705
+ deferFail(normalized.outcome.failure);
706
+ }
707
+ }
708
+ if (syncTerminal !== void 0) {
709
+ if (syncTerminal.kind === "reject") rejectOnce(syncTerminal.cause);
710
+ else fail(syncTerminal.failure);
711
+ }
712
+ });
713
+ }
714
+ var SYNC_MICRO_YIELD_LIMIT = 64;
715
+ var SYNC_MACRO_YIELD_LIMIT = 1024;
716
+ function map(items, options, fn) {
717
+ let concurrency;
718
+ let parentSignal;
719
+ try {
720
+ if (options === null || typeof options !== "object") {
721
+ return Promise.reject(new TypeError("Trust.map requires an options object with concurrency"));
722
+ }
723
+ concurrency = options.concurrency;
724
+ parentSignal = options.signal;
725
+ } catch (cause) {
726
+ return Promise.reject(cause);
727
+ }
728
+ if (!Number.isSafeInteger(concurrency) || concurrency < 1) {
729
+ return Promise.reject(new RangeError(`Trust.map concurrency must be a finite integer >= 1, got ${String(concurrency)}`));
730
+ }
731
+ if (typeof fn !== "function") {
732
+ return Promise.reject(new TypeError("Trust.map requires a mapper function"));
733
+ }
734
+ let linked;
735
+ try {
736
+ linked = linkSignal(parentSignal);
737
+ } catch (cause) {
738
+ return Promise.reject(cause);
739
+ }
740
+ const { controller, unlink } = linked;
741
+ let activeIterator;
742
+ let activeNext;
743
+ let activeMapper = fn;
744
+ try {
745
+ const iterator = items[Symbol.iterator]();
746
+ if ((typeof iterator !== "object" || iterator === null) && typeof iterator !== "function") {
747
+ throw new TypeError("Trust.map iterator must be an object");
748
+ }
749
+ const candidateNext = iterator.next;
750
+ if (typeof candidateNext !== "function") {
751
+ throw new TypeError("Trust.map iterator.next must be a function");
752
+ }
753
+ activeIterator = iterator;
754
+ activeNext = candidateNext;
755
+ } catch (cause) {
756
+ unlink();
757
+ controller.abort();
758
+ return Promise.reject(cause);
759
+ }
760
+ return new Promise((resolve, reject) => {
761
+ let values = [];
762
+ let nextIndex = 0;
763
+ let active = 0;
764
+ let exhausted = false;
765
+ let pullingIterator = false;
766
+ let pendingClose = false;
767
+ let settled = false;
768
+ let pumping = false;
769
+ let microYieldPending = false;
770
+ let macroYieldPending = false;
771
+ let stepsSinceMacroYield = 0;
772
+ let macroTimer;
773
+ const clearScheduledYield = () => {
774
+ microYieldPending = false;
775
+ macroYieldPending = false;
776
+ if (macroTimer !== void 0) {
777
+ if (typeof globalThis.clearTimeout === "function") globalThis.clearTimeout(macroTimer);
778
+ macroTimer = void 0;
779
+ }
780
+ };
781
+ const closeIterator = () => {
782
+ if (exhausted) {
783
+ activeIterator = null;
784
+ activeNext = null;
785
+ return;
786
+ }
787
+ if (pullingIterator) {
788
+ pendingClose = true;
789
+ return;
790
+ }
791
+ exhausted = true;
792
+ const iter = activeIterator;
793
+ activeIterator = null;
794
+ activeNext = null;
795
+ if (iter === null) return;
796
+ try {
797
+ const returnMethod = iter.return;
798
+ if (returnMethod !== void 0 && returnMethod !== null) {
799
+ Reflect.apply(returnMethod, iter, []);
800
+ }
801
+ } catch {
802
+ }
803
+ };
804
+ const fail = (brandedFailure) => {
805
+ if (settled) return;
806
+ settled = true;
807
+ if (values !== null) {
808
+ values.length = 0;
809
+ values = null;
810
+ }
811
+ activeMapper = null;
812
+ clearScheduledYield();
813
+ closeIterator();
814
+ unlink();
815
+ controller.abort();
816
+ resolve(brandedFailure);
817
+ };
818
+ const rejectOnce = (cause) => {
819
+ if (settled) return;
820
+ settled = true;
821
+ if (values !== null) {
822
+ values.length = 0;
823
+ values = null;
824
+ }
825
+ activeMapper = null;
826
+ clearScheduledYield();
827
+ closeIterator();
828
+ unlink();
829
+ controller.abort();
830
+ reject(cause);
831
+ };
832
+ const finishIfDone = () => {
833
+ if (!settled && exhausted && active === 0 && values !== null) {
834
+ settled = true;
835
+ const completed = values;
836
+ values = null;
837
+ activeMapper = null;
838
+ activeIterator = null;
839
+ activeNext = null;
840
+ clearScheduledYield();
841
+ unlink();
842
+ resolve(ok(completed));
843
+ return true;
844
+ }
845
+ return false;
846
+ };
847
+ const microBatchLimit = concurrency < SYNC_MICRO_YIELD_LIMIT ? concurrency : SYNC_MICRO_YIELD_LIMIT;
848
+ const scheduleMicroYield = () => {
849
+ if (microYieldPending || macroYieldPending || settled) return;
850
+ microYieldPending = true;
851
+ Promise.resolve().then(() => {
852
+ microYieldPending = false;
853
+ pump();
854
+ });
855
+ };
856
+ const scheduleMacroYield = () => {
857
+ if (macroYieldPending || settled) return;
858
+ stepsSinceMacroYield = 0;
859
+ if (typeof globalThis.setTimeout === "function") {
860
+ try {
861
+ macroYieldPending = true;
862
+ macroTimer = globalThis.setTimeout(() => {
863
+ macroTimer = void 0;
864
+ macroYieldPending = false;
865
+ pump();
866
+ }, 0);
867
+ } catch (cause) {
868
+ macroYieldPending = false;
869
+ rejectOnce(cause);
870
+ }
871
+ } else {
872
+ scheduleMicroYield();
873
+ }
874
+ };
875
+ const pump = () => {
876
+ if (pumping || settled || macroYieldPending) return;
877
+ pumping = true;
878
+ let launchesInPump = 0;
879
+ try {
880
+ while (!settled && !exhausted && !macroYieldPending && active < concurrency) {
881
+ let done = false;
882
+ let itemValue;
883
+ let pullThrew = false;
884
+ let pullError;
885
+ pullingIterator = true;
886
+ try {
887
+ const step = Reflect.apply(activeNext, activeIterator, []);
888
+ if (!settled) {
889
+ if ((typeof step !== "object" || step === null) && typeof step !== "function") {
890
+ throw new TypeError("Iterator result must be an object");
891
+ }
892
+ done = Boolean(step.done);
893
+ if (done && !settled) {
894
+ exhausted = true;
895
+ activeIterator = null;
896
+ activeNext = null;
897
+ } else if (!settled) {
898
+ itemValue = step.value;
899
+ }
900
+ }
901
+ } catch (cause) {
902
+ pullThrew = true;
903
+ pullError = cause;
904
+ } finally {
905
+ pullingIterator = false;
906
+ }
907
+ if (pendingClose) {
908
+ pendingClose = false;
909
+ closeIterator();
910
+ }
911
+ if (pullThrew) {
912
+ rejectOnce(pullError);
913
+ return;
914
+ }
915
+ if (settled) {
916
+ return;
917
+ }
918
+ if (done) {
919
+ break;
920
+ }
921
+ const index = nextIndex;
922
+ nextIndex += 1;
923
+ values.push(void 0);
924
+ active += 1;
925
+ launchesInPump += 1;
926
+ stepsSinceMacroYield += 1;
927
+ let out;
928
+ try {
929
+ out = activeMapper(itemValue, controller.signal, index);
930
+ } catch (cause) {
931
+ active -= 1;
932
+ rejectOnce(cause);
933
+ return;
934
+ }
935
+ if (settled) {
936
+ active -= 1;
937
+ silenceThenable(out);
938
+ return;
939
+ }
940
+ const normalized = normalizeTask(out);
941
+ if (normalized.kind === "async") {
942
+ try {
943
+ subscribeThenable(
944
+ normalized.target,
945
+ normalized.then,
946
+ (res) => {
947
+ if (settled) {
948
+ active -= 1;
949
+ return;
950
+ }
951
+ let outcome;
952
+ try {
953
+ outcome = readOutcome(res);
954
+ } catch (cause) {
955
+ active -= 1;
956
+ rejectOnce(cause);
957
+ return;
958
+ }
959
+ if (settled) {
960
+ active -= 1;
961
+ return;
962
+ }
963
+ if (!outcome.ok) {
964
+ active -= 1;
965
+ fail(outcome.failure);
966
+ return;
967
+ }
968
+ if (values !== null) values[index] = outcome.value;
969
+ active -= 1;
970
+ if (finishIfDone()) return;
971
+ stepsSinceMacroYield += 1;
972
+ if (stepsSinceMacroYield >= SYNC_MACRO_YIELD_LIMIT) {
973
+ scheduleMacroYield();
974
+ return;
975
+ }
976
+ scheduleMicroYield();
977
+ },
978
+ (cause) => {
979
+ active -= 1;
980
+ rejectOnce(cause);
981
+ }
982
+ );
983
+ } catch (cause) {
984
+ active -= 1;
985
+ rejectOnce(cause);
986
+ return;
987
+ }
988
+ } else if (normalized.kind === "reject") {
989
+ active -= 1;
990
+ rejectOnce(normalized.cause);
991
+ return;
992
+ } else {
993
+ active -= 1;
994
+ if (!normalized.outcome.ok) {
995
+ fail(normalized.outcome.failure);
996
+ return;
997
+ }
998
+ if (values !== null) values[index] = normalized.outcome.value;
999
+ }
1000
+ if (active < concurrency) {
1001
+ if (stepsSinceMacroYield >= SYNC_MACRO_YIELD_LIMIT) {
1002
+ scheduleMacroYield();
1003
+ return;
1004
+ }
1005
+ if (active > 0 && launchesInPump >= microBatchLimit) {
1006
+ scheduleMicroYield();
1007
+ return;
1008
+ }
1009
+ }
1010
+ }
1011
+ finishIfDone();
1012
+ } catch (cause) {
1013
+ rejectOnce(cause);
1014
+ } finally {
1015
+ pumping = false;
1016
+ }
1017
+ };
1018
+ pump();
1019
+ });
1020
+ }
60
1021
  function getThen(value) {
61
1022
  if ((typeof value !== "object" || value === null) && typeof value !== "function") return void 0;
62
1023
  const then = value.then;
@@ -272,14 +1233,17 @@ async function usingAsync(acquire, use, release, ...rest) {
272
1233
  return runUsingAsync(acquired.value, use, release, onReleaseError);
273
1234
  }
274
1235
  var Result = { ok, err, state };
275
- var Trust = { try: tryResult, tryAsync: tryResultAsync, decide, translate, match, using, usingAsync };
1236
+ var Trust = { try: tryResult, tryAsync: tryResultAsync, decide, translate, match, retry, all, map, using, usingAsync };
276
1237
  export {
277
1238
  Result,
278
1239
  Trust,
1240
+ all,
279
1241
  decide,
280
1242
  err,
1243
+ map,
281
1244
  match,
282
1245
  ok,
1246
+ retry,
283
1247
  state,
284
1248
  translate,
285
1249
  tryResult,