//#region src/media-shared/http/deadline.ts
/**
* Pick the smallest *positive* timeout among the inputs.
*
* - Negative / zero / non-finite values are ignored.
* - Returns undefined when no valid timeout is supplied.
*/
/**
* Effective positive timeout for outbound provider calls, or `fallbackMs` when
* neither per-call nor provider-default timeouts are set.
*/
function pickTimeoutMsOrFallback(timeoutMs, providerDefaultMs, fallbackMs) {
	return pickEffectiveTimeoutMs({
		timeoutMs,
		providerDefaultMs
	}) ?? fallbackMs;
}
function pickEffectiveTimeoutMs(input) {
	const candidates = [];
	if (typeof input.timeoutMs === "number" && Number.isFinite(input.timeoutMs) && input.timeoutMs > 0) candidates.push(input.timeoutMs);
	if (typeof input.providerDefaultMs === "number" && Number.isFinite(input.providerDefaultMs) && input.providerDefaultMs > 0) candidates.push(input.providerDefaultMs);
	if (candidates.length === 0) return void 0;
	return Math.min(...candidates);
}
/**
* Build a combined deadline.
*
* Always returns a fresh {@link AbortController} so that callers can pass
* `signal` directly to `fetch()` without leaking listeners on long-lived
* upstream signals.
*/
function resolveDeadline(input) {
	const controller = new AbortController();
	const timeoutMs = pickEffectiveTimeoutMs(input);
	const cleanups = [];
	if (timeoutMs !== void 0) {
		const timer = setTimeout(() => {
			controller.abort(new TimeoutAbortError(timeoutMs));
		}, timeoutMs);
		if (typeof timer.unref === "function") timer.unref();
		cleanups.push(() => clearTimeout(timer));
	}
	const upstream = input.signal;
	if (upstream) if (upstream.aborted) controller.abort(upstream.reason);
	else {
		const onAbort = () => controller.abort(upstream.reason);
		upstream.addEventListener("abort", onAbort, { once: true });
		cleanups.push(() => upstream.removeEventListener("abort", onAbort));
	}
	return {
		timeoutMs,
		signal: controller.signal,
		cleanup: () => {
			for (const fn of cleanups) try {
				fn();
			} catch {}
		}
	};
}
/** Concrete error class so callers can distinguish deadline-aborts from upstream-aborts. */
var TimeoutAbortError = class extends Error {
	timeoutMs;
	constructor(timeoutMs) {
		super(`Provider HTTP call timed out after ${timeoutMs}ms`);
		this.name = "TimeoutAbortError";
		this.timeoutMs = timeoutMs;
	}
};
function isTimeoutAbortError(e) {
	return e instanceof TimeoutAbortError;
}
//#endregion
export { TimeoutAbortError, isTimeoutAbortError, pickEffectiveTimeoutMs, pickTimeoutMsOrFallback, resolveDeadline };

//# sourceMappingURL=deadline.js.map