/** * Execute async work with a bounded number of in-flight tasks. */ export async function runWithConcurrency( items: T[], limit: number, worker: (item: T) => Promise ): Promise { if (items.length === 0) return; const concurrency = Math.max(1, Math.floor(limit)); let nextIndex = 0; async function runWorker(): Promise { while (true) { const currentIndex = nextIndex; nextIndex += 1; if (currentIndex >= items.length) { return; } await worker(items[currentIndex]); } } const workerCount = Math.min(concurrency, items.length); await Promise.all(Array.from({ length: workerCount }, () => runWorker())); }