merge(main): 合入 main (v0.8.22) 解决 catalog 灰度开通网关冲突
- 解决 src/domains/platform/workflow/transport/catalog/api.ts 中的冲突, 合并 innerData 解析与 interpretGatewayOutcome 判定逻辑; - 执行 bun install 补齐 qrcode-terminal 依赖; - 全部 1021 个单测通过,tsc --noEmit 校验通过。
This commit is contained in:
commit
c3e39fe77a
53 files changed
+20116
-640
No files matched your search
@@ -220,7 +220,9 @@ export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
|
||||
"check": "检查错误管道",
|
||||
"enum": "查询在线枚举字典(不可用时使用内置字典)",
|
||||
"lint-script": "静态检查 JavaScript / MVEL 脚本",
|
||||
"eval-script": "在本地沙箱中模拟执行脚本"
|
||||
"eval-script": "在本地沙箱中模拟执行脚本",
|
||||
"webhook": "向工作流 Webhook 触发器发送测试数据 (别名: webhook-send)",
|
||||
"link": "生成工作流设计器 (Piper) 免密直达链接 (包含特权警告)"
|
||||
},
|
||||
"options": [
|
||||
"--flow=<单号> 指定测试单据",
|
||||
@@ -271,9 +273,13 @@ export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
|
||||
"run-script": "eval-script",
|
||||
"enums": "enum",
|
||||
"dictionary": "enum",
|
||||
"dict": "enum"
|
||||
"dict": "enum",
|
||||
"webhook-send": "webhook",
|
||||
"webhooks": "webhook",
|
||||
"url": "link",
|
||||
"web": "link"
|
||||
},
|
||||
flags: { ...flagList("all allow-prod allow-production auto-publish autoPublish compare detail diff empty errors f fail fail-on-alert failOnAlert failed failed-only failedOnly follow force force-write forceWrite full has-error hasError in-place inPlace includeDetail json none once publish snapshot v value-json valueJson verbose with-tasks withTasks timeline progress steps", "boolean"), ...flagList("a admin-key adminKey after app app-id appId b bill body c code code-file container count d data desc description display display-name displayName end-time endTime entity execution-logs field file filter flow flow-code flowCode from i id input input-file insert-after interval job job-id job1 job2 jobA jobB jobId json-file keyword l label limit log logs mapping mapping-file max-jobs maxJobs n name node node-id nodeId nodes output output-file outputFile p page page-size pageSize parent parent-id parentId password path payload pipeline pipeline-id pipelineId platform platform-id platformId pwd q query record s sample sample-id sampleId set size snapshot1 snapshot2 snapshotA snapshotB source start-time startTime state state-file stateFile t target targetName targetPlatformId task taskType third-id thirdId timeout timeout-ms timeoutMs to trigger type types value workflowId", "value") }
|
||||
flags: { ...flagList("all allow-prod allow-production auto-publish autoPublish compare detail diff empty errors f fail fail-on-alert failOnAlert failed failed-only failedOnly follow force force-write forceWrite full has-error hasError in-place inPlace includeDetail json none once publish snapshot v value-json valueJson verbose with-tasks withTasks timeline progress steps", "boolean"), ...flagList("a admin-key adminKey after app app-id appId b bill body c code code-file container count d data desc description display display-name displayName end-time endTime entity execution-logs field file filter flow flow-code flowCode from i id input input-file insert-after interval job job-id job1 job2 jobA jobB jobId json-file keyword l label limit log logs mapping mapping-file max-jobs maxJobs n name node node-id nodeId nodes output output-file outputFile p page page-size pageSize parent parent-id parentId password path payload pipeline pipeline-id pipelineId platform platform-id platformId pwd q query record s sample sample-id sampleId seconds set size sleep-time sleepTime snapshot1 snapshot2 snapshotA snapshotB source start-time startTime state state-file stateFile t target targetName targetPlatformId task taskType third-id thirdId timeout timeout-ms timeoutMs to trigger type types value workflowId", "value") }
|
||||
},
|
||||
"bill": {
|
||||
"summary": "单据检索、表单规格诊断与审批动作",
|
||||
@@ -832,8 +838,9 @@ export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
|
||||
"forward": "transfer"
|
||||
},
|
||||
flags: {
|
||||
...flagList("token t user name u hose-token jwt ticket ticket-id auth-code staff staff-id staffId alias corp-name count limit n start offset state status corpid id keyword query q message msg reason matter hours hour duration days day to recipient target remarks comment corp", "value"),
|
||||
...flagList("all a logout admin save import persist switch current overwrite candidates list-candidates", "boolean")
|
||||
...flagList("token t user name u hose-token jwt ticket ticket-id auth-code staff staff-id staffId alias corp-name count limit n start offset state corpid id keyword query q message msg reason matter hours hour duration days day to recipient target remarks comment corp", "value"),
|
||||
...flagList("all a logout admin save import persist switch current overwrite candidates list-candidates qr check", "boolean"),
|
||||
...flagList("status", "boolean-or-value")
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
@@ -4,7 +4,10 @@ import {
|
||||
clearAssistPlatformSession,
|
||||
} from "../../../core/auth/assist-platform-store.js";
|
||||
import { createAssistPlatformClient } from "../../../core/http/assist-platform-client.js";
|
||||
import { searchCorporations } from "../../../domains/assist-platform/services.js";
|
||||
import {
|
||||
searchCorporations,
|
||||
loginAssistPlatformByQrCode,
|
||||
} from "../../../domains/assist-platform/services.js";
|
||||
import { booleanOption, stringOption } from "../../parser.js";
|
||||
import { printJson, printKeyValue } from "../../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||
@@ -66,35 +69,150 @@ export async function handleLogin(
|
||||
};
|
||||
}
|
||||
|
||||
// 查看当前协助平台会话状态
|
||||
const checkStatusOnly = booleanOption(parsed.options, ["status", "check"]);
|
||||
const forceQr = booleanOption(parsed.options, ["qr", "force"]);
|
||||
const isInteractive = Boolean(
|
||||
process.stdin.isTTY && !process.env.CI && process.env.NODE_ENV !== "test"
|
||||
);
|
||||
const existing = loadAssistPlatformSession();
|
||||
if (!existing || !existing.token) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `未检测到协助平台登录凭证。\n用法:\n hose-use assist-platform login --token <TOKEN> [--user <姓名>]\n hose-use assist-platform login --logout (清理凭证)\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
// 如果仅检查状态 (--status)
|
||||
if (checkStatusOnly) {
|
||||
if (!existing || !existing.token) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `[ERROR] 未检测到协助平台登录凭证。\n请运行: hose-use assist-platform login 进行扫码登录\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const testClient = createAssistPlatformClient({
|
||||
token: existing.token,
|
||||
baseUrl: existing.baseUrl,
|
||||
hoseAccessToken: existing.hoseAccessToken,
|
||||
});
|
||||
|
||||
try {
|
||||
await searchCorporations(testClient, { limit: { start: 0, count: 1 } });
|
||||
} catch {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `[ERROR] 协助平台凭证已过期或无效。\n请运行: hose-use assist-platform login 进行扫码登录\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({ valid: true, ...existing }),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const pairs: Record<string, string> = {
|
||||
协助平台状态: "🟢 凭证有效 (已登录)",
|
||||
操作员工姓名: existing.userName || "运营实施人员",
|
||||
基础服务地址: existing.baseUrl || "https://unity.ekuaibao.com/api",
|
||||
当前会话凭证: existing.token.replace(/(.{4}).*(.{4})/, "$1****$2"),
|
||||
最后更新时间: new Date(existing.updatedAt).toLocaleString("zh-CN", { hour12: false }),
|
||||
};
|
||||
|
||||
return {
|
||||
stdout: printJson(existing),
|
||||
stdout: `====== 合思协助平台当前会话 ======\n${printKeyValue(pairs)}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const pairs: Record<string, string> = {
|
||||
协助平台状态: "🟢 已登录",
|
||||
操作员工姓名: existing.userName || "运营实施人员",
|
||||
基础服务地址: existing.baseUrl || "https://unity.ekuaibao.com/api",
|
||||
当前会话凭证: existing.token.replace(/(.{4}).*(.{4})/, "$1****$2"),
|
||||
最后更新时间: new Date(existing.updatedAt).toLocaleString("zh-CN", { hour12: false }),
|
||||
};
|
||||
// 如果已有凭证且未强制发起扫码,先探测有效性
|
||||
if (existing?.token && !forceQr) {
|
||||
let isValid = false;
|
||||
const testClient = createAssistPlatformClient({
|
||||
token: existing.token,
|
||||
baseUrl: existing.baseUrl,
|
||||
hoseAccessToken: existing.hoseAccessToken,
|
||||
});
|
||||
|
||||
return {
|
||||
stdout: `====== 合思协助平台当前会话 ======\n${printKeyValue(pairs)}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
try {
|
||||
await searchCorporations(testClient, { limit: { start: 0, count: 1 } });
|
||||
isValid = true;
|
||||
} catch {
|
||||
isValid = false;
|
||||
}
|
||||
|
||||
if (isValid) {
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(existing),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const pairs: Record<string, string> = {
|
||||
协助平台状态: "🟢 已登录 (凭证有效)",
|
||||
操作员工姓名: existing.userName || "运营实施人员",
|
||||
基础服务地址: existing.baseUrl || "https://unity.ekuaibao.com/api",
|
||||
当前会话凭证: existing.token.replace(/(.{4}).*(.{4})/, "$1****$2"),
|
||||
最后更新时间: new Date(existing.updatedAt).toLocaleString("zh-CN", { hour12: false }),
|
||||
};
|
||||
|
||||
return {
|
||||
stdout: `====== 合思协助平台当前会话 ======\n${printKeyValue(pairs)}\n\n💡 提示: 当前凭证处于有效状态。如需重新扫码登录,请运行: hose-use assist-platform login --qr\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// 凭证不存在或已失效:非交互/测试模式下给出指引,交互模式或显式 --qr 下直接自动拉起扫码登录
|
||||
if (!isInteractive && !forceQr) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `未检测到协助平台登录凭证。\n用法:\n hose-use assist-platform login [--qr]\n hose-use assist-platform login --token <TOKEN> [--user <姓名>]\n hose-use assist-platform login --logout (清理凭证)\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
// ── 自动发起钉钉交互式扫码登录流程 ──────────────────────────
|
||||
try {
|
||||
const loginRes = await loginAssistPlatformByQrCode({
|
||||
timeoutMs: 60000,
|
||||
onQrCode: (qrText, dingUrl) => {
|
||||
if (!runtime.jsonMode) {
|
||||
process.stdout.write(`\n====== 合思协助平台钉钉扫码登录 ======\n`);
|
||||
process.stdout.write(`请使用钉钉 App 扫描下方二维码确认登录(有效期 60 秒):\n\n`);
|
||||
process.stdout.write(`${qrText}\n\n`);
|
||||
process.stdout.write(`🔗 快捷授权链接: ${dingUrl}\n\n`);
|
||||
process.stdout.write(`等待钉钉扫码并确认中... (最长等待 60 秒)\n`);
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({
|
||||
success: true,
|
||||
token: loginRes.token,
|
||||
userName: loginRes.userName,
|
||||
baseUrl: loginRes.baseUrl,
|
||||
}),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: `\n[SUCCESS] 协助平台凭证已自动更新成功!\n操作人员: ${loginRes.userName}\n会话 Token: ${loginRes.token}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
} catch (err) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `[ERROR] 协助平台扫码登录失败: ${err instanceof Error ? err.message : String(err)}\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -2331,5 +2331,90 @@ describe("CLI - workflow list 轻量化与名称搜索", () => {
|
||||
expect(data.workflows[0].pipelineName).toBe("待摊台账拆分计划");
|
||||
expect(data.totalWorkflows).toBe(1);
|
||||
});
|
||||
|
||||
it("workflow link 生成高特权免密直达链接并输出安全警告与自建应用信息", async () => {
|
||||
const mockSessionClient = {
|
||||
get: () => ({
|
||||
json: async () => ({ id: "mock.jwt.token" }),
|
||||
}),
|
||||
};
|
||||
spies.push(
|
||||
spyOn(helpers, "createClientsForCorp").mockResolvedValue({
|
||||
sessionClient: mockSessionClient,
|
||||
} as any),
|
||||
spyOn(platformServices, "listAllWorkflows").mockResolvedValue({
|
||||
workflows: [
|
||||
{
|
||||
id: "wf_001",
|
||||
pipelineName: "待摊台账拆分计划",
|
||||
platformId: "app_platform_1",
|
||||
platformName: "商机台账",
|
||||
state: 1,
|
||||
},
|
||||
] as any,
|
||||
errors: [],
|
||||
})
|
||||
);
|
||||
|
||||
const res = await handleWorkflowCommand(
|
||||
{
|
||||
area: "workflow",
|
||||
action: "link",
|
||||
args: ["wf_001"],
|
||||
options: {},
|
||||
raw: ["workflow", "link", "wf_001"],
|
||||
},
|
||||
mockRuntime
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("【高特权免密直达警告】");
|
||||
expect(res.stdout).toContain("所属自建应用 : 商机台账 (app_platform_1)");
|
||||
expect(res.stdout).toContain("目标工作流 : 待摊台账拆分计划 (wf_001)");
|
||||
expect(res.stdout).toContain("https://piper.ekuaibao.com/#/workflow/wf_001?jwtToken=mock.jwt.token&$platformId=app_platform_1");
|
||||
});
|
||||
|
||||
it("workflow link --json 返回结构化授权链接与警告信息", async () => {
|
||||
const mockSessionClient = {
|
||||
get: () => ({
|
||||
json: async () => ({ id: "mock.jwt.token" }),
|
||||
}),
|
||||
};
|
||||
spies.push(
|
||||
spyOn(helpers, "createClientsForCorp").mockResolvedValue({
|
||||
sessionClient: mockSessionClient,
|
||||
} as any),
|
||||
spyOn(platformServices, "listAllWorkflows").mockResolvedValue({
|
||||
workflows: [
|
||||
{
|
||||
id: "wf_001",
|
||||
pipelineName: "待摊台账拆分计划",
|
||||
platformId: "app_platform_1",
|
||||
platformName: "商机台账",
|
||||
state: 1,
|
||||
},
|
||||
] as any,
|
||||
errors: [],
|
||||
})
|
||||
);
|
||||
|
||||
const res = await handleWorkflowCommand(
|
||||
{
|
||||
area: "workflow",
|
||||
action: "link",
|
||||
args: ["wf_001"],
|
||||
options: { json: true },
|
||||
raw: ["workflow", "link", "wf_001", "--json"],
|
||||
},
|
||||
{ ...mockRuntime, jsonMode: true }
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
const data = JSON.parse(res.stdout);
|
||||
expect(data.pipelineId).toBe("wf_001");
|
||||
expect(data.platformName).toBe("商机台账");
|
||||
expect(data.jwtToken).toBe("mock.jwt.token");
|
||||
expect(data.warning).toContain("特权");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -15,6 +15,7 @@
|
||||
| [analyze.ts](./analyze.ts)、[check.ts](./check.ts)、[diff.ts](./diff.ts) | 静态分析、健康检查与配置/执行差异 |
|
||||
| [script.ts](./script.ts)、[test.ts](./test.ts) | 脚本校验、求值与工作流测试 |
|
||||
| [tail.ts](./tail.ts)、[webhook.ts](./webhook.ts)、[enum.ts](./enum.ts) | 执行监听、Webhook 与业务枚举 |
|
||||
| [link.ts](./link.ts) | 工作流设计器 (Piper) 免密直达链接签发与高特权安全警告 |
|
||||
|
||||
## 保存和执行契约
|
||||
|
||||
|
||||
@@ -0,0 +1,146 @@
|
||||
import { afterEach, beforeEach, describe, expect, it } from "bun:test";
|
||||
import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { tmpdir } from "node:os";
|
||||
import { runCli } from "../../runner.js";
|
||||
import { renderScopedHelp } from "../../help.js";
|
||||
|
||||
const keys = ["HOSE_ENTERPRISES_DIR", "HOSE_CONFIG_FILE"] as const;
|
||||
const original = keys.map((key) => process.env[key]);
|
||||
let tempDir = "";
|
||||
|
||||
describe("workflow CLI ergonomics & layered help", () => {
|
||||
beforeEach(() => {
|
||||
tempDir = mkdtempSync(join(tmpdir(), "hose-ergonomics-"));
|
||||
const corps = join(tempDir, "corps");
|
||||
mkdirSync(corps, { recursive: true });
|
||||
writeFileSync(
|
||||
join(corps, "corp.json"),
|
||||
JSON.stringify({
|
||||
id: "corp",
|
||||
name: "Fixture",
|
||||
source: "manual",
|
||||
credentials: { accessToken: "fake", corpId: "corp", staffId: "staff" },
|
||||
})
|
||||
);
|
||||
writeFileSync(
|
||||
join(tempDir, "config.json"),
|
||||
JSON.stringify({ defaultCorpId: "corp", stateful: true })
|
||||
);
|
||||
process.env.HOSE_ENTERPRISES_DIR = corps;
|
||||
process.env.HOSE_CONFIG_FILE = join(tempDir, "config.json");
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
keys.forEach((key, i) => {
|
||||
if (original[i] === undefined) delete process.env[key];
|
||||
else process.env[key] = original[i];
|
||||
});
|
||||
if (tempDir) {
|
||||
rmSync(tempDir, { recursive: true, force: true });
|
||||
tempDir = "";
|
||||
}
|
||||
});
|
||||
it("renders specialized layered help for workflow node add", () => {
|
||||
const help = renderScopedHelp(["workflow", "node", "add"]);
|
||||
expect(help).toContain("workflow node add -");
|
||||
expect(help).toContain("--type=<type>");
|
||||
expect(help).toContain("--sleep-time=<秒数>");
|
||||
expect(help).toContain("--set='key=value'");
|
||||
expect(help).toContain("--after=<节点name>");
|
||||
expect(help).toContain("支持选项:");
|
||||
});
|
||||
|
||||
it("renders specialized layered help for workflow node edit", () => {
|
||||
const help = renderScopedHelp(["workflow", "node", "edit"]);
|
||||
expect(help).toContain("workflow node edit -");
|
||||
expect(help).toContain("--sleep-time=<秒数>");
|
||||
expect(help).toContain("--set='key=value'");
|
||||
expect(help).toContain("支持选项:");
|
||||
});
|
||||
|
||||
it("renders specialized layered help for workflow test", () => {
|
||||
const help = renderScopedHelp(["workflow", "test"]);
|
||||
expect(help).toContain("workflow test -");
|
||||
expect(help).toContain("--flow=<单号>");
|
||||
expect(help).toContain("--body='{...}'");
|
||||
expect(help).toContain("--sample=<1|2|3>");
|
||||
expect(help).toContain("支持选项:");
|
||||
});
|
||||
|
||||
it("renders specialized layered help for workflow webhook send", () => {
|
||||
const help = renderScopedHelp(["workflow", "webhook", "send"]);
|
||||
expect(help).toContain("workflow webhook send -");
|
||||
expect(help).toContain("--bill=<单号|单据ID>");
|
||||
expect(help).toContain("--body='{...}'");
|
||||
expect(help).toContain("支持选项:");
|
||||
});
|
||||
|
||||
it("runCli correctly resolves sub-subcommand help via --help flag", async () => {
|
||||
const result = await runCli(["workflow", "node", "add", "--help"]);
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain("workflow node add -");
|
||||
expect(result.stdout).toContain("--sleep-time=<秒数>");
|
||||
});
|
||||
|
||||
it("workflow test automatically swaps reversed arguments (billCode and 18-digit pipelineId)", async () => {
|
||||
const result = await runCli(["workflow", "test", "B26000148", "881196955148578838", "--dry-run"]);
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain("881196955148578838");
|
||||
expect(result.stdout).toContain("B26000148");
|
||||
});
|
||||
|
||||
it("workflow node add dry-run accepts --sleep-time directly", async () => {
|
||||
const result = await runCli([
|
||||
"workflow",
|
||||
"node",
|
||||
"add",
|
||||
"881196955148578838",
|
||||
"--type=task-dynamic-delay",
|
||||
"--sleep-time=5",
|
||||
"--dry-run",
|
||||
]);
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain("追加工作流节点");
|
||||
expect(result.stdout).toContain("task-dynamic-delay");
|
||||
});
|
||||
|
||||
it("workflow node edit dry-run parses JSON payload in --set", async () => {
|
||||
const result = await runCli([
|
||||
"workflow",
|
||||
"node",
|
||||
"edit",
|
||||
"881196955148578838",
|
||||
"action_agree_normal",
|
||||
'--set={"authId":157,"appId":"4"}',
|
||||
"--dry-run",
|
||||
]);
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain("修改工作流节点");
|
||||
expect(result.stdout).toContain('"authId":157');
|
||||
expect(result.stdout).toContain('"appId":"4"');
|
||||
});
|
||||
|
||||
it("WorkflowTaskSchema preserves authId and appId on http tasks without stripping", async () => {
|
||||
const { WorkflowTaskSchema } = await import("../../../domains/platform/workflow/models/nodes.js");
|
||||
const sample = {
|
||||
name: "action_test",
|
||||
type: "http",
|
||||
label: "http节点",
|
||||
groupName: "action",
|
||||
orderIndex: 0,
|
||||
levelIndex: [0],
|
||||
status: "active",
|
||||
method: "POST",
|
||||
url: "https://example.com",
|
||||
header: [],
|
||||
params: [],
|
||||
successCode: ["200"],
|
||||
authId: 157,
|
||||
appId: "4",
|
||||
};
|
||||
const parsed = WorkflowTaskSchema.parse(sample);
|
||||
expect((parsed as any).authId).toBe(157);
|
||||
expect((parsed as any).appId).toBe("4");
|
||||
});
|
||||
});
|
||||
@@ -16,6 +16,7 @@ import { handleWorkflowTailCommand } from "./tail.js";
|
||||
import { handleWorkflowLintScript, handleWorkflowEvalScript } from "./script.js";
|
||||
import { handleWorkflowEnum } from "./enum.js";
|
||||
import { handleWebhookCommand } from "./webhook.js";
|
||||
import { handleWorkflowLink } from "./link.js";
|
||||
|
||||
export async function handleWorkflowCommand(
|
||||
parsed: CliParsedArgs,
|
||||
@@ -121,10 +122,14 @@ export async function handleWorkflowCommand(
|
||||
case "webhook-send":
|
||||
case "webhooks":
|
||||
return handleWebhookCommand(parsed, runtime);
|
||||
case "link":
|
||||
case "url":
|
||||
case "web":
|
||||
return handleWorkflowLink(parsed, runtime);
|
||||
default:
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `未知 workflow 子命令: ${action}。支持: list, get, find, analyze, toggle, publish, patch, save, refresh-chooses, history, logs, job, diff, diff-job, check, test, copy, create, delete, node, tail, lint-script, eval-script, enum, webhook\n`,
|
||||
stderr: `未知 workflow 子命令: ${action}。支持: list, get, find, analyze, toggle, publish, patch, save, refresh-chooses, history, logs, job, diff, diff-job, check, test, copy, create, delete, node, tail, lint-script, eval-script, enum, webhook, link\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
import { stringOption } from "../../parser.js";
|
||||
import { printJson } from "../../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||
import { createClientsForCorp } from "../../helpers.js";
|
||||
import { listAllWorkflows } from "../../../domains/platform/workflow/services.js";
|
||||
|
||||
// ── 工作流设计器 (Piper) 免密直达链接签发 ────────────────────────────────────
|
||||
|
||||
export async function handleWorkflowLink(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
const corp = runtime.selectedCorp!;
|
||||
const pipelineId =
|
||||
parsed.args[0] ||
|
||||
stringOption(parsed.options, ["id", "pipelineId", "workflowId", "pipeline"]);
|
||||
|
||||
if (!pipelineId) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: [
|
||||
"请提供工作流 ID: hose-use workflow link <pipelineId> [选项]",
|
||||
"",
|
||||
"常用选项:",
|
||||
" --corp=<corpId> 指定企业 (默认当前企业)",
|
||||
" --platform-id=<platformId> 指定所属自建应用 ID (可选,默认自动识别)",
|
||||
" --json 输出结构化 JSON 格式",
|
||||
"",
|
||||
"示例:",
|
||||
" hose-use workflow link 881196955148578838",
|
||||
].join("\n") + "\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const clients = await createClientsForCorp(corp);
|
||||
|
||||
// 1. 查询工作流元数据及所属自建应用平台信息
|
||||
let platformId = stringOption(parsed.options, ["platform-id", "platformId", "app-id", "appId"]);
|
||||
let platformName = "";
|
||||
let pipelineName = "";
|
||||
let workflowState: number | undefined;
|
||||
|
||||
try {
|
||||
const all = await listAllWorkflows(clients, { page: 1, pageSize: 100 });
|
||||
const match = all.workflows.find((w) => w.id === pipelineId);
|
||||
if (match) {
|
||||
pipelineName = match.pipelineName || "";
|
||||
platformId = platformId || match.platformId || "";
|
||||
platformName = match.platformName || "";
|
||||
workflowState = match.state;
|
||||
}
|
||||
} catch {
|
||||
// 容错降级
|
||||
}
|
||||
|
||||
platformId = platformId || corp.corpId || corp.id;
|
||||
|
||||
// 2. 向 EASO Realm 申请专属 3 段式 JWT 授权凭据
|
||||
let jwt = "";
|
||||
try {
|
||||
const jwtRes = await clients.sessionClient.get("api/engine/realm/$EASO/actions/jwt", {
|
||||
searchParams: { corpId: corp.corpId || corp.id },
|
||||
}).json<{ id: string }>();
|
||||
jwt = jwtRes.id;
|
||||
} catch (err) {
|
||||
const errMsg = err instanceof Error ? err.message : String(err);
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `获取 EASO JWT 授权凭据失败: ${errMsg}\n请确认当前会话是否有效或重新登录。\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const directUrl = `https://piper.ekuaibao.com/#/workflow/${pipelineId}?jwtToken=${jwt}&$platformId=${encodeURIComponent(platformId)}`;
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
const output = {
|
||||
pipelineId,
|
||||
pipelineName: pipelineName || pipelineId,
|
||||
corpId: corp.corpId || corp.id,
|
||||
corpName: corp.name,
|
||||
env: corp.env || (corp.isTest ? "test" : "prod"),
|
||||
staffId: corp.staffId,
|
||||
staffName: corp.staffName || corp.staffId,
|
||||
platformId,
|
||||
platformName: platformName || "自建应用",
|
||||
state: workflowState,
|
||||
jwtToken: jwt,
|
||||
url: directUrl,
|
||||
warning: "⚠️ 该直达链接具备以当前员工身份免密直接访问和修改工作流的最高特权,严禁外泄!",
|
||||
};
|
||||
return {
|
||||
stdout: printJson(output, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const envTag = corp.isTest ? "🧪 测试环境" : "🚨 生产环境";
|
||||
const stateText =
|
||||
workflowState === 1
|
||||
? "🟢 启用中 (state=1)"
|
||||
: workflowState === 0
|
||||
? "⚪ 停用/草稿 (state=0)"
|
||||
: "未知";
|
||||
|
||||
const lines = [
|
||||
"⚠️ 【高特权免密直达警告】(HIGH PRIVILEGE DIRECT ACCESS WARNING)",
|
||||
" ----------------------------------------------------------------------",
|
||||
" • 该链接包含有效 3 段式 EASO JWT 授权凭证,在浏览器中打开即直接以当前员工身份进入!",
|
||||
" • 具有对该工作流的所有节点配置、代码脚本、版本发布及运行实例的完全编辑/删除/调试权限!",
|
||||
" • 严禁将该链接发送到群聊、公开工单或不受信渠道;使用完毕后请及时关闭会话标签页。",
|
||||
" ----------------------------------------------------------------------",
|
||||
"",
|
||||
"====== 合思工作流设计器 (Piper) 免密直达链接 ======",
|
||||
` 企业名称 : ${corp.name} (${corp.corpId || corp.id}) [${envTag}]`,
|
||||
` 操作人身份 : ${corp.staffName || "未指定姓名"} (${corp.staffId})`,
|
||||
` 所属自建应用 : ${platformName ? `${platformName} (${platformId})` : platformId}`,
|
||||
` 目标工作流 : ${pipelineName ? `${pipelineName} (${pipelineId})` : pipelineId}`,
|
||||
` 当前流程状态 : ${stateText}`,
|
||||
" 凭证有效时长 : 约 2 小时 (由合思 EASO Realm 动态颁发)",
|
||||
"",
|
||||
" 直达链接:",
|
||||
` ${directUrl}`,
|
||||
"",
|
||||
`Markdown 直达: [打开「${platformName || "工作流"}」设计器 (${pipelineName || pipelineId} - ${corp.staffName || "免密"})](${directUrl})`,
|
||||
];
|
||||
|
||||
return {
|
||||
stdout: `${lines.join("\n")}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
@@ -11,7 +11,7 @@ import {
|
||||
import { isServerManagedDescType } from "../../../domains/platform/workflow/nodes/mutations.js";
|
||||
import { ValidationError } from "../../../core/errors.js";
|
||||
import type { WorkflowDetail } from "../../../domains/platform/workflow/types.js";
|
||||
import { stringOption } from "../../parser.js";
|
||||
import { stringOption, numberOption } from "../../parser.js";
|
||||
import { printJson, printTable, printKeyValue } from "../../printer.js";
|
||||
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../../mutation.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||
@@ -257,10 +257,12 @@ async function handleAddNode(
|
||||
stdout: "",
|
||||
stderr: [
|
||||
"请指定新增节点类型: --type=<类型>",
|
||||
"常见类型: code-js2 (JS脚本), code (MVEL代码), http (HTTP请求), stop (终止流程), every (循环遍历), condition (分支条件)",
|
||||
"常见类型: task-dynamic-delay (延迟等待), code-js2 (JS脚本), code (MVEL代码), http (HTTP请求), stop (终止流程), every (循环遍历), condition (分支条件)",
|
||||
"",
|
||||
"常用选项:",
|
||||
" --type=<type> 节点类型 (如 code-js2 / code)",
|
||||
" --type=<type> 节点类型 (如 task-dynamic-delay / code-js2 / http)",
|
||||
" --sleep-time=<秒数> 延迟等待秒数 (针对 task-dynamic-delay,如 5)",
|
||||
" --set='key=value' 自定义节点属性注入",
|
||||
" --label=<标题> 节点类型标题",
|
||||
" --display-name=<名称> 设计器节点标题(displayName,最多 20 字符)",
|
||||
" --code-file=<脚本路径> (推荐) 从本地文件导入代码,避免终端转义与 Token 浪费",
|
||||
@@ -269,7 +271,9 @@ async function handleAddNode(
|
||||
" --after=<前置节点name> 插入指定节点之后",
|
||||
" --yes 确认追加",
|
||||
"",
|
||||
"示例: hose-use workflow node add 896398895352487950 --type=code-js2 --label='数据清洗' --code-file=./clean.js --yes",
|
||||
"示例:",
|
||||
" hose-use workflow node add 881196955148578838 --type=task-dynamic-delay --sleep-time=5 --after=action_123 --yes",
|
||||
" hose-use workflow node add 896398895352487950 --type=code-js2 --label='数据清洗' --code-file=./clean.js --yes",
|
||||
].join("\n") + "\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
@@ -288,6 +292,33 @@ async function handleAddNode(
|
||||
code = await fs.readFile(codeFile, "utf-8");
|
||||
}
|
||||
|
||||
const rawSleepTime = numberOption(parsed.options, ["sleep-time", "sleepTime", "seconds"]);
|
||||
const rawSet = stringOption(parsed.options, ["set", "value"]);
|
||||
const extra: Record<string, any> = {};
|
||||
if (rawSleepTime !== undefined) {
|
||||
extra.sleepTime = rawSleepTime;
|
||||
}
|
||||
if (rawSet) {
|
||||
if (rawSet.startsWith("{") && rawSet.endsWith("}")) {
|
||||
try {
|
||||
Object.assign(extra, JSON.parse(rawSet));
|
||||
} catch {
|
||||
// fallback
|
||||
}
|
||||
} else {
|
||||
const eqIdx = rawSet.indexOf("=");
|
||||
if (eqIdx !== -1) {
|
||||
const k = rawSet.slice(0, eqIdx).trim();
|
||||
const v = rawSet.slice(eqIdx + 1).trim();
|
||||
try {
|
||||
extra[k] = JSON.parse(v);
|
||||
} catch {
|
||||
extra[k] = v;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
requireMutationConfirmation(
|
||||
parsed,
|
||||
runtime,
|
||||
@@ -295,6 +326,17 @@ async function handleAddNode(
|
||||
`hose-use workflow node add ${pipelineId} --type=${type}${label ? ` --label="${label}"` : ""}${displayName ? ` --display-name="${displayName}"` : ""}${parent ? ` --parent="${parent}"` : ""}${after ? ` --after="${after}"` : ""} --yes`
|
||||
);
|
||||
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "追加工作流节点", pipelineId, {
|
||||
pipelineId,
|
||||
type,
|
||||
label: label || "-",
|
||||
displayName: displayName || "-",
|
||||
targetLocation: parent ? `容器 [${parent}] 内部` : after ? `节点 [${after}] 之后` : "工作流末尾",
|
||||
extra: Object.keys(extra).length ? extra : undefined,
|
||||
});
|
||||
}
|
||||
|
||||
const { client, platformId } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
|
||||
const detail = await getWorkflowDetail(client, pipelineId);
|
||||
|
||||
@@ -306,20 +348,9 @@ async function handleAddNode(
|
||||
code,
|
||||
parent,
|
||||
after,
|
||||
extra: Object.keys(extra).length ? extra : undefined,
|
||||
});
|
||||
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "追加工作流节点", pipelineId, {
|
||||
pipelineId,
|
||||
newNodeName: newTask.name,
|
||||
type: newTask.type,
|
||||
label: newTask.label,
|
||||
displayName: newTask.displayName,
|
||||
targetLocation: parent ? `容器 [${parent}] 内部` : after ? `节点 [${after}] 之后` : "工作流末尾",
|
||||
totalTasksCount: updatedWorkflow.tasks?.length || 0,
|
||||
});
|
||||
}
|
||||
|
||||
const saveResult = await saveNodeChanges(client, detail, updatedWorkflow, platformId);
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
@@ -359,12 +390,13 @@ async function handleEditNode(
|
||||
"请提供节点标识 (name 或层级序号): hose-use workflow node edit <pipelineId> <nodeNameOrIndex> [选项]",
|
||||
"",
|
||||
"常用选项:",
|
||||
" --sleep-time=<秒数> 更新延迟等待秒数 (针对 task-dynamic-delay,如 5)",
|
||||
" --set='key=value' 定向修改节点自定义属性 (如 --set='sleepTime=5')",
|
||||
" --label=<类型标题> 更新节点类型标题(服务端保存时可能重新生成)",
|
||||
" --display-name=<新名称> 更新设计器节点标题(displayName,最多 20 字符)",
|
||||
" --code-file=<脚本路径> (推荐) 从本地文件导入最新脚本,避免终端转义与 Token 浪费",
|
||||
" --code=<行内代码> 直接传入代码片段(短脚本)",
|
||||
" --desc=<描述> 更新节点描述",
|
||||
" --set='key=value' 定向修改节点自定义属性",
|
||||
" --dry-run 只预览变更",
|
||||
" --yes 确认保存修改",
|
||||
"",
|
||||
@@ -388,15 +420,27 @@ async function handleEditNode(
|
||||
|
||||
const rawSet = stringOption(parsed.options, ["set", "value"]);
|
||||
const customSet: Record<string, any> = {};
|
||||
const rawSleepTime = numberOption(parsed.options, ["sleep-time", "sleepTime", "seconds"]);
|
||||
if (rawSleepTime !== undefined) {
|
||||
customSet.sleepTime = rawSleepTime;
|
||||
}
|
||||
if (rawSet) {
|
||||
const eqIdx = rawSet.indexOf("=");
|
||||
if (eqIdx !== -1) {
|
||||
const k = rawSet.slice(0, eqIdx).trim();
|
||||
const v = rawSet.slice(eqIdx + 1).trim();
|
||||
if (rawSet.startsWith("{") && rawSet.endsWith("}")) {
|
||||
try {
|
||||
customSet[k] = JSON.parse(v);
|
||||
Object.assign(customSet, JSON.parse(rawSet));
|
||||
} catch {
|
||||
customSet[k] = v;
|
||||
// fallback to key=value if json parse fails
|
||||
}
|
||||
} else {
|
||||
const eqIdx = rawSet.indexOf("=");
|
||||
if (eqIdx !== -1) {
|
||||
const k = rawSet.slice(0, eqIdx).trim();
|
||||
const v = rawSet.slice(eqIdx + 1).trim();
|
||||
try {
|
||||
customSet[k] = JSON.parse(v);
|
||||
} catch {
|
||||
customSet[k] = v;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -416,6 +460,22 @@ async function handleEditNode(
|
||||
`hose-use workflow node edit ${pipelineId} ${nodeTarget}${label ? ` --label="${label}"` : ""}${displayName ? ` --display-name="${displayName}"` : ""} --yes`
|
||||
);
|
||||
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "修改工作流节点", `${pipelineId}:${nodeTarget}`, {
|
||||
pipelineId,
|
||||
nodeName: nodeTarget,
|
||||
label: label || "-",
|
||||
displayName: displayName || "-",
|
||||
updatedFields: {
|
||||
...(label ? { label } : {}),
|
||||
...(displayName !== undefined ? { displayName } : {}),
|
||||
...(desc ? { desc } : {}),
|
||||
...(code !== undefined ? { code: `${code.length} 字符${!codeFile && code.length > 300 ? " [TIP: 建议使用 --code-file=<path> 从本地文件载入以规避转义错误并节省 Token]" : ""}` } : {}),
|
||||
...customSet,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const { client, platformId } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
|
||||
const detail = await getWorkflowDetail(client, pipelineId);
|
||||
|
||||
@@ -428,22 +488,6 @@ async function handleEditNode(
|
||||
});
|
||||
const descManaged = desc !== undefined && isServerManagedDescType(editedTask.type);
|
||||
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "修改工作流节点", `${pipelineId}:${editedTask.name}`, {
|
||||
pipelineId,
|
||||
nodeName: editedTask.name,
|
||||
label: editedTask.label,
|
||||
updatedFields: {
|
||||
...(label ? { label } : {}),
|
||||
...(displayName !== undefined ? { displayName } : {}),
|
||||
...(desc && !descManaged ? { desc } : {}),
|
||||
...(descManaged ? { desc: "服务端托管,已跳过" } : {}),
|
||||
...(code !== undefined ? { code: `${code.length} 字符${!codeFile && code.length > 300 ? " [TIP: 建议使用 --code-file=<path> 从本地文件载入以规避转义错误并节省 Token]" : ""}` } : {}),
|
||||
...customSet,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const saveResult = await saveNodeChanges(client, detail, updatedWorkflow, platformId);
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
|
||||
@@ -18,7 +18,20 @@ export async function handleWorkflowTest(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
const pipelineId = parsed.args[0] || stringOption(parsed.options, ["id", "pipeline-id", "pipelineId"]);
|
||||
let pipelineId = parsed.args[0] || stringOption(parsed.options, ["id", "pipeline-id", "pipelineId"]);
|
||||
let flowCodeOrId = stringOption(parsed.options, ["flow", "record", "code", "flow-code", "flowCode", "bill", "entity", "id"]);
|
||||
|
||||
// 智能参数纠错:如果首参数疑似单号/台账记录(非纯数字长ID),且第二个位置参数为工作流ID(16~20位纯数字)
|
||||
if (
|
||||
parsed.args[0] &&
|
||||
parsed.args[1] &&
|
||||
/^\d{16,20}$/.test(parsed.args[1]) &&
|
||||
!/^\d{16,20}$/.test(parsed.args[0])
|
||||
) {
|
||||
flowCodeOrId = parsed.args[0];
|
||||
pipelineId = parsed.args[1];
|
||||
}
|
||||
|
||||
if (!pipelineId) {
|
||||
return {
|
||||
stdout: "",
|
||||
@@ -44,7 +57,6 @@ export async function handleWorkflowTest(
|
||||
};
|
||||
}
|
||||
|
||||
const flowCodeOrId = stringOption(parsed.options, ["flow", "record", "code", "flow-code", "flowCode", "bill", "entity", "id"]);
|
||||
const autoPublish = booleanOption(parsed.options, ["auto-publish", "autoPublish", "publish"]);
|
||||
const timeoutMs = numberOption(parsed.options, ["timeout", "timeout-ms", "timeoutMs"]) ?? 15000;
|
||||
const rawBody = stringOption(parsed.options, ["body", "data", "payload"]);
|
||||
@@ -245,13 +257,16 @@ export async function handleWorkflowTest(
|
||||
...(sampleLines.length > 0
|
||||
? [` --sample=<1|2|3> 直接选用上述服务器最近接收的数据样本发起测试`]
|
||||
: []),
|
||||
` --flow=<单号> 提取指定单据的编码与数据作为 Webhook Payload 发起测试`,
|
||||
` --body='{"key": "value"}' 直接传入自定义 JSON 请求体`,
|
||||
` --file=<payload.json> 从本地 JSON 文件读取请求体`,
|
||||
` --empty 使用空对象 {} 直接发起测试`,
|
||||
"",
|
||||
`示例: hose-use workflow test ${pipelineId} ${
|
||||
sampleLines.length > 0 ? "--sample=1" : `--body='{"code": "TEST-001"}'`
|
||||
`示例:`,
|
||||
` hose-use workflow test ${pipelineId} ${
|
||||
sampleLines.length > 0 ? "--sample=1" : `--flow=B26000148`
|
||||
}`,
|
||||
` hose-use workflow webhook send ${pipelineId} --bill=B26000148 --yes`,
|
||||
].join("\n") + "\n",
|
||||
stderr: "",
|
||||
exitCode: 1,
|
||||
@@ -357,9 +372,13 @@ export async function handleWorkflowTest(
|
||||
].join("\n");
|
||||
return { stdout: `${out}\n`, stderr: "", exitCode: 1 };
|
||||
} catch (err: any) {
|
||||
const errMsg = err.message || String(err);
|
||||
const notFoundHint = errMsg.includes("expected 1 result. got 0")
|
||||
? `\n💡 提示: 云端未查询到工作流 [${pipelineId}] 的调试数据源,请检查工作流 ID 是否有效,或工作流类型是否需要 --flow / --body 等参数。`
|
||||
: "";
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `未指定测试单号 (--flow=<单号>),且拉取候选单据失败: ${err.message || String(err)}\n`,
|
||||
stderr: `未指定测试单号 (--flow=<单号>),且拉取候选单据失败: ${errMsg}${notFoundHint}\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
@@ -489,6 +508,13 @@ export async function handleWorkflowTest(
|
||||
outLines.push(...formatCodeNodeSummariesCard(codeSummaries, report.jobId));
|
||||
}
|
||||
|
||||
if (category === "WEBHOOK" && report.outcome !== "completed") {
|
||||
outLines.push("");
|
||||
outLines.push("💡 [Webhook 流程调试提示]");
|
||||
outLines.push(" 工作流首节点为 Webhook 触发器。若需向合思云端发起真实的 Webhook 事件调度流转,可直接运行:");
|
||||
outLines.push(` hose-use workflow webhook send ${pipelineId}${flowCodeOrId ? ` --bill=${flowCodeOrId}` : ""} --yes`);
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: `${outLines.join("\n")}\n`,
|
||||
stderr: "",
|
||||
|
||||
+86
-4
@@ -3,6 +3,72 @@ import { usageError } from "./errors.js";
|
||||
export type { HelpTopic } from "./command-metadata.js";
|
||||
export const HELP_REGISTRY = COMMAND_METADATA;
|
||||
|
||||
interface SubActionHelp {
|
||||
summary: string;
|
||||
usage: string;
|
||||
options: string[];
|
||||
}
|
||||
|
||||
const SUB_ACTION_HELP: Record<string, SubActionHelp> = {
|
||||
"workflow:node:add": {
|
||||
summary: "向工作流声明式追加任务节点",
|
||||
usage: "hose-use workflow node add <pipelineId> --type=<类型> [选项]",
|
||||
options: [
|
||||
"--type=<type> 节点类型 (如 task-dynamic-delay / code-js2 / http / stop / every)",
|
||||
"--sleep-time=<秒数> 延迟等待秒数 (针对 task-dynamic-delay,如 5)",
|
||||
"--set='key=value' 自定义节点属性注入 (如 --set='sleepTime=5')",
|
||||
"--after=<节点name> 插入在指定节点之后",
|
||||
"--parent=<容器节点name> 插入指定容器节点内部 (如 every 循环)",
|
||||
"--label=<标题> 节点类型标题",
|
||||
"--display-name=<名称> 设计器节点标题(最多 20 字符)",
|
||||
"--code-file=<脚本路径> 从本地文件导入代码 (推荐)",
|
||||
"--code=<代码片段> 传入代码字符串 (仅限简短代码)",
|
||||
"--dry-run 只预览追加变更,不实际写入",
|
||||
"--yes 确认追加新节点",
|
||||
],
|
||||
},
|
||||
"workflow:node:edit": {
|
||||
summary: "定向修改工作流任务节点配置",
|
||||
usage: "hose-use workflow node edit <pipelineId> <nodeNameOrIndex> [选项]",
|
||||
options: [
|
||||
"--sleep-time=<秒数> 更新延迟等待秒数 (针对 task-dynamic-delay,如 5)",
|
||||
"--set='key=value' 定向修改节点自定义属性 (如 --set='sleepTime=5')",
|
||||
"--display-name=<新名称> 更新设计器节点标题(displayName,最多 20 字符)",
|
||||
"--code-file=<脚本路径> 从本地文件导入最新脚本 (推荐)",
|
||||
"--code=<行内代码> 直接传入代码片段",
|
||||
"--desc=<描述> 更新节点描述",
|
||||
"--label=<类型标题> 更新节点类型标题",
|
||||
"--dry-run 只预览变更",
|
||||
"--yes 确认保存修改",
|
||||
],
|
||||
},
|
||||
"workflow:test": {
|
||||
summary: "端到端一键调试工作流(替代前端手工调测)",
|
||||
usage: "hose-use workflow test <pipelineId> [选项]",
|
||||
options: [
|
||||
"--flow=<单号> 测试单据编号 (flowCode 或 flowId)",
|
||||
"--body='{...}' 自定义测试请求体 (针对 Webhook 触发器)",
|
||||
"--sample=<1|2|3> 直接选用服务器最近接收的数据样本发起测试",
|
||||
"--timeout=<ms> 轮询超时时间 (毫秒,默认 15000)",
|
||||
"--auto-publish 调试通过后是否自动发布测试快照 (默认 false)",
|
||||
"--force, -f 生产环境安全放行 (正式企业 env: prod 调试必须加)",
|
||||
"--dry-run 只预览测试配置,不发起调用",
|
||||
"--yes/--confirm 确认执行真实调试",
|
||||
],
|
||||
},
|
||||
"workflow:webhook": {
|
||||
summary: "向工作流 Webhook 触发器发送测试数据 (别名: webhook-send)",
|
||||
usage: "hose-use workflow webhook [send] <pipelineId> [选项]",
|
||||
options: [
|
||||
"--bill=<单号|单据ID> 抓取真实单据数据作为测试载荷发送",
|
||||
"--body='{...}' 指定自定义 JSON 请求体",
|
||||
"--file=<path.json> 从 JSON 文件读取请求体",
|
||||
"--dry-run 仅预览目标 Webhook 地址与载荷,不实际发送",
|
||||
"--yes 确认发送网络请求",
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
export function renderScopedHelp(target: string[]): string {
|
||||
const resolved = resolveCommandMetadata(target[0]);
|
||||
if (!resolved) throw usageError(`未找到命令域帮助: ${target.join(" ") || "<empty>"}。运行 hose-use --help 查看全部命令域。`);
|
||||
@@ -10,10 +76,26 @@ export function renderScopedHelp(target: string[]): string {
|
||||
|
||||
const action = resolveCommandAction(area, target[1]);
|
||||
if (action && !Object.hasOwn(topic.commands, action)) throw usageError(`未找到子命令帮助: ${area} ${target[1]}`);
|
||||
const lines = [`${area} - ${topic.summary}`, "", `用法: ${topic.usage}`, "", "子命令:"];
|
||||
if (action && topic.commands[action]) lines.push(` ${action.padEnd(14)} ${topic.commands[action]}`);
|
||||
else for (const [name, description] of Object.entries(topic.commands)) lines.push(` ${name.padEnd(14)} ${description}`);
|
||||
if (topic.options?.length) lines.push("", "常用选项:", ...topic.options.map((option) => ` ${option}`));
|
||||
|
||||
const subTarget = target[2]?.toLowerCase();
|
||||
const subKey = subTarget ? `${area}:${action}:${subTarget}` : `${area}:${action}`;
|
||||
const subHelp = SUB_ACTION_HELP[subKey] || SUB_ACTION_HELP[`${area}:${action}`];
|
||||
|
||||
const titlePrefix = subHelp ? `${area} ${action}${subTarget ? ` ${subTarget}` : ""}` : area;
|
||||
const summaryText = subHelp?.summary || topic.summary;
|
||||
const usageText = subHelp?.usage || topic.usage;
|
||||
const commonOpts = subHelp?.options || topic.options;
|
||||
|
||||
const lines = [`${titlePrefix} - ${summaryText}`, "", `用法: ${usageText}`, "", "子命令:"];
|
||||
if (subHelp) {
|
||||
lines.push(` ${action}${subTarget ? ` ${subTarget}` : ""}`.padEnd(16) + ` ${subHelp.summary}`);
|
||||
} else if (action && topic.commands[action]) {
|
||||
lines.push(` ${action.padEnd(14)} ${topic.commands[action]}`);
|
||||
} else {
|
||||
for (const [name, description] of Object.entries(topic.commands)) lines.push(` ${name.padEnd(14)} ${description}`);
|
||||
}
|
||||
|
||||
if (commonOpts?.length) lines.push("", "常用选项:", ...commonOpts.map((option) => ` ${option}`));
|
||||
lines.push("", "支持选项:", ...Object.entries(commandFlags(area, action)).map(([key, kind]) => ` --${key}${kind === "value" ? "=<值>" : kind === "boolean-or-value" ? "[=<值>]" : ""}`));
|
||||
lines.push("", "提示: 追加 --json 获取机器可解析结果;写操作先用 --dry-run,再用 --yes 或 --confirm 执行。", "更多: hose-use --help");
|
||||
return lines.join("\n");
|
||||
|
||||
+4
-2
@@ -93,9 +93,11 @@ function isVersionRequested(parsed: CliParsedArgs): boolean {
|
||||
|
||||
function resolveHelpTarget(parsed: CliParsedArgs): string[] {
|
||||
if (["help", "h", "?"].includes((parsed.area || "").toLowerCase())) {
|
||||
return [parsed.action, parsed.args[0]].filter((value): value is string => Boolean(value));
|
||||
return [parsed.action, parsed.args[0], parsed.args[1]].filter((value): value is string => Boolean(value));
|
||||
}
|
||||
return [parsed.area, parsed.action === "help" ? parsed.args[0] : parsed.action].filter((value): value is string => Boolean(value));
|
||||
const primaryAction = parsed.action === "help" ? parsed.args[0] : parsed.action;
|
||||
const subAction = parsed.action === "help" ? parsed.args[1] : parsed.args[0];
|
||||
return [parsed.area, primaryAction, subAction].filter((value): value is string => Boolean(value));
|
||||
}
|
||||
|
||||
async function dispatchCli(rawArgs: string[], options: CliRunOptions = {}): Promise<CliResult> {
|
||||
|
||||
Reference in new issue
Block a user