import { EkbApiError } from "../../core/errors.js"; import { createHoseDocsClient, DEFAULT_HOSE_DOCS_BASE_URL, } from "../../core/http/hose-docs-client.js"; import { DocCatalogSchema, type DocCatalog, type OpenApiDocItem, } from "./types.js"; export const DEFAULT_DOCS_BASE_URL = DEFAULT_HOSE_DOCS_BASE_URL; interface RawSearchDoc { i: number; t: string; u: string; b?: string[]; h?: string; p?: number; s?: string; } interface RawSearchSection { documents?: RawSearchDoc[]; index?: Record; } export function parseRawSearchIndexToCatalog( rawSections: RawSearchSection[], baseUrl = DEFAULT_DOCS_BASE_URL ): DocCatalog { const rawDocs = rawSections[0]?.documents || []; const rawHeadings = rawSections[1]?.documents || []; const rawParagraphs = rawSections[2]?.documents || []; const apiDocs = rawDocs.filter((d) => d.u?.startsWith("/docs/open-api/")); const items: OpenApiDocItem[] = []; for (const doc of apiDocs) { const headings = rawHeadings .filter((h) => h.p === doc.i) .map((h) => h.t) .filter(Boolean); const paragraphs = rawParagraphs.filter((p) => p.p === doc.i); let method: string | undefined; let path: string | undefined; let curl: string | undefined; let responseSample: string | undefined; let parameters: string | undefined; const sections: Array<{ title: string; content: string }> = []; for (const p of paragraphs) { const sectionTitle = p.s || "概述"; const text = (p.t || "").trim(); if (!text) continue; // Extract HTTP method and path from paragraph text if (!method || !path) { const methodMatch = text.match( /\b(GET|POST|PUT|DELETE|PATCH)\s*(\/api\/[^\s]+)/i ); if (methodMatch) { method = methodMatch[1].toUpperCase(); path = methodMatch[2]; } } // Extract CURL if ( sectionTitle === "CURL" || text.startsWith("curl ") || text.includes("curl --location") ) { curl = text; // Fallback method/path extraction from curl if not found yet if (!method || !path) { const curlMatch = text.match( /--request\s+(GET|POST|PUT|DELETE|PATCH)\s+['"][^'"]*?(\/api\/[^?'"\s]+)/i ); if (curlMatch) { method = curlMatch[1].toUpperCase(); path = curlMatch[2]; } } } else if ( sectionTitle === "成功响应" || sectionTitle === "Response" || (text.startsWith("{") && text.endsWith("}")) ) { responseSample = text; } else if ( sectionTitle.includes("Parameter") || sectionTitle.includes("参数") || sectionTitle.includes("Body") ) { parameters = parameters ? `${parameters}\n${text}` : text; } sections.push({ title: sectionTitle, content: text, }); } const category = doc.b?.[1] || "未分类"; const cleanUrl = doc.u || ""; items.push({ id: doc.i, title: doc.t || "未命名文档", category, url: cleanUrl, permalink: `${baseUrl.replace(/\/+$/, "")}${cleanUrl}`, method, path, breadcrumbs: doc.b || [], headings, sections, parameters, curl, responseSample, }); } const catalog: DocCatalog = { version: "1.0.0", updatedAt: new Date().toISOString(), sourceUrl: `${baseUrl.replace(/\/+$/, "")}/search-index.json`, totalDocs: items.length, totalEndpoints: items.filter((i) => i.method && i.path).length, items, }; return DocCatalogSchema.parse(catalog); } /** * 实时从线上文档站点获取最新接口定义索引 */ export async function fetchLiveDocsCatalog(options?: { baseUrl?: string; timeoutMs?: number; }): Promise { const baseUrl = options?.baseUrl || DEFAULT_DOCS_BASE_URL; const timeoutMs = options?.timeoutMs ?? 15000; const client = createHoseDocsClient({ baseUrl, timeout: timeoutMs }); try { const response = await client.get("search-index.json"); if (!response.ok) { throw new EkbApiError( `获取开放平台文档索引失败: HTTP ${response.status}`, "DOCS_FETCH_FAILED", response.status ); } const raw = (await response.json()) as RawSearchSection[]; if (!Array.isArray(raw) || raw.length === 0) { throw new EkbApiError( "开放平台文档索引数据异常: 返回格式不是有效的分区数组", "DOCS_INVALID_DATA" ); } return parseRawSearchIndexToCatalog(raw, baseUrl); } catch (error: any) { if (error instanceof EkbApiError) throw error; throw new EkbApiError( `请求开放平台文档站点 (${baseUrl}/search-index.json) 失败: ${error?.message || String(error)}`, "DOCS_NETWORK_ERROR", 502 ); } }