Files
hose-use/src/domains/docs/api.ts
T
gitea 42bf0bfb0b refactor(core/http): 7大通信底座客户端语义化全量重构与合思开放文档客户端纳管
- 彻底移除旧内部狭隘命名与垫片包袱,一步到位全仓整体重命名:
  * session-client.ts ➔ hose-web-session-client.ts (合思 Web 主站会话客户端)
  * script-engine-client.ts ➔ piper-workflow-client.ts (Piper 工作流引擎客户端)
  * unity-client.ts ➔ unity-easo-client.ts (Unity / EASO 运营中台与动态集群客户端)
  * sso-client.ts ➔ sso-auth-client.ts (SSO 与扫码鉴权客户端)
- 新增 hose-docs-client.ts 纳为第 7 大通信底座客户端,收口 docs.ekuaibao.com 文档站点通信
- 端正 Piper 工作流引擎定位,完整覆盖工作流创建、保存、发布、108 类节点编排与 Job 流转
- 彻底整体替换全仓 import 引用与测试套件,新增 clients-semantics.test.ts 自动化校验
- 全量自动化测试 150 files 1155 tests 全部通过,类型检查零错误
2026-11-16 17:15:29 +08:00

180 lines
4.8 KiB
TypeScript

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<string, unknown>;
}
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<DocCatalog> {
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
);
}
}