Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
62b47f5ad7 | ||
|
|
83dacf90c4 | ||
|
|
1c5d6153a2 | ||
|
|
6ba748e531 | ||
|
|
9cf247fe45 | ||
|
|
4f572ad9c1 | ||
|
|
448dd438ff | ||
|
|
cfd0c48a8b | ||
|
|
b7fda124fd | ||
|
|
e00adbe5a8 |
No files matched your search
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "hose-use",
|
||||
"version": "0.9.6",
|
||||
"version": "0.9.7",
|
||||
"description": "合思/易快报 (ekuaibao) 企业级 SaaS CLI 与底层 SDK:多账号登录、企业租户切换、单据明细检索、工作流管理、内置 HTTP 服务与常驻守护进程。",
|
||||
"author": {
|
||||
"name": "yingqing"
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
# hose-use (v0.9.6)
|
||||
# hose-use (v0.9.7)
|
||||
|
||||
合思/易快报(ekuaibao)企业级 CLI 命令行工具与底层 SDK。
|
||||
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "hose-use",
|
||||
"version": "0.9.6",
|
||||
"version": "0.9.7",
|
||||
"module": "src/server.ts",
|
||||
"type": "module",
|
||||
"exports": {
|
||||
|
||||
@@ -2,11 +2,11 @@
|
||||
name: hose-aipro
|
||||
description: "合思 AI PRO(EASO AI PRO)确定性审批仲裁网关 CLI 与技能套件:单据挂载绑定、事实证据核验与打标 (PASS/FAIL/SKIP)、审核要点/规则场景库检索、确定性审批仲裁(同意/驳回/转人工硬阻断)、审计轨迹日志查询与常驻服务管理。用于一切合思 AI PRO 确定性审批仲裁与要点核验请求。"
|
||||
metadata:
|
||||
version: 0.9.6
|
||||
version: 0.9.7
|
||||
short-description: 合思 AI PRO 确定性审批仲裁网关与审核要点核验 skill
|
||||
---
|
||||
|
||||
# hose-aipro (v0.9.6)
|
||||
# hose-aipro (v0.9.7)
|
||||
|
||||
合思 AI PRO 确定性审批仲裁网关是专门面向企业财务核算、单据审核与自动化合规风控的确定性仲裁命令行与 SDK。
|
||||
|
||||
|
||||
@@ -2,11 +2,11 @@
|
||||
name: hose-use
|
||||
description: "合思/易快报(Ekuaibao)企业级 SaaS 一站式能力:hose-use CLI/SDK 多账号登录、租户切换、单据检索与审批动作、自建应用与工作流扫描、密钥与应用中心、常驻守护进程与 HTTP 文档/OpenAPI,以及工作流 MVEL 代码节点脚本生成调试、节点批量开通。用于一切合思/易快报相关请求。"
|
||||
metadata:
|
||||
version: 0.9.6
|
||||
version: 0.9.7
|
||||
short-description: 合思/易快报 企业级 CLI 与工作流 skill 套件(含 MVEL 代码节点)
|
||||
---
|
||||
|
||||
# hose-use (v0.9.6)
|
||||
# hose-use (v0.9.7)
|
||||
|
||||
在具备 MCP 的 AI 智能体环境中,**优先使用 `hose_cli` 单工具网关**,传入 `command: string` 执行;在终端或自动化脚本中,直接调用全局 `hose` 或 `hose-use` 命令行。
|
||||
本 Skill 是智能体的路由分发层:保持主文档简明,遇到复杂业务时深入查阅对应的专属参考文档(`references/*.md`)。
|
||||
|
||||
@@ -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
|
||||
@@ -1,7 +1,7 @@
|
||||
openapi: 3.1.0
|
||||
info:
|
||||
title: hose-use API & MCP Tools Specification
|
||||
version: 0.9.6
|
||||
version: 0.9.7
|
||||
description: >-
|
||||
Unified Enterprise SaaS API, CLI, and MCP Specification for Ekuaibao (合思/易快报), EASO, and Piper Workflows.
|
||||
servers:
|
||||
|
||||
+1
-1
@@ -2,7 +2,7 @@
|
||||
"openapi": "3.1.0",
|
||||
"info": {
|
||||
"title": "hose-use API & MCP Tools Specification",
|
||||
"version": "0.9.6",
|
||||
"version": "0.9.7",
|
||||
"description": "Unified Enterprise SaaS API, CLI, and MCP Specification for Ekuaibao (合思/易快报), EASO, and Piper Workflows."
|
||||
},
|
||||
"servers": [
|
||||
|
||||
@@ -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,249 @@
|
||||
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,
|
||||
matchReason: item.matchReason || undefined,
|
||||
}));
|
||||
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 hasKeyword = Boolean(keyword);
|
||||
const headers = hasKeyword
|
||||
? ["Method", "Path / URL", "标题", "分类", "匹配依据"]
|
||||
: ["Method", "Path / URL", "标题", "分类"];
|
||||
|
||||
const rows = searchRes.items.map((item) => {
|
||||
const base = [
|
||||
item.method || "DOC",
|
||||
item.path || item.url,
|
||||
item.title,
|
||||
item.category,
|
||||
];
|
||||
if (hasKeyword) {
|
||||
base.push(item.matchReason || "-");
|
||||
}
|
||||
return base;
|
||||
});
|
||||
|
||||
const table = printTable(headers, 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`
|
||||
);
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { readFileSync, writeFileSync } from "node:fs";
|
||||
import { EkbError } from "../../../core/errors.js";
|
||||
import { getWorkflowDetail, listAllWorkflows, refreshWorkflowChooses, updateWorkflow } from "../../../domains/platform/workflow/services.js";
|
||||
import { getWorkflowDetail, listAllWorkflows, refreshWorkflowChooses, updateWorkflow, lintWorkflowScripts } from "../../../domains/platform/workflow/services.js";
|
||||
import { WorkflowSavePartialError } from "../../../domains/platform/workflow/management/save-error.js";
|
||||
import { WorkflowDetailSchema } from "../../../domains/platform/workflow/types.js";
|
||||
import {
|
||||
@@ -99,6 +99,22 @@ export async function handleSave(parsed: CliParsedArgs, runtime: CliRuntime): Pr
|
||||
|
||||
const forceWrite = booleanOption(parsed.options, ["force-write", "forceWrite"]);
|
||||
const syncFile = booleanOption(parsed.options, ["in-place", "inPlace"]);
|
||||
|
||||
// 保存前静态代码健康度检查
|
||||
const scriptLintReport = lintWorkflowScripts(parsedWorkflow as any);
|
||||
const scriptWarnings: string[] = [];
|
||||
if (scriptLintReport.totalCodeNodes > 0) {
|
||||
for (const node of scriptLintReport.reports) {
|
||||
if (node.issues.length > 0) {
|
||||
for (const iss of node.issues) {
|
||||
const icon = iss.level === "error" ? "❌" : "⚠️";
|
||||
const loc = iss.line ? `(L${iss.line})` : "";
|
||||
scriptWarnings.push(`${icon} 节点 [${node.nodeName}] ${loc}: [${iss.rule}] ${iss.message}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
requireMutationConfirmation(
|
||||
parsed,
|
||||
runtime,
|
||||
@@ -112,6 +128,7 @@ export async function handleSave(parsed: CliParsedArgs, runtime: CliRuntime): Pr
|
||||
tasksVersion: parsedWorkflow.tasksVersion,
|
||||
forceWrite,
|
||||
syncFile,
|
||||
...(scriptWarnings.length > 0 ? { scriptWarnings } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -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,155 @@
|
||||
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("查询角色组和角色");
|
||||
expect(res.items[0]?.matchReason).toBeDefined();
|
||||
});
|
||||
|
||||
it("searchDocs 支持多词分词与跨正文/参数模糊检索", async () => {
|
||||
const res = await searchDocs({ keyword: "员工 手机" });
|
||||
expect(res.total).toBeGreaterThanOrEqual(1);
|
||||
expect(res.items.some((i) => i.title.includes("员工"))).toBe(true);
|
||||
expect(res.items[0]?.matchReason).toBeDefined();
|
||||
});
|
||||
|
||||
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,352 @@
|
||||
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 evaluateDocMatch(
|
||||
item: OpenApiDocItem,
|
||||
rawKeyword: string
|
||||
): { item: OpenApiDocItem; score: number } | null {
|
||||
const queryLower = rawKeyword.trim().toLowerCase();
|
||||
if (!queryLower) return null;
|
||||
|
||||
const tokens = queryLower.split(/[\s,+/]+/).filter(Boolean);
|
||||
if (tokens.length === 0) return null;
|
||||
|
||||
let score = 0;
|
||||
const matchReasons: string[] = [];
|
||||
|
||||
const pathLower = (item.path || "").toLowerCase();
|
||||
const titleLower = item.title.toLowerCase();
|
||||
const categoryLower = item.category.toLowerCase();
|
||||
const paramLower = (item.parameters || "").toLowerCase();
|
||||
const curlLower = (item.curl || "").toLowerCase();
|
||||
const respLower = (item.responseSample || "").toLowerCase();
|
||||
const allSectionsText = item.sections.map((s) => s.content).join(" ");
|
||||
const sectionsLower = allSectionsText.toLowerCase();
|
||||
|
||||
// 1. 完整短语匹配加分 (Phrase match)
|
||||
if (queryLower.length > 1) {
|
||||
if (pathLower === queryLower) {
|
||||
score += 120;
|
||||
matchReasons.push("路径完全匹配");
|
||||
} else if (pathLower.includes(queryLower)) {
|
||||
score += 80;
|
||||
matchReasons.push(`路径包含 "${queryLower}"`);
|
||||
}
|
||||
|
||||
if (titleLower === queryLower) {
|
||||
score += 100;
|
||||
matchReasons.push("标题完全匹配");
|
||||
} else if (titleLower.includes(queryLower)) {
|
||||
score += 60;
|
||||
matchReasons.push(`标题包含 "${queryLower}"`);
|
||||
}
|
||||
|
||||
if (categoryLower.includes(queryLower)) {
|
||||
score += 40;
|
||||
matchReasons.push(`模块: ${item.category}`);
|
||||
}
|
||||
|
||||
if (paramLower.includes(queryLower)) {
|
||||
score += 45;
|
||||
const idx = paramLower.indexOf(queryLower);
|
||||
const snippet = (item.parameters || "")
|
||||
.substring(Math.max(0, idx - 12), Math.min(item.parameters?.length || 0, idx + 30))
|
||||
.replace(/\s+/g, " ");
|
||||
matchReasons.push(`参数规格: ...${snippet}...`);
|
||||
}
|
||||
|
||||
if (sectionsLower.includes(queryLower)) {
|
||||
score += 35;
|
||||
const idx = sectionsLower.indexOf(queryLower);
|
||||
const snippet = allSectionsText
|
||||
.substring(Math.max(0, idx - 12), Math.min(allSectionsText.length, idx + 30))
|
||||
.replace(/\s+/g, " ");
|
||||
matchReasons.push(`正文段落: ...${snippet}...`);
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Token 分词逐项匹配 (Multi-token match)
|
||||
let tokensMatched = 0;
|
||||
for (const token of tokens) {
|
||||
let tokenMatched = false;
|
||||
|
||||
if (pathLower.includes(token)) {
|
||||
score += 30;
|
||||
tokenMatched = true;
|
||||
if (!matchReasons.some((r) => r.includes(token))) {
|
||||
matchReasons.push(`路径含 "${token}"`);
|
||||
}
|
||||
}
|
||||
if (titleLower.includes(token)) {
|
||||
score += 25;
|
||||
tokenMatched = true;
|
||||
if (!matchReasons.some((r) => r.includes(token))) {
|
||||
matchReasons.push(`标题含 "${token}"`);
|
||||
}
|
||||
}
|
||||
if (categoryLower.includes(token)) {
|
||||
score += 20;
|
||||
tokenMatched = true;
|
||||
if (!matchReasons.some((r) => r.includes(token))) {
|
||||
matchReasons.push(`分类含 "${token}"`);
|
||||
}
|
||||
}
|
||||
if (paramLower.includes(token)) {
|
||||
score += 20;
|
||||
tokenMatched = true;
|
||||
if (!matchReasons.some((r) => r.includes(token))) {
|
||||
const idx = paramLower.indexOf(token);
|
||||
const snippet = (item.parameters || "")
|
||||
.substring(Math.max(0, idx - 10), Math.min(item.parameters?.length || 0, idx + 25))
|
||||
.replace(/\s+/g, " ");
|
||||
matchReasons.push(`参数: ...${snippet}...`);
|
||||
}
|
||||
}
|
||||
if (sectionsLower.includes(token)) {
|
||||
score += 15;
|
||||
tokenMatched = true;
|
||||
if (!matchReasons.some((r) => r.includes(token))) {
|
||||
const idx = sectionsLower.indexOf(token);
|
||||
const snippet = allSectionsText
|
||||
.substring(Math.max(0, idx - 10), Math.min(allSectionsText.length, idx + 25))
|
||||
.replace(/\s+/g, " ");
|
||||
matchReasons.push(`正文: ...${snippet}...`);
|
||||
}
|
||||
}
|
||||
if (curlLower.includes(token) || respLower.includes(token)) {
|
||||
score += 15;
|
||||
tokenMatched = true;
|
||||
if (!matchReasons.some((r) => r.includes(token))) {
|
||||
matchReasons.push(`请求/响应含 "${token}"`);
|
||||
}
|
||||
}
|
||||
|
||||
if (tokenMatched) tokensMatched++;
|
||||
}
|
||||
|
||||
// 多词全部命中奖励 (All-tokens match bonus)
|
||||
if (tokens.length > 1 && tokensMatched === tokens.length) {
|
||||
score += 50;
|
||||
}
|
||||
|
||||
if (score <= 0 || tokensMatched === 0) return null;
|
||||
|
||||
const matchReason = matchReasons.slice(0, 2).join(" | ");
|
||||
return {
|
||||
item: {
|
||||
...item,
|
||||
matchReason,
|
||||
},
|
||||
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 scored = items
|
||||
.map((item) => evaluateDocMatch(item, rawKeyword))
|
||||
.filter((entry): entry is { item: OpenApiDocItem; score: number } => entry !== null)
|
||||
.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,58 @@
|
||||
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(),
|
||||
matchReason: 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;
|
||||
}
|
||||
@@ -350,3 +350,16 @@ hose-use --corp=<企业ID> workflow get <pipelineId> --json \
|
||||
已有流程若 `$snapshot` 为空(例如由 CLI 复制/创建产生),需要用全量保存补齐快照条目:读取 `workflow get --json`、在 `$snapshot` 中按 `<taskPath>.url-snapshot` 追加富文本模型,再 `workflow save --file=<json> --yes`。
|
||||
|
||||
富文本模型形如:`root → paragraph → [text, context-tag(choose), text]`,三段的拼接结果必须等同于 `url` 字段。
|
||||
|
||||
## 上游官方规范与参考依据 (Upstream References)
|
||||
|
||||
本域在解析底层数据格式、变量选择树与灰度节点规范时,参考了合思/易快报官方公开的开源仓库定义:
|
||||
|
||||
1. **HoseCloud Hab 任务插件框架**:[`ekuaibao/Hab-Plugin`](https://github.com/ekuaibao/Hab-Plugin)
|
||||
- **底层数据类型**:定义了 39 类官方底层字段数据类型(`com.hosecloud.hab.plugin.DataType`,如 `TEXT`, `MONEY`, `FLOW_FORM`, `DATA_LINK`, `REQUISITION_ITEMS` 等)与 8 种选择项类型(`Choose.ItemType`),收录于 `catalog/enums.ts`(`WORKFLOW_DATA_TYPES` 与 `WORKFLOW_CHOOSE_ITEM_TYPES`);
|
||||
- **动态任务节点机制**:阐明了合思工作流中 `task-dynamic-*`(如官方延迟等待节点 `task-dynamic-delay`)的 PF4J 插件化容器与执行生命周期;
|
||||
- **架构边界说明**:`hose-use` 仅作为合思平台工作流的客户端 CLI、SDK 编排与诊断工具,**不开发或篡改其服务端底层运行时,亦不违规在客户端捏造服务端未支持的自造节点类型**。所有节点类型必须严格对齐服务端或官方灰度清单(`GRAY_NODES_CATALOG`)。
|
||||
|
||||
2. **开放平台接口文档中心**:[`ekuaibao/open-platform-docs`](https://github.com/ekuaibao/open-platform-docs)
|
||||
- 包含开放平台 23 大类、249 篇接口规范,作为工作流 HTTP 节点 (`http`) 与 OpenAPI 任务节点 (`task-openapi`) 的调用路径、参数规格与应用权限映射基准。
|
||||
|
||||
@@ -5,6 +5,10 @@ import {
|
||||
isWorkflowActionCode,
|
||||
matchWorkflowAction,
|
||||
resolveWorkflowEnumOptions,
|
||||
WORKFLOW_DATA_TYPES,
|
||||
WORKFLOW_CHOOSE_ITEM_TYPES,
|
||||
isWorkflowDataType,
|
||||
isWorkflowChooseItemType,
|
||||
} from "../services.js";
|
||||
import { analyzeWorkflow } from "../analysis/index.js";
|
||||
|
||||
@@ -182,4 +186,25 @@ describe("Workflow Action Enums & Diagnostics", () => {
|
||||
expect(codes).not.toContain("DEADLOCK_CONDITION_STATE_FILTER");
|
||||
expect(codes).not.toContain("INVALID_ACTION_ENUM_TEXT_VALUE");
|
||||
});
|
||||
|
||||
it("verifies official workflow DataType definitions from Hab-Plugin", () => {
|
||||
// 官方参考: https://github.com/ekuaibao/Hab-Plugin (com.hosecloud.hab.plugin.DataType)
|
||||
expect(WORKFLOW_DATA_TYPES).toHaveLength(39);
|
||||
expect(isWorkflowDataType("TEXT")).toBe(true);
|
||||
expect(isWorkflowDataType("MONEY")).toBe(true);
|
||||
expect(isWorkflowDataType("FLOW_FORM")).toBe(true);
|
||||
expect(isWorkflowDataType("DATA_LINK")).toBe(true);
|
||||
expect(isWorkflowDataType("REQUISITION_ITEMS")).toBe(true);
|
||||
expect(isWorkflowDataType("NOT_A_REAL_TYPE")).toBe(false);
|
||||
});
|
||||
|
||||
it("verifies official workflow Choose ItemType definitions from Hab-Plugin", () => {
|
||||
// 官方参考: https://github.com/ekuaibao/Hab-Plugin (com.hosecloud.hab.plugin.Choose.ItemType)
|
||||
expect(WORKFLOW_CHOOSE_ITEM_TYPES).toHaveLength(8);
|
||||
expect(isWorkflowChooseItemType("TEXT")).toBe(true);
|
||||
expect(isWorkflowChooseItemType("NUMBER")).toBe(true);
|
||||
expect(isWorkflowChooseItemType("MONEY")).toBe(true);
|
||||
expect(isWorkflowChooseItemType("BOOLEAN")).toBe(true);
|
||||
expect(isWorkflowChooseItemType("UNKNOWN")).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -57,3 +57,86 @@ export function matchWorkflowAction(query: string): WorkflowActionEnumItem | und
|
||||
(item) => item.code.toLowerCase() === trimmed.toLowerCase() || item.label === trimmed || item.name === trimmed
|
||||
);
|
||||
}
|
||||
|
||||
// ── 工作流底层官方字段类型与 Choose 类型枚举 ────────────────────────────────────
|
||||
// 来源于 HoseCloud Hab 官方插件框架底层定义 (https://github.com/ekuaibao/Hab-Plugin)
|
||||
// 参考规范:com.hosecloud.hab.plugin.DataType 与 com.hosecloud.hab.plugin.Choose.ItemType
|
||||
// 说明:仅作为客户端变量解析、字段类型断言与 Schema 校验依据,不侵入平台服务端内部插件实现。
|
||||
|
||||
/**
|
||||
* 合思/易快报工作流官方字段底层数据类型枚举(共 39 类)
|
||||
* 对应 HoseCloud Hab 插件框架 com.hosecloud.hab.plugin.DataType (https://github.com/ekuaibao/Hab-Plugin)
|
||||
*/
|
||||
export const WORKFLOW_DATA_TYPES = [
|
||||
"TEXT",
|
||||
"AUTO_NUMBER",
|
||||
"NUMBER",
|
||||
"MONEY",
|
||||
"BOOLEAN",
|
||||
"SWITCH",
|
||||
"DATE",
|
||||
"DATE_RANGE",
|
||||
"DEPARTMENT",
|
||||
"FEISHU_DEPARTMENT",
|
||||
"STAFF",
|
||||
"STAFF_LIST",
|
||||
"DATA_LINK",
|
||||
"DATA_LINK_LIST",
|
||||
"PAYEE_INFO",
|
||||
"DIMENSION",
|
||||
"DIMENSION_LIST",
|
||||
"ENUM",
|
||||
"LIST",
|
||||
"MAP",
|
||||
"FLOW_TEMPLATE",
|
||||
"CITY",
|
||||
"_SELECT_INVOICE_TYPE_",
|
||||
"ATTACHMENT",
|
||||
"REQUISITION_ITEMS",
|
||||
"FEE_DETAIL",
|
||||
"FEE_DETAIL_ITEM",
|
||||
"FLOW_FORM",
|
||||
"FLOW_FORM_ITEM",
|
||||
"RECORD_LINK",
|
||||
"RECORD_LINK_LIST",
|
||||
"VISIBILITY",
|
||||
"ROLE",
|
||||
"ZS_TYPE",
|
||||
"ZS_LIST",
|
||||
"SELECT_INVOICE_CORPORATION",
|
||||
"FREQUENCY",
|
||||
"DATALINK_FILTERS",
|
||||
"UNDEFINED",
|
||||
] as const;
|
||||
|
||||
export type WorkflowDataType = (typeof WORKFLOW_DATA_TYPES)[number];
|
||||
|
||||
const WORKFLOW_DATA_TYPES_SET = new Set<string>(WORKFLOW_DATA_TYPES);
|
||||
|
||||
export function isWorkflowDataType(type: string): type is WorkflowDataType {
|
||||
return WORKFLOW_DATA_TYPES_SET.has(type);
|
||||
}
|
||||
|
||||
/**
|
||||
* 合思/易快报工作流 Choose 选择项官方基础类型
|
||||
* 对应 HoseCloud Hab 插件框架 com.hosecloud.hab.plugin.Choose.ItemType
|
||||
*/
|
||||
export const WORKFLOW_CHOOSE_ITEM_TYPES = [
|
||||
"TEXT",
|
||||
"NUMBER",
|
||||
"BOOLEAN",
|
||||
"DATE",
|
||||
"DATA_RANGE",
|
||||
"LIST",
|
||||
"MAP",
|
||||
"MONEY",
|
||||
] as const;
|
||||
|
||||
export type WorkflowChooseItemType = (typeof WORKFLOW_CHOOSE_ITEM_TYPES)[number];
|
||||
|
||||
const WORKFLOW_CHOOSE_ITEM_TYPES_SET = new Set<string>(WORKFLOW_CHOOSE_ITEM_TYPES);
|
||||
|
||||
export function isWorkflowChooseItemType(type: string): type is WorkflowChooseItemType {
|
||||
return WORKFLOW_CHOOSE_ITEM_TYPES_SET.has(type);
|
||||
}
|
||||
|
||||
@@ -89,6 +89,59 @@ describe("workflow-script - 本地静态语法校验与沙箱仿真引擎", () =
|
||||
expect(res.issues).toHaveLength(0);
|
||||
expect(res.referencedNodes[0].exists).toBe(true);
|
||||
});
|
||||
|
||||
it("flags unscoped block assignment in MVEL conditional branches", () => {
|
||||
const badCode = `
|
||||
var upstream = action_calc;
|
||||
while (upstream != null) {
|
||||
if (upstream > 0) {
|
||||
pEnd = 100;
|
||||
} else {
|
||||
pEnd = 200;
|
||||
}
|
||||
}
|
||||
return pEnd;
|
||||
`;
|
||||
const existing = new Set(["action_calc"]);
|
||||
const res = lintMvelCode(badCode, existing);
|
||||
const branchIssue = res.issues.find((i) => i.rule === "mvel-unscoped-block-assignment");
|
||||
expect(branchIssue).toBeDefined();
|
||||
expect(branchIssue?.message).toContain("pEnd");
|
||||
expect(branchIssue?.level).toBe("warning");
|
||||
});
|
||||
|
||||
it("passes MVEL code when branch variable is initialized at outer scope or uses ternary", () => {
|
||||
const safeCode = `
|
||||
var upstream = action_calc;
|
||||
pEnd = 0;
|
||||
while (upstream != null) {
|
||||
if (upstream > 0) {
|
||||
pEnd = 100;
|
||||
}
|
||||
}
|
||||
return pEnd;
|
||||
`;
|
||||
const existing = new Set(["action_calc"]);
|
||||
const res = lintMvelCode(safeCode, existing);
|
||||
expect(res.issues.some((i) => i.rule === "mvel-unscoped-block-assignment")).toBe(false);
|
||||
});
|
||||
|
||||
it("detects unsupported break keyword in MVEL code", () => {
|
||||
const codeWithBreak = `
|
||||
var upstream = action_calc;
|
||||
while (upstream != null) {
|
||||
if (upstream > 10) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return upstream;
|
||||
`;
|
||||
const res = lintMvelCode(codeWithBreak, new Set(["action_calc"]));
|
||||
const breakIssue = res.issues.find((i) => i.rule === "mvel-unsupported-break");
|
||||
expect(breakIssue).toBeDefined();
|
||||
expect(breakIssue?.level).toBe("error");
|
||||
expect(breakIssue?.message).toContain("break");
|
||||
});
|
||||
});
|
||||
|
||||
describe("lintWorkflowScripts", () => {
|
||||
|
||||
@@ -154,9 +154,96 @@ export function lintMvelCode(
|
||||
}
|
||||
}
|
||||
|
||||
// 3. 检查条件分支块 (if / else / switch / case / catch) 内部首次赋值但未在外部作用域预先声明的变量
|
||||
// 杜绝 MVEL2 ReflectiveAccessorOptimizer 误将局部变量当属性反射而触发 unresolvable property or identifier 运行时异常
|
||||
checkMvelUnscopedBlockAssignments(executableCode, issues);
|
||||
|
||||
// 4. 检查 MVEL2 不支持的 break 控制流关键字
|
||||
// MVEL2 解释器在循环中不支持 break,会误触发属性查找并抛出 unresolvable property or identifier: break
|
||||
const breakRegex = /\bbreak\b/g;
|
||||
let breakMatch: RegExpExecArray | null;
|
||||
while ((breakMatch = breakRegex.exec(executableCode)) !== null) {
|
||||
const textBefore = executableCode.slice(0, breakMatch.index);
|
||||
const lineNum = textBefore.split("\n").length;
|
||||
const lastNewline = textBefore.lastIndexOf("\n");
|
||||
const colNum = breakMatch.index - (lastNewline >= 0 ? lastNewline : 0);
|
||||
issues.push({
|
||||
level: "error",
|
||||
line: lineNum,
|
||||
column: colNum,
|
||||
rule: "mvel-unsupported-break",
|
||||
message: "MVEL2 运行时不支持 break 关键字,在循环内使用 break 会被解析器当成未声明属性查找而抛出 'unresolvable property or identifier: break' 致命异常;请改用 boolean 标志位条件控制循环终止",
|
||||
});
|
||||
}
|
||||
|
||||
return { issues, referencedNodes, hasReturn: hasRet };
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查条件分支块内部首次赋值但未在外部预先初始化的变量
|
||||
*/
|
||||
function checkMvelUnscopedBlockAssignments(executableCode: string, issues: ScriptIssue[]): void {
|
||||
const lines = executableCode.split(/\r?\n/);
|
||||
const knownVars = new Set([
|
||||
"bill", "result", "items", "success", "message", "System",
|
||||
"true", "false", "null", "Double", "Integer", "Long", "Float", "String", "Math", "Calendar", "Date",
|
||||
]);
|
||||
|
||||
let inBranchBlock = 0;
|
||||
const branchBraceDepths: number[] = [];
|
||||
let pendingBranch = false;
|
||||
|
||||
for (let l = 0; l < lines.length; l++) {
|
||||
const line = lines[l];
|
||||
|
||||
if (/\b(if|else|catch|switch|case)\b/.test(line)) {
|
||||
pendingBranch = true;
|
||||
}
|
||||
|
||||
for (let c = 0; c < line.length; c++) {
|
||||
const ch = line[c];
|
||||
if (ch === "{") {
|
||||
if (pendingBranch) {
|
||||
branchBraceDepths.push(branchBraceDepths.length + 1);
|
||||
inBranchBlock++;
|
||||
pendingBranch = false;
|
||||
} else {
|
||||
branchBraceDepths.push(0);
|
||||
}
|
||||
} else if (ch === "}") {
|
||||
if (branchBraceDepths.length > 0) {
|
||||
const depth = branchBraceDepths.pop();
|
||||
if (depth && depth > 0) inBranchBlock--;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const assignRegex = /(?:^|[^\w$.])([a-zA-Z_$][a-zA-Z0-9_$]*)\s*=(?!=)/g;
|
||||
let m: RegExpExecArray | null;
|
||||
while ((m = assignRegex.exec(line)) !== null) {
|
||||
const varName = m[1];
|
||||
if (["if", "else", "while", "for", "return", "new", "throw", "try", "catch", "finally", "switch", "case"].includes(varName)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (inBranchBlock > 0) {
|
||||
if (!knownVars.has(varName)) {
|
||||
issues.push({
|
||||
level: "warning",
|
||||
line: l + 1,
|
||||
column: m.index + 1,
|
||||
rule: "mvel-unscoped-block-assignment",
|
||||
message: `变量 [${varName}] 在条件分支块内部首次被赋值,但在外层作用域未预先声明或初始化;在 MVEL2 优化编译模式下极易触发 'unresolvable property or identifier' 运行时异常,建议在外部提前声明/初始化 (如: ${varName} = null;) 或改用三元表达式`,
|
||||
});
|
||||
knownVars.add(varName);
|
||||
}
|
||||
} else {
|
||||
knownVars.add(varName);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 递归收集工作流任务树中所有节点标识
|
||||
*/
|
||||
|
||||
Reference in new issue
Block a user