export class OperationTimeoutError extends Error { constructor(message: string) { super(message); this.name = "TimeoutError"; } } export function withDeadline( promise: Promise, timeoutMs: number, message: string, onTimeout?: (error: OperationTimeoutError) => void, ): Promise { let timer: ReturnType | null = null; const timeout = new Promise((_resolve, reject) => { timer = setTimeout(() => { const error = new OperationTimeoutError(message); reject(error); onTimeout?.(error); }, timeoutMs); }); return Promise.race([promise, timeout]).finally(() => { if (timer) clearTimeout(timer); }); }