export async function withTimeout(promise, timeoutMs, message) {
    let timer;
    const timeout = new Promise((_, reject) => {
        timer = setTimeout(() => reject(new Error(message)), Math.max(1, timeoutMs));
        timer.unref?.();
    });
    try {
        return await Promise.race([promise, timeout]);
    }
    finally {
        if (timer)
            clearTimeout(timer);
    }
}
export async function withTimeoutOrNull(promise, timeoutMs) {
    try {
        return await withTimeout(promise, timeoutMs, 'operation timed out');
    }
    catch {
        return null;
    }
}
export function clampTimeoutMs(value, fallbackMs, minMs, maxMs) {
    if (typeof value !== 'number' || !Number.isFinite(value))
        return fallbackMs;
    return Math.max(minMs, Math.min(maxMs, Math.trunc(value)));
}
