export const AOS_ENHANCE_RESULT_TIMEOUT_MS = 30_000; export class EnhanceTerminalError extends Error {} export async function readCompletedEnhanceImage( data: { image?: unknown; image_base64?: unknown }, fetcher: typeof fetch = fetch, ): Promise<{ buffer: Buffer; mimeType: string }> { try { const image = data.image_base64 || data.image; if (typeof image !== "string" || !image) throw new Error("处理结果缺少图片"); let buffer: Buffer; if (/^https?:\/\//i.test(image)) { const response = await fetcher(image, { cache: "no-store", signal: AbortSignal.timeout(60_000), }); if (!response.ok) throw new Error(`HTTP ${response.status}`); buffer = Buffer.from(await response.arrayBuffer()); } else { buffer = Buffer.from(image, "base64"); } const { default: sharp } = await import("sharp"); const { format } = await sharp(buffer).metadata(); if (!format || !["jpeg", "png", "webp", "tiff"].includes(format)) { throw new Error("处理结果的图片格式不可用"); } return { buffer, mimeType: `image/${format}` }; } catch (error) { throw new Error("图片变清晰已完成,但结果图片未取回。", { cause: error }); } } export async function pollTaskResult( apiUrl: string, apiKey: string, taskId: string, delay = 1000, timeout = 120000, fetcher: typeof fetch = fetch, ): Promise { const deadline = Date.now() + timeout; while (Date.now() < deadline) { try { const response = await fetcher( `${apiUrl}/api/tasks/visual/scale/${encodeURIComponent(taskId)}`, { method: "GET", headers: { "X-API-KEY": apiKey }, signal: AbortSignal.timeout( Math.max(1, Math.min(AOS_ENHANCE_RESULT_TIMEOUT_MS, deadline - Date.now())), ), }, ); const result = await response.json(); if (result?.data) { const state = Number(result.data.state); if (state < 0) { throw new EnhanceTerminalError( `AOS任务失败: ${String(result.data.err_message || result.data.err_info || result.data.state_detail || result.data.state)}`, ); } if (response.ok && (state === 1 || (!(state > 1) && result.data.progress >= 100))) { return result; } } } catch (error) { if (error instanceof EnhanceTerminalError) throw error; } const remaining = deadline - Date.now(); if (remaining > 0) await new Promise((resolve) => setTimeout(resolve, Math.min(delay, remaining))); } throw Error("轮询超时"); }