export type HttpResponse = { status: number; body: string };export class NetworkError extends Error { public readonly kind = "network" as const; constructor(message: string) { super(message); }}export type Fetcher = (url: string) => Promise<HttpResponse>;export type RetryOptions = { retries: number; baseDelayMs: number; sleep: (ms: number) => Promise<void>;};export class HttpError extends Error { public readonly kind = "http" as const; constructor(public readonly status: number) { super(`http ${status}`); }}export class ExhaustedError extends Error { public readonly kind = "exhausted" as const; constructor( public readonly attempts: number, public readonly lastStatus?: number, ) { super(`exhausted after ${attempts} attempts`); }}/** Resolves with the response body. Rejects with HttpError or ExhaustedError. */export async function retryFetch(fetcher: Fetcher, url: string, options: RetryOptions): Promise<string> { const { retries, baseDelayMs, sleep } = options; for (let attempt = 0; ; attempt += 1) { let lastStatus: number | undefined; try { const res = await fetcher(url); if (res.status >= 200 && res.status <= 299) return res.body; if (res.status < 500 || res.status > 599) throw new HttpError(res.status); lastStatus = res.status; } catch (e) { if (e instanceof HttpError) throw e; lastStatus = undefined; } if (attempt >= retries) throw new ExhaustedError(attempt + 1, lastStatus); await sleep(baseDelayMs * 2 ** attempt); }}