Files
hose-use/src/cli/commands/workflow/webhook.ts
T
gitea 7af7e7db35 refactor: 整理工作流触发器并校验节点写入版本
集中触发器分类及 Webhook 规则,节点写入前检查远端版本并保留部分保存语义。
2026-10-30 17:38:28 +08:00

220 lines
7.2 KiB
TypeScript

import { existsSync, readFileSync } from "node:fs";
import ky from "ky";
import { getWorkflowDetail, webhookTriggerUrl } from "../../../domains/platform/workflow/services.js";
import { getBillByCodeOrId } from "../../../domains/bill/tools.js";
import { stringOption } from "../../parser.js";
import { printJson, printKeyValue } from "../../printer.js";
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../../mutation.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
import { createWorkflowDetailClient } from "./shared.js";
export async function handleWebhookCommand(
parsed: CliParsedArgs,
runtime: CliRuntime
): Promise<CliResult> {
const firstArg = parsed.args[0]?.toLowerCase();
const isActionVerb = firstArg === "send" || firstArg === "trigger" || firstArg === "post";
const pipelineId =
(isActionVerb ? parsed.args[1] : parsed.args[0]) ||
stringOption(parsed.options, ["id", "pipelineId", "source"]);
if (!pipelineId) {
return {
stdout: "",
stderr: [
"用法: hose-use workflow webhook [send] <pipelineId> [选项]",
"",
"说明:",
" 向工作流的 Webhook 触发器地址发送测试数据,生成新的数据样本。",
" 可彻底解决 Web 控制台复制或新建工作流后【获取更多数据样本】收不到事件的问题。",
"",
"选项:",
" --body='{...}' 指定自定义 JSON 请求体",
" --file=<path.json> 从 JSON 文件读取请求体",
" --bill=<单号|单据ID> 抓取真实单据数据作为测试载荷发送",
" --dry-run 仅预览目标 Webhook 地址与载荷,不实际发送",
" --yes 确认发送网络请求",
"",
"示例:",
" hose-use workflow webhook send 881196955148578838 --bill=spWC2AmbRbovsQ --yes",
" hose-use workflow webhook 881196955148578838 --body='{\"event\":\"test\"}' --yes",
].join("\n") + "\n",
exitCode: 1,
};
}
const { client, clients } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
const detail = await getWorkflowDetail(client, pipelineId);
const triggerNode =
detail.tasks?.find(
(t) => t.type === "webhook" || t.type === "datalink-button-trigger"
) || detail.tasks?.[0];
const triggerType = triggerNode?.type || "unknown";
if (triggerType !== "webhook" && triggerType !== "datalink-button-trigger") {
return {
stdout: "",
stderr: `❌ 工作流 [${detail.label || pipelineId}] 的首节点不是 Webhook 触发器 (当前类型: ${triggerType})。\n该命令仅适用于以 Webhook 或外部事件为触发源的工作流。\n`,
exitCode: 1,
};
}
const webhookUrl = triggerNode && webhookTriggerUrl(triggerNode);
if (!webhookUrl) {
return {
stdout: "",
stderr: `❌ 未能在 Webhook 触发器节点 [${triggerNode?.name || "-"}] 中找到有效的调用路径 (urlPath)。\n`,
exitCode: 1,
};
}
let payload: Record<string, unknown> = {};
const rawBody = stringOption(parsed.options, ["body", "data", "payload"]);
const filePath = stringOption(parsed.options, ["file", "path"]);
const billId = stringOption(parsed.options, ["bill", "flow", "code"]);
if (billId) {
const corpId = runtime.selectedCorp!.corpId || runtime.selectedCorp!.id;
try {
const bills = await getBillByCodeOrId(clients.ekbClient, corpId, billId);
if (!bills.length) {
return {
stdout: "",
stderr: `❌ 未找到单号/ID 为 [${billId}] 的单据\n`,
exitCode: 1,
};
}
const bill = bills[0];
payload = {
event: "flow.submit",
action: "flow.submit",
flowId: bill.billId,
code: bill.billCode,
title: bill.title,
data: bill,
mockTimestamp: Date.now(),
};
} catch (err: unknown) {
return {
stdout: "",
stderr: `❌ 抓取单据 [${billId}] 失败: ${err instanceof Error ? err.message : String(err)}\n`,
exitCode: 1,
};
}
} else if (rawBody) {
try {
payload = JSON.parse(rawBody);
} catch (e: unknown) {
return {
stdout: "",
stderr: `❌ --body 参数不是合法的 JSON 格式: ${e instanceof Error ? e.message : String(e)}\n`,
exitCode: 1,
};
}
} else if (filePath) {
if (!existsSync(filePath)) {
return {
stdout: "",
stderr: `❌ 指定的 Payload 文件不存在: ${filePath}\n`,
exitCode: 1,
};
}
try {
payload = JSON.parse(readFileSync(filePath, "utf-8"));
} catch (e: unknown) {
return {
stdout: "",
stderr: `❌ 读取并解析文件 [${filePath}] 失败: ${e instanceof Error ? e.message : String(e)}\n`,
exitCode: 1,
};
}
} else {
payload = {
event: "manual_sample_test",
pipelineId,
triggerType,
timestamp: Date.now(),
message: "Sample event injected via hose-use workflow webhook send",
};
}
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "发送 Webhook 测试事件", pipelineId, {
pipelineId,
pipelineName: detail.label,
targetUrl: webhookUrl,
payload,
});
}
requireMutationConfirmation(
parsed,
runtime,
"发送 Webhook 测试事件",
`hose-use workflow webhook send ${pipelineId}${billId ? ` --bill=${billId}` : ""} --yes`
);
let responseText = "";
let responseStatus = 200;
try {
const res = await ky.post(webhookUrl, {
json: payload,
timeout: 15000,
throwHttpErrors: false,
});
responseStatus = res.status;
responseText = await res.text();
} catch (err: unknown) {
return {
stdout: "",
stderr: `❌ 发送 Webhook 请求失败: ${err instanceof Error ? err.message : String(err)}\n`,
exitCode: 1,
};
}
const isSuccess = responseStatus >= 200 && responseStatus < 300;
const resultData = {
pipelineId,
pipelineName: detail.label,
webhookUrl,
statusCode: responseStatus,
payloadSize: JSON.stringify(payload).length,
response: responseText,
success: isSuccess,
};
if (runtime.jsonMode) {
return {
stdout: printJson(resultData, runtime.outputOptions),
stderr: "",
exitCode: isSuccess ? 0 : 2,
};
}
const out = [
isSuccess ? "✅ Webhook 测试样本已成功发送!" : "⚠️ Webhook 请求已发送但服务端返回非 2xx 状态码:",
printKeyValue({
"工作流 ID": pipelineId,
"工作流名称": detail.label,
"Webhook 目标地址": webhookUrl,
"HTTP 状态码": String(responseStatus),
"载荷字节大小": `${resultData.payloadSize} bytes`,
}),
"",
"服务端响应体:",
responseText || "(空响应体)",
"",
"下一步操作建议:",
" 1. Web 控制台: 在工作流首节点触发器中点击【获取更多数据样本】,直接选取刚刚注入的样本;",
` 2. 命令行调试: 执行 hose-use workflow test ${pipelineId} --sample=1 进行沙箱运行。`,
].join("\n");
return {
stdout: `${out}\n`,
stderr: "",
exitCode: isSuccess ? 0 : 2,
};
}