// app/api/convert/route.ts
export const runtime = "nodejs";
export const maxDuration = 300;
async function pollJob(jobId: string): Promise<string> {
const key = process.env.FLASH_MD_API_KEY!;
const url = process.env.FLASH_MD_API_URL!;
while (true) {
await new Promise((r) => setTimeout(r, 5000));
const res = await fetch(`${url}/jobs/${jobId}`, {
headers: { "x-api-key": key },
});
const data = await res.json();
if (data.status === "completed") return data.body;
if (data.status === "failed") throw new Error(data.error);
}
}
export async function POST(request: Request) {
const form = await request.formData();
const file = form.get("file");
if (!(file instanceof File)) {
return Response.json({ error: "Missing file" }, { status: 400 });
}
const res = await fetch(
`${process.env.FLASH_MD_API_URL}/convert/raw?filename=${encodeURIComponent(file.name)}&mode=fast`,
{
method: "POST",
headers: {
"x-api-key": process.env.FLASH_MD_API_KEY!,
"content-type": file.type || "application/octet-stream",
},
body: file,
}
);
if (res.status === 202) {
const job = await res.json();
const markdown = await pollJob(job.job_id);
return new Response(markdown, {
headers: { "content-type": "text/markdown; charset=utf-8" },
});
}
return new Response(await res.text(), {
status: res.status,
headers: { "content-type": res.headers.get("content-type") || "text/markdown" },
});
}