import TurndownService from "turndown"; const turndown = new TurndownService({ headingStyle: "atx", codeBlockStyle: "fenced", bulletListMarker: "-", }); export type ParseMode = "raw" | "markdown" | "json"; export interface ParseResult { content: unknown; contentType: "text" | "markdown" | "json"; degraded?: boolean; note?: string; } export function parseResponse( body: string, mode: ParseMode, contentTypeHeader?: string, ): ParseResult { switch (mode) { case "raw": return { content: body, contentType: "text" }; case "json": { try { const parsed = JSON.parse(body); return { content: parsed, contentType: "json" }; } catch { return { content: body, contentType: "text", degraded: true, note: "JSON 解析失败,返回原始文本", }; } } case "markdown": { const isHtml = contentTypeHeader?.includes("text/html") || /^\s*<(?:!doctype|html|body|div|p|h[1-6]|ul|ol|table|span|a)\b/i.test(body); if (isHtml) { const md = turndown.turndown(body); return { content: md, contentType: "markdown" }; } return { content: body, contentType: "text" }; } default: return { content: body, contentType: "text" }; } }