import PQueue from "p-queue"; import { verifyRequest } from "./verify.js"; import { renderTemplate } from "./render.js"; import type { LureCache } from "./loader.js"; import type { LureRequest } from "./types.js"; interface QueueOptions { cache: LureCache; callback: (prompt: string, config: unknown) => Promise; maxAttempts: number; } export function createQueue(options: QueueOptions): { enqueue(lurePath: string, req: LureRequest): void; drain(): Promise; } { const { cache, callback, maxAttempts } = options; const queue = new PQueue({ concurrency: 1 }); return { enqueue(lurePath: string, req: LureRequest): void { void queue.add(async () => { const lure = cache.get(lurePath); if (lure === undefined) { return; } const verified = await verifyRequest(lure, req); if (!verified) { return; } const prompt = await renderTemplate(lure, req); let lastError: unknown; for (let attempt = 0; attempt < maxAttempts; attempt++) { try { await callback(prompt, lure.frontmatter.config); return; } catch (error) { lastError = error; } } console.error(`Callback failed after ${maxAttempts} attempts for ${lurePath}:`, lastError); }); }, drain(): Promise { return queue.onIdle(); }, }; }