class TimeoutError extends Error { code = "ETIMEOUT"; constructor(message: string) { super(message); this.name = "TimeoutError"; } } export const withTimeout = async (promise: Promise, ms: number, label: string): Promise => { let timeout: ReturnType | undefined; try { return await Promise.race([ promise, new Promise((_, reject) => { timeout = setTimeout(() => reject(new TimeoutError(`${label} timed out after ${ms}ms`)), ms); }), ]); } finally { if (timeout) clearTimeout(timeout); } };