import type { Complete } from "race-cancellation"; import { oneshot } from "race-cancellation"; import type { Response } from "../types"; export default function newResponses(): [UsingResponse, ResolveResponse] { let seq = 0; const pending = new Map void>(); return [usingResponse, resolveResponse]; function resolveResponse(response: Response): void { const resolve = pending.get(response.id); if (resolve !== undefined) { resolve(response); } } async function usingResponse( using: UsingResponseCallback, ): Promise> { const id = seq++; try { const [response, resolve] = oneshot>(); pending.set(id, resolve as Complete); return await using(id, response); } finally { pending.delete(id); } } } export type ResolveResponse = (response: Response) => void; export type UsingResponse = ( using: UsingResponseCallback, ) => Promise>; export type UsingResponseCallback = ( id: number, response: () => Promise>, ) => Promise>;