import type { Ref } from '@stacksjs/stx' import { ref } from '@stacksjs/stx' export type UseAsyncQueueTask = () => Promise export interface UseAsyncQueueResult { state: 'fulfilled' | 'rejected' | 'pending' data?: T } export interface UseAsyncQueueReturn { activeIndex: Ref result: Ref[]> isFinished: Ref } /** * Sequential async task queue. * Runs tasks one after another, tracking status and results. * * @param tasks - Array of async task functions to execute sequentially */ export function useAsyncQueue(tasks: UseAsyncQueueTask[]): UseAsyncQueueReturn { const activeIndex = ref(-1) const isFinished = ref(false) const result = ref[]>( tasks.map(() => ({ state: 'pending' as const })), ) as Ref[]> async function runTasks(): Promise { for (let i = 0; i < tasks.length; i++) { activeIndex.value = i const task = tasks[i] if (!task) continue try { const data = await task() result.value = result.value.map((r, idx) => idx === i ? { state: 'fulfilled' as const, data } : r, ) } catch (e) { result.value = result.value.map((r, idx) => idx === i ? { state: 'rejected' as const, data: e as T } : r, ) } } activeIndex.value = tasks.length isFinished.value = true } runTasks() return { activeIndex, result, isFinished } }