|
1 | 1 | import type { Fn } from './types' |
2 | 2 |
|
3 | | -import { emptyFunction } from './constants' |
4 | | - |
5 | 3 | /** |
6 | 4 | * Checks whether a value is a promise-like object. |
7 | 5 | * @param maybePromiseLike - the value to check |
@@ -16,18 +14,39 @@ export const isPromiseLike = <T>( |
16 | 14 | typeof (maybePromiseLike as PromiseLike<T>).then === 'function' |
17 | 15 |
|
18 | 16 | /** |
19 | | - * Suppresses rejections of a promise-like value, and of the promise its own |
20 | | - * `then` call returns, so neither surfaces as an unhandled rejection. |
| 17 | + * Suppresses rejections of a promise-like value across its rejection channel, |
| 18 | + * the promise its own `then` call returns, and promise-like values it settles |
| 19 | + * with, so none surfaces as an unhandled rejection. Only raw handlers are |
| 20 | + * attached, never assimilated, so handling is realm-agnostic and bounded: |
| 21 | + * every value is attached at most once per probe, so a value reachable |
| 22 | + * through several channels costs a single attach, and settled values and |
| 23 | + * returned promises are followed with a budget of `depth` levels only, which |
| 24 | + * ends rejection and fulfillment cycles of any shape and keeps a self-nesting |
| 25 | + * thenable from generating work endlessly. A thenable that keeps settling new |
| 26 | + * values on persistent handlers can still keep making work on its own; no |
| 27 | + * probe can detach from it. |
21 | 28 | * @param value - the promise-like value to mark handled |
| 29 | + * @param depth - the remaining budget for following settled values |
| 30 | + * @param seen - values already attached to by this probe |
22 | 31 | */ |
23 | | -export const markHandled = (value: unknown): void => { |
| 32 | +export const markHandled = ( |
| 33 | + value: unknown, |
| 34 | + depth = 2, |
| 35 | + seen: WeakSet<object> = new WeakSet() |
| 36 | +): void => { |
24 | 37 | try { |
25 | | - const returned = (value as PromiseLike<unknown>).then( |
26 | | - emptyFunction, |
27 | | - emptyFunction |
28 | | - ) |
29 | | - if (isPromiseLike(returned)) { |
30 | | - Promise.resolve(returned).catch(emptyFunction) |
| 38 | + if (!isPromiseLike(value) || seen.has(value)) { |
| 39 | + return |
| 40 | + } |
| 41 | + seen.add(value) |
| 42 | + const settle = (settled: unknown): void => { |
| 43 | + if (depth >= 0) { |
| 44 | + markHandled(settled, depth - 1, seen) |
| 45 | + } |
| 46 | + } |
| 47 | + const returned = value.then(settle, settle) |
| 48 | + if (depth >= 0) { |
| 49 | + markHandled(returned, depth - 1, seen) |
31 | 50 | } |
32 | 51 | } catch { |
33 | 52 | // Treat a throwing `then` as handled |
|