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