feat(docs): 新增合思开放平台官方接口文档检索独立业务域与 CLI 客户端
- 新增 `src/domains/docs/` 领域(api.ts, tools.ts, types.ts, README.docs.md, docs.test.ts) - 实现从线上 `docs.ekuaibao.com/search-index.json` 实时拉取最新规范与端点提取能力 - 集成多级缓存(L1 内存 + L2 SQLite)与 `specs/docs-catalog.json` 静态预编译保底,支持零网络离线毫秒级检索 - 提供 270+ 个 OpenAPI HTTP 接口端点、参数表格、CURL 示范与成功响应示例的高精度解析与结构化输出 - 注册 `hose-use docs` CLI 命令(search, show, categories, sync)及 `doc`, `api-doc` 别名 - 严格遵循 AGENTS.md 架构分层约束,全量 1144+ 自动化单测与 tsc 类型检查 100% 通过
This commit is contained in:
1 parent
448dd438ff
commit
4f572ad9c1
11 files changed
+1013
-2
No files matched your search
@@ -0,0 +1 @@
|
||||
{"version":"1.0.0","updatedAt":"2026-11-16T08:08:21.159Z","sourceUrl":"https://docs.ekuaibao.com/search-index.json","totalDocs":330,"totalEndpoints":279,"items":[{"id":3788,"title":"下载附件","category":"附件","url":"/docs/open-api/attachment/attachment-download","permalink":"https://docs.ekuaibao.com/docs/open-api/attachment/attachment-download","method":"POST","path":"/api/openapi/v2/attachment/downloadurls","breadcrumbs":["Open API","附件"],"headings":["Query Parameters","Body Parameters","CURL","成功响应","失败响应","钉盘附件下载","阿里云OSS CURL"],"sections":[{"title":"下载附件","content":"通过附件的 id、key 去获取附件的下载链接。 POST/api/openapi/v2/attachment/downloadurls 更新日志 2.3.1 🚀 优化了接口,支持ISV应用钉盘附件下载。 1.6.3 🐞 优化了接口 HTTP 500 错误,输出报错信息。"},{"title":"Query Parameters","content":"名称 类型 描述 是否必填 默认值 备注 accessToken String 认证token 必填 - 通过 获取授权 获取 accessToken"},{"title":"Body Parameters","content":"名称 类型 描述 是否必填 默认值 备注 -- Array 数组参数 必填 - 数组参数,最大支持 100 个参数 ∟ id String 文件fileId 必填 - 上传附件 接口返回的 fileId 字段 接口下载单据上的附件时,可通过 获取单据详情 获取 attachments 字段的 fileId 值 ∟ key String 文件key 必填 - 上传附件 接口返回的 key 字段 接口下载单据上的附件时,可通过 获取单据详情 获取 attachments 字段的 key 值,注意: key 值前缀是 DP:时,表示该附件是钉盘附件 。 ∟ expiration Number 下载链接有效时间 必填 - 下载链接在多长时间内有效,单位:秒,最大 1800 秒 ,钉盘附件该值无效"},{"title":"CURL","content":"curl --location --request POST 'https://app.ekuaibao.com/api/openapi/v2/attachment/downloadurls?accessToken=UvsbtOEHTsk000' \\ --header 'Content-Type: application/json' \\ --data-raw '[ { \"id\": \"61sbwX3DEAgk00\", \"key\": \"openapi0306c2d1-7a5b-4e96-8172-60c5ee0f971e-kotlin简介.docx\", \"expiration\": 1000 }, { \"id\": \"136634573449\", \"key\": \"DP:{\\\"fileId\\\":\\\"136634437985\\\",\\\"fileName\\\":\\\"128163bbba83.jpg\\\",\\\"fileSize\\\":2985928,\\\"fileType\\\":\\\"jpg\\\",\\\"spaceId\\\":\\\"7215288789\\\"}\", \"expiration\": 1000 } ]'"},{"title":"成功响应","content":"tip url 是文件下载路径,thumbUrl 是指缩略图的下载路径。 thumbUrl 只针对图片有效,PDF文件生成的链接是不可用的。 key 下载钉盘附件时,url 和 thumbUrl 都是 阿里OSS 文件链接,保存文件时需要根据key值内的 fileType 值来判断文件类型。 headers 只针对钉盘附件有效,下载文件时需要将 headers传入,否则会下载失败。 [ { \"id\": \"61sbwX3DEAgk00\", \"key\": \"openapi0306c2d1-7a5b-4e96-8172-60c5ee0f971e-kotlin简介.docx\", \"url\": \"https://ekuaibao.oss-cn-hangzhou.aliyuncs.com/openapi0306c2d1-7a5b-4e96-8172-60c5ee0f971e-kotlin%E7%AE%80%E4%BB%8B.docx?Expires=1599099810&OSSAccessKeyId=STS.NUTdxysMYQXwZApA734jgqnJb&Signature=wTRfcimdrHhXbL3efe8MftOSOmo%3D&security-token=CAIS8AF1q6Ft5B2yfSjIr5bhL8LNnpJ45pqcWGfBpTdmOOVLnqvhgDz2IHlPdHZhBekYtPszmW9Z6%2FsdlqF%2BSIJETEbNapPbRkWwXEXzDbDasumZsJYm6vT8a0XxZjf%2F2MjNGZabKPrWZvaqbX3diyZ32sGUXD6%2BXlujQ%2Fbr4NwdGbZxZASjaidcD9p7PxZrrNRgVUHcLvGwKBXn8AGyZQhKwlMk1zojtf7lmpTMtUuE0ALAp7VL99irEP%2BNdNJxOZpzadCx0dFte7DJuCwqsEERpPgn0PUao2ib447MXgQO%2BXScOu%2FT6cZ0MBRpwUXA2EKANZEagAFRCqgjZY6QvIiWMtTWb7UIfba4ebfujIHa7cn7sA3r0vGyNUnObhl5H5zW4cc%2FM%2FiHehACg83wRu189TUg4Qt5MRZ0KuYre7mpa4NWPJpcILHkRjLBR2YoL6Z27iqhNbtcZoezq%2B4ky3N60IIaXhUoYJcteXtru12W%2BiLzfiB%2FuA%3D%3D\", \"thumbUrl\": \"https://ekuaibao.oss-cn-hangzhou.aliyuncs.com/openapi0306c2d1-7a5b-4e96-8172-60c5ee0f971e-kotlin%E7%AE%80%E4%BB%8B.docx?Expires=1599099810&OSSAccessKeyId=STS.NUTdxysMYQXwZApA734jgqnJb&Signature=evQnFfd4YhL5zkFMovDl9ZfVdlw%3D&x-oss-process=image%2Fresize%2Cw_120%2Ch_120&security-token=CAIS8AF1q6Ft5B2yfSjIr5bhL8LNnpJ45pqcWGfBpTdmOOVLnqvhgDz2IHlPdHZhBekYtPszmW9Z6%2FsdlqF%2BSIJETEbNapPbRkWwXEXzDbDasumZsJYm6vT8a0XxZjf%2F2MjNGZabKPrWZvaqbX3diyZ32sGUXD6%2BXlujQ%2Fbr4NwdGbZxZASjaidcD9p7PxZrrNRgVUHcLvGwKBXn8AGyZQhKwlMk1zojtf7lmpTMtUuE0ALAp7VL99irEP%2BNdNJxOZpzadCx0dFte7DJuCwqsEERpPgn0PUao2ib447MXgQO%2BXScOu%2FT6cZ0MBRpwUXA2EKANZEagAFRCqgjZY6QvIiWMtTWb7UIfba4ebfujIHa7cn7sA3r0vGyNUnObhl5H5zW4cc%2FM%2FiHehACg83wRu189TUg4Qt5MRZ0KuYre7mpa4NWPJpcILHkRjLBR2YoL6Z27iqhNbtcZoezq%2B4ky3N60IIaXhUoYJcteXtru12W%2BiLzfiB%2FuA%3D%3D\" }, { \"id\": \"136634573449\", \"key\": \"DP:{\\\"fileId\\\":\\\"136634437985\\\",\\\"fileName\\\":\\\"128163bbba83.jpg\\\",\\\"fileSize\\\":2985928,\\\"fileType\\\":\\\"jpg\\\",\\\"spaceId\\\":\\\"7215288789\\\"}\", \"url\": \"https://sh-dualstack.trans.dingtalk.com/yundisk0/iAEIAqRmaWxlA6h5dW5kaXNrMATOITK4JgXNEKcGzTyBB85mF5ENCM24VQ.file\", \"thumbUrl\": \"https://sh-dualstack.trans.dingtalk.com/yundisk0/iAEIAqRmaWxlA6h5dW5kaXLine truncated
|
||||
@@ -904,6 +904,41 @@ export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
|
||||
...flagList("all a logout admin save import persist switch current overwrite candidates list-candidates qr check", "boolean"),
|
||||
...flagList("status", "boolean-or-value")
|
||||
}
|
||||
},
|
||||
"docs": {
|
||||
"summary": "合思开放平台官方接口文档与端点规范检索",
|
||||
"usage": "hose-use docs <search|show|categories|sync> [关键词|路径] [--json]",
|
||||
"commands": {
|
||||
"search": "按关键词、分类或方法检索开放平台 HTTP 接口",
|
||||
"show": "查看指定接口的完整规范、参数定义、CURL 与响应示例",
|
||||
"categories": "查看开放平台所有业务模块分类与端点统计",
|
||||
"sync": "强制与线上文档中心全量同步最新索引"
|
||||
},
|
||||
"aliases": [
|
||||
"doc",
|
||||
"api-doc",
|
||||
"api-docs"
|
||||
],
|
||||
"commandAliases": {
|
||||
"find": "search",
|
||||
"list": "search",
|
||||
"ls": "search",
|
||||
"get": "show",
|
||||
"info": "show",
|
||||
"cat": "show",
|
||||
"read": "show",
|
||||
"detail": "show",
|
||||
"category": "categories",
|
||||
"cats": "categories",
|
||||
"modules": "categories",
|
||||
"groups": "categories",
|
||||
"update": "sync",
|
||||
"refresh": "sync"
|
||||
},
|
||||
flags: {
|
||||
...flagList("keyword query q category cat module method m path p target id name url limit count n", "value"),
|
||||
...flagList("refresh sync force", "boolean")
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { runCli } from "../runner.js";
|
||||
|
||||
describe("CLI - 开放平台官方接口文档域 (docs / openapi-docs)", () => {
|
||||
test("hose-use docs 输出开放平台文档概览与端点总数", async () => {
|
||||
const res = await runCli(["docs"]);
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("合思开放平台官方文档中心");
|
||||
expect(res.stdout).toContain("文档总数:");
|
||||
expect(res.stdout).toContain("端点总数:");
|
||||
expect(res.stdout).toContain("hose-use docs search");
|
||||
});
|
||||
|
||||
test("hose-use docs --json 输出概览结构化元数据", async () => {
|
||||
const res = await runCli(["docs", "--json"]);
|
||||
expect(res.exitCode).toBe(0);
|
||||
const data = JSON.parse(res.stdout);
|
||||
expect(data.totalDocs).toBeGreaterThan(100);
|
||||
expect(data.totalEndpoints).toBeGreaterThan(100);
|
||||
});
|
||||
|
||||
test("hose-use docs search roleDefGroups 能检索出角色组接口", async () => {
|
||||
const res = await runCli(["docs", "search", "roleDefGroups"]);
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("GET");
|
||||
expect(res.stdout).toContain("/api/openapi/v1/roleDefGroups");
|
||||
expect(res.stdout).toContain("查询角色组和角色");
|
||||
expect(res.stdout).toContain("企业通讯录");
|
||||
});
|
||||
|
||||
test("hose-use docs search 角色组 --json 输出精准结构化搜索结果", async () => {
|
||||
const res = await runCli(["docs", "search", "角色组", "--json"]);
|
||||
expect(res.exitCode).toBe(0);
|
||||
const data = JSON.parse(res.stdout);
|
||||
expect(data.total).toBeGreaterThanOrEqual(1);
|
||||
expect(data.items.some((i: any) => i.path === "/api/openapi/v1/roleDefGroups")).toBe(true);
|
||||
});
|
||||
|
||||
test("hose-use docs show /api/openapi/v1/roleDefGroups 展示完整接口规格与 CURL 示范", async () => {
|
||||
const res = await runCli(["docs", "show", "/api/openapi/v1/roleDefGroups"]);
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("查询角色组和角色");
|
||||
expect(res.stdout).toContain("GET");
|
||||
expect(res.stdout).toContain("/api/openapi/v1/roleDefGroups");
|
||||
expect(res.stdout).toContain("CURL 请求示范");
|
||||
expect(res.stdout).toContain("成功响应示例");
|
||||
expect(res.stdout).toContain("accessToken");
|
||||
});
|
||||
|
||||
test("hose-use docs show /api/openapi/v1/roleDefGroups --json 返回全量结构化文档项", async () => {
|
||||
const res = await runCli(["docs", "show", "/api/openapi/v1/roleDefGroups", "--json"]);
|
||||
expect(res.exitCode).toBe(0);
|
||||
const doc = JSON.parse(res.stdout);
|
||||
expect(doc.path).toBe("/api/openapi/v1/roleDefGroups");
|
||||
expect(doc.method).toBe("GET");
|
||||
expect(doc.category).toBe("企业通讯录");
|
||||
expect(doc.permalink).toContain("get-roles-group");
|
||||
});
|
||||
|
||||
test("hose-use docs show 未知目标时返回友好错误", async () => {
|
||||
const res = await runCli(["docs", "show", "non_existing_api_path_xyz"]);
|
||||
expect(res.exitCode).toBe(1);
|
||||
expect(res.stderr).toContain("NOT FOUND");
|
||||
});
|
||||
|
||||
test("hose-use docs categories 输出所有业务分类与端点分布", async () => {
|
||||
const res = await runCli(["docs", "categories"]);
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("合思开放平台业务模块分类");
|
||||
expect(res.stdout).toContain("企业通讯录");
|
||||
expect(res.stdout).toContain("预算");
|
||||
expect(res.stdout).toContain("单据");
|
||||
});
|
||||
|
||||
test("hose-use doc 别名也能正常调用", async () => {
|
||||
const res = await runCli(["doc", "search", "roleDefGroups"]);
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("/api/openapi/v1/roleDefGroups");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,237 @@
|
||||
import { booleanOption, numberOption, stringOption } from "../parser.js";
|
||||
import { printJson, printKeyValue, printTable } from "../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||
import {
|
||||
getDocDetail,
|
||||
getDocsCatalog,
|
||||
listCategories,
|
||||
searchDocs,
|
||||
syncDocsCatalog,
|
||||
} from "../../domains/docs/tools.js";
|
||||
|
||||
export async function handleDocsCommand(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
const action = parsed.action?.toLowerCase() || "";
|
||||
const forceRefresh =
|
||||
booleanOption(parsed.options, ["refresh", "force", "sync"]) ||
|
||||
action === "sync";
|
||||
|
||||
// 1. 同步命令: hose-use docs sync
|
||||
if (action === "sync") {
|
||||
const res = await syncDocsCatalog();
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(res, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
return {
|
||||
stdout: `====== 开放平台文档同步完成 ======\n文档总数: ${res.totalDocs}\n接口端点: ${res.totalEndpoints}\n数据源: ${res.source}\n更新时间: ${res.updatedAt}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
// 2. 分类列表: hose-use docs categories
|
||||
if (["categories", "category", "cats", "modules"].includes(action)) {
|
||||
const cats = await listCategories({ forceRefresh });
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({ count: cats.length, categories: cats }, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
const rows = cats.map((c, i) => [
|
||||
i + 1,
|
||||
c.name,
|
||||
`${c.count} 篇`,
|
||||
`${c.endpointsCount} 个`,
|
||||
]);
|
||||
const table = printTable(["#", "业务分类", "文档篇数", "HTTP 端点数"], rows);
|
||||
return {
|
||||
stdout: `====== 合思开放平台业务模块分类 (共 ${cats.length} 个) ======\n\n${table}\n\n提示: 运行 hose-use docs search --category=<模块名> 可查看该模块下的所有接口\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
// 3. 详情命令: hose-use docs show <target>
|
||||
if (["show", "get", "info", "cat", "read"].includes(action)) {
|
||||
const target = parsed.args[0] || stringOption(parsed.options, ["path", "url", "id", "name", "target"]);
|
||||
if (!target) {
|
||||
throw new Error("请指定要查看的接口路径、文档 URL 或名称: hose-use docs show <接口或URL>");
|
||||
}
|
||||
|
||||
const doc = await getDocDetail(target, { forceRefresh });
|
||||
if (!doc) {
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({ found: false, target }, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `[NOT FOUND] 未找到匹配的文档或接口: ${target}\n提示: 可以先运行 hose-use docs search ${target} 检索相近接口。\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(doc, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
let out = `====== ${doc.title} ======\n`;
|
||||
out += printKeyValue({
|
||||
"业务模块": doc.category,
|
||||
"HTTP 方法": doc.method || "非端点/指南页面",
|
||||
"接口路径": doc.path || "-",
|
||||
"在线文档": doc.permalink,
|
||||
"文档标识": `#${doc.id}`,
|
||||
});
|
||||
|
||||
if (doc.parameters) {
|
||||
out += `\n\n### 参数规格与定义\n${doc.parameters}\n`;
|
||||
}
|
||||
|
||||
if (doc.curl) {
|
||||
out += `\n### CURL 请求示范\n\`\`\`bash\n${doc.curl}\n\`\`\`\n`;
|
||||
}
|
||||
|
||||
if (doc.responseSample) {
|
||||
out += `\n### 成功响应示例\n\`\`\`json\n${doc.responseSample}\n\`\`\`\n`;
|
||||
}
|
||||
|
||||
return { stdout: `${out}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
// 4. 搜索命令 (默认行为): hose-use docs search <keyword> 或 hose-use docs <keyword>
|
||||
const isSearchAction = ["search", "find", "list", "ls", ""].includes(action);
|
||||
if (isSearchAction) {
|
||||
const keyword =
|
||||
(action === "search" || action === "find" ? parsed.args[0] : action || parsed.args[0]) ||
|
||||
stringOption(parsed.options, ["keyword", "q", "query"]);
|
||||
|
||||
const category = stringOption(parsed.options, ["category", "cat", "module"]);
|
||||
const method = stringOption(parsed.options, ["method", "m"]);
|
||||
const path = stringOption(parsed.options, ["path", "p"]);
|
||||
const limit = numberOption(parsed.options, ["limit", "n", "count"], 25);
|
||||
|
||||
// 如果没有任何搜索条件且没有关键词,展示全局概览
|
||||
if (!keyword && !category && !method && !path && !action) {
|
||||
const catalog = await getDocsCatalog({ forceRefresh });
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
totalDocs: catalog.totalDocs,
|
||||
totalEndpoints: catalog.totalEndpoints,
|
||||
sourceUrl: catalog.sourceUrl,
|
||||
updatedAt: catalog.updatedAt,
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
return {
|
||||
stdout: `====== 合思开放平台官方文档中心 ======
|
||||
文档总数: ${catalog.totalDocs} 篇
|
||||
端点总数: ${catalog.totalEndpoints} 个
|
||||
数据来源: ${catalog.sourceUrl}
|
||||
更新时间: ${catalog.updatedAt}
|
||||
|
||||
常用子命令:
|
||||
hose-use docs search <关键词> 检索开放平台 HTTP 接口与文档
|
||||
hose-use docs show <路径|名称|URL> 查看单篇接口规格、参数表格与 CURL 响应
|
||||
hose-use docs categories 查看 26+ 个业务分类及其端点数
|
||||
hose-use docs sync 强制与线上最新文档中心全量同步
|
||||
`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const searchRes = await searchDocs(
|
||||
{
|
||||
keyword,
|
||||
category,
|
||||
method,
|
||||
path,
|
||||
limit,
|
||||
},
|
||||
{ forceRefresh }
|
||||
);
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
const summaryItems = searchRes.items.map((item) => ({
|
||||
id: item.id,
|
||||
title: item.title,
|
||||
category: item.category,
|
||||
method: item.method,
|
||||
path: item.path,
|
||||
url: item.url,
|
||||
permalink: item.permalink,
|
||||
}));
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
total: searchRes.total,
|
||||
count: summaryItems.length,
|
||||
keyword: searchRes.keyword,
|
||||
category: searchRes.category,
|
||||
method: searchRes.method,
|
||||
items: summaryItems,
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
if (searchRes.items.length === 0) {
|
||||
return {
|
||||
stdout: `未找到匹配的文档或接口 (关键词: ${keyword || "-"}, 分类: ${category || "-"}, 方法: ${method || "-"})\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const rows = searchRes.items.map((item) => [
|
||||
item.method || "DOC",
|
||||
item.path || item.url,
|
||||
item.title,
|
||||
item.category,
|
||||
]);
|
||||
|
||||
const table = printTable(["Method", "Path / URL", "标题", "分类"], rows);
|
||||
const filterDesc = [
|
||||
keyword ? `关键词: '${keyword}'` : "",
|
||||
category ? `分类: '${category}'` : "",
|
||||
method ? `方法: '${method}'` : "",
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(", ");
|
||||
|
||||
return {
|
||||
stdout: `====== 开放平台接口搜索结果 (找到 ${searchRes.total} 条${filterDesc ? ` | ${filterDesc}` : ""}) ======\n\n${table}\n\n提示: 运行 hose-use docs show <Path> 可查看对应接口的完整参数和 CURL 示范\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
throw new Error(
|
||||
`未知的 docs 子命令: ${action}。支持: search <关键词>, show <路径|URL>, categories, sync`
|
||||
);
|
||||
}
|
||||
@@ -30,6 +30,7 @@ import { handleKeysCommand } from "./commands/keys.js";
|
||||
import { handleStoreCommand } from "./commands/store.js";
|
||||
import { handleFeeTypeCommand } from "./commands/feetype.js";
|
||||
import { handleAssistPlatformCommand } from "./commands/assist-platform/index.js";
|
||||
import { handleDocsCommand } from "./commands/docs.js";
|
||||
import { COMMAND_METADATA, type CliCommandMetadata } from "./command-metadata.js";
|
||||
import type { CliParsedArgs, CliResult, CliRunOptions, CliRuntime } from "./types.js";
|
||||
|
||||
@@ -206,6 +207,11 @@ export const CLI_COMMAND_REGISTRY: readonly CliCommandDefinition[] = [
|
||||
...COMMAND_METADATA["assist-platform"],
|
||||
handler: (parsed, runtime) => handleAssistPlatformCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "docs",
|
||||
...COMMAND_METADATA.docs,
|
||||
handler: (parsed, runtime) => handleDocsCommand(parsed, runtime),
|
||||
},
|
||||
];
|
||||
|
||||
const COMMAND_LOOKUP = new Map<string, CliCommandDefinition>();
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
本目录按业务域组织代码,每个域独立负责自己的传输层(`api.ts`)、业务编排层(`tools.ts` / `services.ts`)和模型层(`types.ts`)。
|
||||
|
||||
## 当前域(共 14 个)
|
||||
## 当前域(共 15 个)
|
||||
|
||||
| 域 | 内部形态 | 说明 | 详细文档 |
|
||||
|---|---|---|---|
|
||||
@@ -20,10 +20,11 @@
|
||||
| `message/` | `api / tools / types` | 系统通知消息分页查询与已读状态标记 | [README.message.md](./message/README.message.md) |
|
||||
| `task/` | `api / tools / types` | 待办/已办审批任务流分页查询与汇总 | [README.task.md](./task/README.task.md) |
|
||||
| `events/` | `poller / store / types` | 待办与未读消息增量事件轮询及基于 `core/db` (`observed_events`) 的去重存储 | [README.events.md](./events/README.events.md) |
|
||||
| `docs/` | `api / tools / types` | 合思开放平台官方文档中心(270+ API 端点)在线实时拉取、离线缓存与参数规格检索 | [README.docs.md](./docs/README.docs.md) |
|
||||
|
||||
## 分层与形态规则
|
||||
|
||||
1. **标准三件套形态**(`contact`, `dimension`, `feetype`, `menu`, `message`, `permission`, `role`, `store`, `task`):
|
||||
1. **标准三件套形态**(`contact`, `dimension`, `docs`, `feetype`, `menu`, `message`, `permission`, `role`, `store`, `task`):
|
||||
- `api.ts`:只负责 HTTP 请求和响应校验
|
||||
- `tools.ts`:纯函数式业务编排,供 CLI 命令(`src/cli/commands/*`)调用
|
||||
- `types.ts`:Zod schema 与类型定义
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
# Docs 开放平台文档域说明
|
||||
|
||||
本域提供合思/易快报开放平台官方文档中心(`docs.ekuaibao.com`)全量 API 规范、请求方法、URL 路径、参数表格、CURL 示例与响应 JSON 的结构化离线/在线检索与详情提取能力。
|
||||
|
||||
## 架构
|
||||
|
||||
- `api.ts`:传输层,负责实时拉取线上 `https://docs.ekuaibao.com/search-index.json` 并解析出包含 270+ 接口的结构化目录(DocCatalog)。
|
||||
- `tools.ts`:业务层,提供多级缓存(L1 内存 + L2 SQLite + `specs/docs-catalog.json` 静态预编译保底)、关键词评分加权检索、按 URL/Path/标题精确解析文档详情及业务模块分类汇总。
|
||||
- `types.ts`:Zod 模式与 TypeScript 类型定义(`OpenApiDocItem`, `DocCatalog`, `DocSearchQuery`, `DocSearchResult`)。
|
||||
|
||||
## 核心接口
|
||||
|
||||
- `searchDocs(query, options)`: 按关键词、分类(`category`)、HTTP 方法(`method`)与接口路径(`path`)智能打分检索
|
||||
- `getDocDetail(target, options)`: 快速按 ID、Path、URL 或中文标题检索出完整的接口定义
|
||||
- `listCategories(options)`: 汇总开放平台 26+ 个业务分类及对应的文档和端点总数
|
||||
- `syncDocsCatalog(options)`: 强制与线上文档站点执行全量同步并更新本地缓存
|
||||
@@ -0,0 +1,181 @@
|
||||
import ky from "ky";
|
||||
import { EkbApiError } from "../../core/errors.js";
|
||||
import {
|
||||
DocCatalogSchema,
|
||||
type DocCatalog,
|
||||
type OpenApiDocItem,
|
||||
} from "./types.js";
|
||||
|
||||
export const DEFAULT_DOCS_BASE_URL = "https://docs.ekuaibao.com";
|
||||
|
||||
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 targetUrl = `${baseUrl.replace(/\/+$/, "")}/search-index.json`;
|
||||
|
||||
try {
|
||||
const response = await ky.get(targetUrl, {
|
||||
timeout: timeoutMs,
|
||||
headers: {
|
||||
Accept: "application/json",
|
||||
"User-Agent": "hose-use/docs-client",
|
||||
},
|
||||
});
|
||||
|
||||
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(
|
||||
`请求开放平台文档站点 (${targetUrl}) 失败: ${error?.message || String(error)}`,
|
||||
"DOCS_NETWORK_ERROR",
|
||||
502
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
import { describe, expect, it } from "bun:test";
|
||||
import { parseRawSearchIndexToCatalog } from "./api.js";
|
||||
import {
|
||||
getDocDetail,
|
||||
getDocsCatalog,
|
||||
listCategories,
|
||||
searchDocs,
|
||||
} from "./tools.js";
|
||||
|
||||
const mockRawSections = [
|
||||
{
|
||||
documents: [
|
||||
{
|
||||
i: 1001,
|
||||
t: "查询角色组和角色",
|
||||
u: "/docs/open-api/corporation/get-roles-group",
|
||||
b: ["Open API", "企业通讯录"],
|
||||
},
|
||||
{
|
||||
i: 1002,
|
||||
t: "下载附件",
|
||||
u: "/docs/open-api/attachment/attachment-download",
|
||||
b: ["Open API", "附件"],
|
||||
},
|
||||
{
|
||||
i: 1003,
|
||||
t: "其他非 API 页面",
|
||||
u: "/blog/archive",
|
||||
b: [],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
documents: [
|
||||
{
|
||||
i: 2001,
|
||||
t: "Query Parameters",
|
||||
u: "/docs/open-api/corporation/get-roles-group",
|
||||
h: "#query-parameters",
|
||||
p: 1001,
|
||||
},
|
||||
{
|
||||
i: 2002,
|
||||
t: "CURL",
|
||||
u: "/docs/open-api/corporation/get-roles-group",
|
||||
h: "#curl",
|
||||
p: 1001,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
documents: [
|
||||
{
|
||||
i: 3001,
|
||||
t: "GET /api/openapi/v1/roleDefGroups 更新日志 0.7.135 🆕 新增了本接口。",
|
||||
s: "查询角色组和角色",
|
||||
p: 1001,
|
||||
},
|
||||
{
|
||||
i: 3002,
|
||||
t: "accessToken String 认证token 必填 - 通过 获取授权 获取 accessToken",
|
||||
s: "Query Parameters",
|
||||
p: 1001,
|
||||
},
|
||||
{
|
||||
i: 3003,
|
||||
t: "curl --location --request GET 'https://app.ekuaibao.com/api/openapi/v1/roleDefGroups?accessToken=TOKEN'",
|
||||
s: "CURL",
|
||||
p: 1001,
|
||||
},
|
||||
{
|
||||
i: 3004,
|
||||
t: "POST /api/openapi/v2/attachment/downloadurls",
|
||||
s: "下载附件",
|
||||
p: 1002,
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
describe("Docs Domain - 开放平台文档域", () => {
|
||||
it("parseRawSearchIndexToCatalog 正确解析原始搜索索引并提取 HTTP 属性", () => {
|
||||
const catalog = parseRawSearchIndexToCatalog(mockRawSections as any);
|
||||
expect(catalog.totalDocs).toBe(2);
|
||||
expect(catalog.totalEndpoints).toBe(2);
|
||||
|
||||
const roleGroupDoc = catalog.items.find((i) => i.id === 1001);
|
||||
expect(roleGroupDoc).toBeDefined();
|
||||
expect(roleGroupDoc?.title).toBe("查询角色组和角色");
|
||||
expect(roleGroupDoc?.category).toBe("企业通讯录");
|
||||
expect(roleGroupDoc?.method).toBe("GET");
|
||||
expect(roleGroupDoc?.path).toBe("/api/openapi/v1/roleDefGroups");
|
||||
expect(roleGroupDoc?.curl).toContain("/api/openapi/v1/roleDefGroups");
|
||||
expect(roleGroupDoc?.parameters).toContain("accessToken");
|
||||
|
||||
const attachmentDoc = catalog.items.find((i) => i.id === 1002);
|
||||
expect(attachmentDoc?.method).toBe("POST");
|
||||
expect(attachmentDoc?.path).toBe("/api/openapi/v2/attachment/downloadurls");
|
||||
});
|
||||
|
||||
it("getDocsCatalog 在测试环境中能安全加载预编译/内嵌规格", async () => {
|
||||
const catalog = await getDocsCatalog();
|
||||
expect(catalog.items.length).toBeGreaterThan(100);
|
||||
expect(catalog.totalEndpoints).toBeGreaterThan(100);
|
||||
});
|
||||
|
||||
it("searchDocs 按关键词检索接口并正确排序", async () => {
|
||||
const res = await searchDocs({ keyword: "roleDefGroups" });
|
||||
expect(res.total).toBeGreaterThanOrEqual(1);
|
||||
expect(res.items[0]?.path).toBe("/api/openapi/v1/roleDefGroups");
|
||||
expect(res.items[0]?.title).toBe("查询角色组和角色");
|
||||
});
|
||||
|
||||
it("searchDocs 支持按分类与 HTTP 方法精确过滤", async () => {
|
||||
const res = await searchDocs({
|
||||
category: "企业通讯录",
|
||||
method: "GET",
|
||||
});
|
||||
expect(res.items.length).toBeGreaterThanOrEqual(1);
|
||||
for (const item of res.items) {
|
||||
expect(item.category).toBe("企业通讯录");
|
||||
expect(item.method).toBe("GET");
|
||||
}
|
||||
});
|
||||
|
||||
it("getDocDetail 能按路径、URL、标题或 ID 精准定位文档", async () => {
|
||||
const byPath = await getDocDetail("/api/openapi/v1/roleDefGroups");
|
||||
expect(byPath).toBeDefined();
|
||||
expect(byPath?.title).toBe("查询角色组和角色");
|
||||
|
||||
const byUrl = await getDocDetail("/docs/open-api/corporation/get-roles-group");
|
||||
expect(byUrl).toBeDefined();
|
||||
expect(byUrl?.id).toBe(byPath?.id);
|
||||
|
||||
const byTitle = await getDocDetail("查询角色组和角色");
|
||||
expect(byTitle?.path).toBe("/api/openapi/v1/roleDefGroups");
|
||||
});
|
||||
|
||||
it("listCategories 能够统计分类列表与端点总数", async () => {
|
||||
const cats = await listCategories();
|
||||
expect(cats.length).toBeGreaterThanOrEqual(10);
|
||||
const corpCat = cats.find((c) => c.name === "企业通讯录");
|
||||
expect(corpCat).toBeDefined();
|
||||
expect(corpCat?.count).toBeGreaterThan(0);
|
||||
expect(corpCat?.endpointsCount).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,250 @@
|
||||
import embeddedCatalog from "../../../specs/docs-catalog.json" with { type: "json" };
|
||||
import { getGlobalCache } from "../../core/cache/index.js";
|
||||
import { fetchLiveDocsCatalog } from "./api.js";
|
||||
import type {
|
||||
DocCatalog,
|
||||
DocCategoryInfo,
|
||||
DocSearchQuery,
|
||||
DocSearchResult,
|
||||
OpenApiDocItem,
|
||||
} from "./types.js";
|
||||
|
||||
const CACHE_KEY = "docs:catalog:v1";
|
||||
const CACHE_TTL_MS = 24 * 60 * 60 * 1000; // 24小时缓存
|
||||
|
||||
/**
|
||||
* 获取接口文档目录(具备实时拉取 + L1/L2 缓存 + 静态内嵌保底能力)
|
||||
*/
|
||||
export async function getDocsCatalog(options?: {
|
||||
forceRefresh?: boolean;
|
||||
baseUrl?: string;
|
||||
}): Promise<DocCatalog> {
|
||||
const cache = getGlobalCache();
|
||||
|
||||
if (!options?.forceRefresh) {
|
||||
const cached = cache.get<DocCatalog>(CACHE_KEY, "docs");
|
||||
if (cached && Array.isArray(cached.items) && cached.items.length > 0) {
|
||||
return cached;
|
||||
}
|
||||
}
|
||||
|
||||
// 尝试从线上获取最新规范
|
||||
try {
|
||||
const liveCatalog = await fetchLiveDocsCatalog({ baseUrl: options?.baseUrl });
|
||||
cache.set(CACHE_KEY, liveCatalog, {
|
||||
ttlMs: CACHE_TTL_MS,
|
||||
namespace: "docs",
|
||||
});
|
||||
return liveCatalog;
|
||||
} catch (error) {
|
||||
// 若强制刷新失败且存在历史缓存,则返回历史缓存
|
||||
const cached = cache.get<DocCatalog>(CACHE_KEY, "docs");
|
||||
if (cached && Array.isArray(cached.items) && cached.items.length > 0) {
|
||||
return cached;
|
||||
}
|
||||
|
||||
// 线上无法连通且无历史缓存时,安全降级至本地内嵌预编译规格
|
||||
return embeddedCatalog as unknown as DocCatalog;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算文档项与搜索关键词的相关度得分
|
||||
*/
|
||||
function scoreDocItem(item: OpenApiDocItem, queryLower: string): number {
|
||||
let score = 0;
|
||||
const pathLower = (item.path || "").toLowerCase();
|
||||
const titleLower = item.title.toLowerCase();
|
||||
const categoryLower = item.category.toLowerCase();
|
||||
const urlLower = item.url.toLowerCase();
|
||||
|
||||
// 路径完全匹配
|
||||
if (pathLower === queryLower) score += 100;
|
||||
else if (pathLower.includes(queryLower)) score += 60;
|
||||
|
||||
// 标题完全匹配或包含
|
||||
if (titleLower === queryLower) score += 80;
|
||||
else if (titleLower.includes(queryLower)) score += 40;
|
||||
|
||||
// 分类完全匹配或包含
|
||||
if (categoryLower === queryLower) score += 50;
|
||||
else if (categoryLower.includes(queryLower)) score += 20;
|
||||
|
||||
// URL 路径包含
|
||||
if (urlLower.includes(queryLower)) score += 30;
|
||||
|
||||
// CURL 或参数定义中出现
|
||||
if (item.curl && item.curl.toLowerCase().includes(queryLower)) score += 25;
|
||||
if (item.parameters && item.parameters.toLowerCase().includes(queryLower)) score += 20;
|
||||
|
||||
// 正文段落包含
|
||||
for (const s of item.sections) {
|
||||
if (s.content.toLowerCase().includes(queryLower)) {
|
||||
score += 10;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return score;
|
||||
}
|
||||
|
||||
/**
|
||||
* 搜索开放平台接口与指南文档
|
||||
*/
|
||||
export async function searchDocs(
|
||||
query: DocSearchQuery = {},
|
||||
options?: { forceRefresh?: boolean; baseUrl?: string }
|
||||
): Promise<DocSearchResult> {
|
||||
const catalog = await getDocsCatalog(options);
|
||||
let items = catalog.items;
|
||||
|
||||
// 1. 分类过滤
|
||||
if (query.category) {
|
||||
const catLower = query.category.trim().toLowerCase();
|
||||
items = items.filter((item) =>
|
||||
item.category.toLowerCase().includes(catLower)
|
||||
);
|
||||
}
|
||||
|
||||
// 2. HTTP 方法过滤
|
||||
if (query.method) {
|
||||
const methodUpper = query.method.trim().toUpperCase();
|
||||
items = items.filter((item) => item.method === methodUpper);
|
||||
}
|
||||
|
||||
// 3. 接口路径匹配过滤
|
||||
if (query.path) {
|
||||
const pathLower = query.path.trim().toLowerCase();
|
||||
items = items.filter((item) =>
|
||||
(item.path || "").toLowerCase().includes(pathLower)
|
||||
);
|
||||
}
|
||||
|
||||
// 4. 关键词打分与排序
|
||||
const rawKeyword = query.keyword?.trim();
|
||||
if (rawKeyword) {
|
||||
const keywordLower = rawKeyword.toLowerCase();
|
||||
const scored = items
|
||||
.map((item) => ({ item, score: scoreDocItem(item, keywordLower) }))
|
||||
.filter((entry) => entry.score > 0)
|
||||
.sort((a, b) => b.score - a.score);
|
||||
|
||||
items = scored.map((entry) => entry.item);
|
||||
}
|
||||
|
||||
const total = items.length;
|
||||
const limit = Math.max(1, Math.min(query.limit ?? 20, 100));
|
||||
const pagedItems = items.slice(0, limit);
|
||||
|
||||
return {
|
||||
total,
|
||||
keyword: rawKeyword,
|
||||
category: query.category,
|
||||
method: query.method,
|
||||
items: pagedItems,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 按 ID、Path、URL 或文档标题精确解析单篇文档详情
|
||||
*/
|
||||
export async function getDocDetail(
|
||||
target: string,
|
||||
options?: { forceRefresh?: boolean; baseUrl?: string }
|
||||
): Promise<OpenApiDocItem | undefined> {
|
||||
const catalog = await getDocsCatalog(options);
|
||||
const cleanTarget = target.trim();
|
||||
if (!cleanTarget) return undefined;
|
||||
|
||||
const targetLower = cleanTarget.toLowerCase();
|
||||
|
||||
// 1. 按数字 ID 精确查找
|
||||
const idNum = Number(cleanTarget);
|
||||
if (!Number.isNaN(idNum)) {
|
||||
const byId = catalog.items.find((item) => item.id === idNum);
|
||||
if (byId) return byId;
|
||||
}
|
||||
|
||||
// 2. 按接口 Path 精确查找 (如 /api/openapi/v1/roleDefGroups)
|
||||
const byExactPath = catalog.items.find(
|
||||
(item) => (item.path || "").toLowerCase() === targetLower
|
||||
);
|
||||
if (byExactPath) return byExactPath;
|
||||
|
||||
// 3. 按文档 URL 精确查找 (如 /docs/open-api/corporation/get-roles-group)
|
||||
const byExactUrl = catalog.items.find(
|
||||
(item) => item.url.toLowerCase() === targetLower
|
||||
);
|
||||
if (byExactUrl) return byExactUrl;
|
||||
|
||||
// 4. 按标题精确查找
|
||||
const byExactTitle = catalog.items.find(
|
||||
(item) => item.title.toLowerCase() === targetLower
|
||||
);
|
||||
if (byExactTitle) return byExactTitle;
|
||||
|
||||
// 5. 模糊前缀/子串匹配(取最相似的第一个)
|
||||
return (
|
||||
catalog.items.find((item) => (item.path || "").toLowerCase().includes(targetLower)) ||
|
||||
catalog.items.find((item) => item.url.toLowerCase().includes(targetLower)) ||
|
||||
catalog.items.find((item) => item.title.toLowerCase().includes(targetLower))
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取开放平台所有业务模块分类与文档数量汇总
|
||||
*/
|
||||
export async function listCategories(options?: {
|
||||
forceRefresh?: boolean;
|
||||
baseUrl?: string;
|
||||
}): Promise<DocCategoryInfo[]> {
|
||||
const catalog = await getDocsCatalog(options);
|
||||
const map = new Map<string, { count: number; endpointsCount: number }>();
|
||||
|
||||
for (const item of catalog.items) {
|
||||
const cat = item.category || "未分类";
|
||||
const current = map.get(cat) || { count: 0, endpointsCount: 0 };
|
||||
current.count += 1;
|
||||
if (item.method && item.path) {
|
||||
current.endpointsCount += 1;
|
||||
}
|
||||
map.set(cat, current);
|
||||
}
|
||||
|
||||
const result: DocCategoryInfo[] = [];
|
||||
for (const [name, stats] of map.entries()) {
|
||||
result.push({
|
||||
name,
|
||||
count: stats.count,
|
||||
endpointsCount: stats.endpointsCount,
|
||||
});
|
||||
}
|
||||
|
||||
return result.sort((a, b) => b.count - a.count);
|
||||
}
|
||||
|
||||
/**
|
||||
* 手动强制同步线上文档中心索引并重载本地持久化缓存
|
||||
*/
|
||||
export async function syncDocsCatalog(options?: {
|
||||
baseUrl?: string;
|
||||
}): Promise<{
|
||||
success: boolean;
|
||||
totalDocs: number;
|
||||
totalEndpoints: number;
|
||||
source: string;
|
||||
updatedAt: string;
|
||||
}> {
|
||||
const catalog = await getDocsCatalog({
|
||||
forceRefresh: true,
|
||||
baseUrl: options?.baseUrl,
|
||||
});
|
||||
|
||||
return {
|
||||
success: true,
|
||||
totalDocs: catalog.totalDocs,
|
||||
totalEndpoints: catalog.totalEndpoints,
|
||||
source: catalog.sourceUrl,
|
||||
updatedAt: catalog.updatedAt,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export const DocSectionSchema = z.object({
|
||||
title: z.string().default("概述"),
|
||||
content: z.string().default(""),
|
||||
});
|
||||
|
||||
export const OpenApiDocItemSchema = z.object({
|
||||
id: z.number(),
|
||||
title: z.string().default(""),
|
||||
category: z.string().default("未分类"),
|
||||
url: z.string().default(""),
|
||||
permalink: z.string().default(""),
|
||||
method: z.string().optional(),
|
||||
path: z.string().optional(),
|
||||
breadcrumbs: z.array(z.string()).default([]),
|
||||
headings: z.array(z.string()).default([]),
|
||||
sections: z.array(DocSectionSchema).default([]),
|
||||
parameters: z.string().optional(),
|
||||
curl: z.string().optional(),
|
||||
responseSample: z.string().optional(),
|
||||
});
|
||||
|
||||
export const DocCatalogSchema = z.object({
|
||||
version: z.string().default("1.0.0"),
|
||||
updatedAt: z.string(),
|
||||
sourceUrl: z.string().default("https://docs.ekuaibao.com/search-index.json"),
|
||||
totalDocs: z.number(),
|
||||
totalEndpoints: z.number(),
|
||||
items: z.array(OpenApiDocItemSchema),
|
||||
});
|
||||
|
||||
export type DocSection = z.infer<typeof DocSectionSchema>;
|
||||
export type OpenApiDocItem = z.infer<typeof OpenApiDocItemSchema>;
|
||||
export type DocCatalog = z.infer<typeof DocCatalogSchema>;
|
||||
|
||||
export interface DocSearchQuery {
|
||||
keyword?: string;
|
||||
category?: string;
|
||||
method?: string;
|
||||
path?: string;
|
||||
limit?: number;
|
||||
}
|
||||
|
||||
export interface DocSearchResult {
|
||||
total: number;
|
||||
keyword?: string;
|
||||
category?: string;
|
||||
method?: string;
|
||||
items: OpenApiDocItem[];
|
||||
}
|
||||
|
||||
export interface DocCategoryInfo {
|
||||
name: string;
|
||||
count: number;
|
||||
endpointsCount: number;
|
||||
}
|
||||
Reference in new issue
Block a user