- copyWorkflow 的 label 二次保存改走完整 updateWorkflow 包装 - 自动携带 platformId/inputs 并调用 chooses,避免复制场景描述被重置 - 重新生成 dist/mcp/server.js
1085 lines
34 KiB
TypeScript
1085 lines
34 KiB
TypeScript
import { KyInstance } from "ky";
|
|
import { CorpConfig } from "../../core/config/types.js";
|
|
import * as api from "./api.js";
|
|
import { PermissionError, ValidationError } from "../../core/errors.js";
|
|
import { explainConditionBranches } from "./workflow/branch/index.js";
|
|
import { indexExecutionContexts } from "./execution-context.js";
|
|
import {
|
|
Platform,
|
|
WorkflowSummary,
|
|
WorkflowListAllError,
|
|
WorkflowTask,
|
|
WorkflowTaskExecution,
|
|
WorkflowWithMatches,
|
|
TaskMatch,
|
|
WorkflowSnapshot,
|
|
WorkflowSnapshotDiff,
|
|
TaskConfigDiff,
|
|
WorkflowJobDetail,
|
|
WorkflowJobDiff,
|
|
NodeExecutionDiff,
|
|
} from "./types.js";
|
|
|
|
export interface PlatformClients {
|
|
corp: CorpConfig;
|
|
ekbClient: KyInstance;
|
|
easoClient: KyInstance;
|
|
}
|
|
|
|
export function listPlatforms(...args: Parameters<typeof api.listPlatforms>) {
|
|
return api.listPlatforms(...args);
|
|
}
|
|
|
|
export function listWorkflows(...args: Parameters<typeof api.listWorkflows>) {
|
|
return api.listWorkflows(...args);
|
|
}
|
|
|
|
export function getWorkflowStats(...args: Parameters<typeof api.getWorkflowStats>) {
|
|
return api.getWorkflowStats(...args);
|
|
}
|
|
|
|
export function getWorkflowCharge(...args: Parameters<typeof api.getWorkflowCharge>) {
|
|
return api.getWorkflowCharge(...args);
|
|
}
|
|
|
|
export function getWorkflowDetail(...args: Parameters<typeof api.getWorkflowDetail>) {
|
|
return api.getWorkflowDetail(...args);
|
|
}
|
|
|
|
export function sanitizeWorkflowSnapshot(
|
|
detail: import("./types.js").WorkflowDetail
|
|
): import("./types.js").WorkflowDetail {
|
|
const cloned = JSON.parse(JSON.stringify(detail)) as import("./types.js").WorkflowDetail;
|
|
if (Array.isArray(cloned.$snapshot)) {
|
|
cloned.$snapshot = cloned.$snapshot.map((entry) => {
|
|
if (typeof entry.value === "string" && entry.value.includes("docs.ekuaibao.com")) {
|
|
return {
|
|
...entry,
|
|
value: entry.value.replaceAll("docs.ekuaibao.com", "app.ekuaibao.com"),
|
|
};
|
|
}
|
|
return entry;
|
|
});
|
|
}
|
|
return cloned;
|
|
}
|
|
|
|
export async function updateWorkflow(
|
|
client: KyInstance,
|
|
workflow: import("./types.js").WorkflowDetail,
|
|
platformId?: string
|
|
) {
|
|
// 前端保存时会带上触发输入 $platformId;缺少它会导致平台把内置节点 desc 重置为「」。
|
|
const payload: import("./types.js").WorkflowDetail = platformId && !workflow.inputs?.length
|
|
? { ...workflow, inputs: [{ key: "$platformId", value: platformId }] }
|
|
: workflow;
|
|
const sanitized = sanitizeWorkflowSnapshot(payload);
|
|
const updated = await api.updateWorkflow(client, sanitized);
|
|
// 复刻前端“保存更新”:主线 PUT 之后刷新 chooses。
|
|
await api.updateWorkflowChooses(client, updated.id || workflow.id);
|
|
return updated;
|
|
}
|
|
|
|
export async function copyWorkflow(
|
|
client: import("ky").KyInstance,
|
|
pipelineId: string,
|
|
options: { label?: string; platformId?: string } = {}
|
|
): Promise<import("./types.js").WorkflowDetail> {
|
|
const detail = await api.getWorkflowDetail(client, pipelineId);
|
|
const cloned = JSON.parse(JSON.stringify(detail)) as import("./types.js").WorkflowDetail;
|
|
if (options.label) {
|
|
cloned.label = options.label;
|
|
} else if (!cloned.label.includes("副本")) {
|
|
cloned.label = `${cloned.label} 副本`;
|
|
}
|
|
if (options.platformId) {
|
|
cloned.platformId = options.platformId;
|
|
}
|
|
// 如果首节点是 Webhook,重新分配独立唯一的 urlPath,并清理历史脏样本
|
|
if (cloned.tasks?.[0]?.type === "webhook") {
|
|
(cloned.tasks[0] as any).urlPath = crypto.randomUUID();
|
|
delete (cloned.tasks[0] as any).sampleId;
|
|
}
|
|
const result = await api.copyWorkflow(client, pipelineId, cloned);
|
|
if (options.label && result.label !== options.label) {
|
|
result.label = options.label;
|
|
return updateWorkflow(client, result, options.platformId ?? (result as any).platformId);
|
|
}
|
|
return result;
|
|
}
|
|
|
|
export interface CreateWorkflowOptions {
|
|
label?: string;
|
|
platformId?: string;
|
|
trigger?: "webhook" | "clock" | "flowform" | "datalink" | "none" | string;
|
|
file?: string;
|
|
workflow?: Record<string, any>;
|
|
state?: number;
|
|
desc?: string;
|
|
}
|
|
|
|
export function buildInitialTriggerTask(triggerType: string): WorkflowTask {
|
|
const norm = triggerType.toLowerCase().trim();
|
|
switch (norm) {
|
|
case "webhook":
|
|
return {
|
|
name: "trigger_webhook",
|
|
type: "webhook",
|
|
label: "Webhook触发",
|
|
groupName: "trigger",
|
|
orderIndex: 0,
|
|
levelIndex: [0],
|
|
status: "active",
|
|
urlPath: crypto.randomUUID(),
|
|
params: [],
|
|
};
|
|
case "clock":
|
|
case "schedule":
|
|
case "timer":
|
|
return {
|
|
name: "trigger_clock",
|
|
type: "clock",
|
|
label: "定时触发",
|
|
groupName: "trigger",
|
|
orderIndex: 0,
|
|
levelIndex: [0],
|
|
status: "active",
|
|
cron: "0 0 * * *",
|
|
timeZone: "Asia/Shanghai",
|
|
};
|
|
case "datalink":
|
|
case "data-link":
|
|
case "entity":
|
|
return {
|
|
name: "trigger_datalink_create",
|
|
type: "ekuaibao-datalink-create-trigger",
|
|
label: "业务对象新增时触发",
|
|
groupName: "trigger",
|
|
orderIndex: 0,
|
|
levelIndex: [0],
|
|
status: "active",
|
|
};
|
|
case "flowform":
|
|
case "flow":
|
|
case "bill":
|
|
return {
|
|
name: "trigger_flowform",
|
|
type: "ekuaibao-flowform-trigger",
|
|
label: "单据审批事件触发",
|
|
groupName: "trigger",
|
|
orderIndex: 0,
|
|
levelIndex: [0],
|
|
status: "active",
|
|
};
|
|
default:
|
|
return {
|
|
name: `trigger_${norm.replace(/-/g, "_")}`,
|
|
type: norm,
|
|
label: `${norm}触发`,
|
|
groupName: "trigger",
|
|
orderIndex: 0,
|
|
levelIndex: [0],
|
|
status: "active",
|
|
};
|
|
}
|
|
}
|
|
|
|
export async function createWorkflow(
|
|
client: import("ky").KyInstance,
|
|
options: CreateWorkflowOptions = {}
|
|
): Promise<import("./types.js").WorkflowDetail> {
|
|
let base: Record<string, any> = {};
|
|
if (options.file) {
|
|
const fs = await import("fs/promises");
|
|
const raw = await fs.readFile(options.file, "utf-8");
|
|
base = JSON.parse(raw);
|
|
} else if (options.workflow) {
|
|
base = JSON.parse(JSON.stringify(options.workflow));
|
|
}
|
|
|
|
const payload: Record<string, any> = {
|
|
...base,
|
|
label: options.label || base.label || "未命名流程",
|
|
state: options.state ?? 0, // 强制初始状态为草稿未启用 (0),防御合思服务端默认 state=1 与模板继承
|
|
};
|
|
|
|
if (options.platformId || base.platformId) {
|
|
payload.platformId = options.platformId || base.platformId;
|
|
}
|
|
if (options.desc || base.desc) {
|
|
payload.desc = options.desc || base.desc;
|
|
}
|
|
|
|
// 触发器节点初始化
|
|
if (!payload.tasks || payload.tasks.length === 0) {
|
|
if (options.trigger && options.trigger !== "none" && options.trigger !== "empty") {
|
|
payload.tasks = [buildInitialTriggerTask(options.trigger)];
|
|
} else {
|
|
payload.tasks = [];
|
|
}
|
|
} else if (payload.tasks[0]?.type === "webhook") {
|
|
if (!payload.tasks[0].urlPath) {
|
|
payload.tasks[0].urlPath = crypto.randomUUID();
|
|
}
|
|
}
|
|
|
|
return api.createWorkflow(client, payload);
|
|
}
|
|
|
|
export function deleteWorkflow(...args: Parameters<typeof api.deleteWorkflow>) {
|
|
return api.deleteWorkflow(...args);
|
|
}
|
|
|
|
export function listWorkflowSnapshots(...args: Parameters<typeof api.listWorkflowSnapshots>) {
|
|
return api.listWorkflowSnapshots(...args);
|
|
}
|
|
|
|
export function getWorkflowSnapshot(...args: Parameters<typeof api.getWorkflowSnapshot>) {
|
|
return api.getWorkflowSnapshot(...args);
|
|
}
|
|
|
|
export function listWorkflowLogs(...args: Parameters<typeof api.listWorkflowLogs>) {
|
|
return api.listWorkflowLogs(...args);
|
|
}
|
|
|
|
export function toggleWorkflow(...args: Parameters<typeof api.toggleWorkflow>) {
|
|
return api.toggleWorkflow(...args);
|
|
}
|
|
|
|
export function listRunningJobs(...args: Parameters<typeof api.listRunningJobs>) {
|
|
return api.listRunningJobs(...args);
|
|
}
|
|
|
|
export function getJob(...args: Parameters<typeof api.getJob>) {
|
|
return api.getJob(...args);
|
|
}
|
|
|
|
export function getJobExecutionTree(...args: Parameters<typeof api.getJobExecutionTree>) {
|
|
return api.getJobExecutionTree(...args);
|
|
}
|
|
|
|
export function getJobFailedExecutions(...args: Parameters<typeof api.getJobFailedExecutions>) {
|
|
return api.getJobFailedExecutions(...args);
|
|
}
|
|
|
|
export function getJobExecutionLevel(...args: Parameters<typeof api.getJobExecutionLevel>) {
|
|
return api.getJobExecutionLevel(...args);
|
|
}
|
|
|
|
export function getExecutionLogs(...args: Parameters<typeof api.getExecutionLogs>) {
|
|
return api.getExecutionLogs(...args);
|
|
}
|
|
|
|
export function listDsl(...args: Parameters<typeof api.listDsl>) {
|
|
return api.listDsl(...args);
|
|
}
|
|
|
|
export function listStaffs(...args: Parameters<typeof api.listStaffs>) {
|
|
return api.listStaffs(...args);
|
|
}
|
|
|
|
export function getWebhookInfo(...args: Parameters<typeof api.getWebhookInfo>) {
|
|
return api.getWebhookInfo(...args);
|
|
}
|
|
|
|
export function sampleWorkflowData(...args: Parameters<typeof api.sampleWorkflowData>) {
|
|
return api.sampleWorkflowData(...args);
|
|
}
|
|
|
|
// ── 服务层:跨应用聚合 ───────────────────────────────────────────────────────
|
|
|
|
export interface ListAllWorkflowsOptions {
|
|
page?: number;
|
|
pageSize?: number;
|
|
}
|
|
|
|
export interface ListAllWorkflowsResult {
|
|
workflows: WorkflowSummary[];
|
|
errors: WorkflowListAllError[];
|
|
}
|
|
|
|
export async function listAllWorkflows(
|
|
clients: PlatformClients,
|
|
options: ListAllWorkflowsOptions = {}
|
|
): Promise<ListAllWorkflowsResult> {
|
|
const { ekbClient, easoClient, corp } = clients;
|
|
const page = options.page ?? 1;
|
|
const pageSize = options.pageSize ?? 20;
|
|
|
|
const platforms = await api.listPlatforms(ekbClient, corp.credentials.corpId);
|
|
const enabledPlatforms = platforms.filter((p) => p.active !== false);
|
|
|
|
const workflows: WorkflowSummary[] = [];
|
|
const errors: WorkflowListAllError[] = [];
|
|
|
|
await Promise.all(
|
|
enabledPlatforms.map(async (platform) => {
|
|
try {
|
|
const pageResult = await api.listWorkflows(
|
|
easoClient,
|
|
platform.id,
|
|
page,
|
|
pageSize
|
|
);
|
|
for (const workflow of pageResult.pipelineList) {
|
|
workflows.push({
|
|
...workflow,
|
|
platformId: platform.id,
|
|
platformName: platform.name,
|
|
});
|
|
}
|
|
} catch (err) {
|
|
errors.push({
|
|
platformId: platform.id,
|
|
platformName: platform.name,
|
|
error: err instanceof Error ? err.message : String(err),
|
|
});
|
|
}
|
|
})
|
|
);
|
|
|
|
return { workflows, errors };
|
|
}
|
|
|
|
function collectTasksByType(
|
|
tasks: WorkflowTask[],
|
|
taskType: string,
|
|
matches: TaskMatch[] = []
|
|
): TaskMatch[] {
|
|
for (const task of tasks) {
|
|
if (task.type === taskType) {
|
|
matches.push({
|
|
taskName: task.name,
|
|
taskType: task.type,
|
|
levelIndex: task.levelIndex,
|
|
});
|
|
}
|
|
if ("tasks" in task && Array.isArray(task.tasks)) {
|
|
collectTasksByType(task.tasks as WorkflowTask[], taskType, matches);
|
|
}
|
|
}
|
|
return matches;
|
|
}
|
|
|
|
export interface FindWorkflowsByTaskTypeOptions extends ListAllWorkflowsOptions {
|
|
includeDetail?: boolean;
|
|
}
|
|
|
|
export interface FindWorkflowsByTaskTypeResult {
|
|
workflows: WorkflowWithMatches[];
|
|
errors: WorkflowListAllError[];
|
|
}
|
|
|
|
export async function findWorkflowsByTaskType(
|
|
clients: PlatformClients,
|
|
taskType: string,
|
|
options: FindWorkflowsByTaskTypeOptions = {}
|
|
): Promise<FindWorkflowsByTaskTypeResult> {
|
|
const { easoClient } = clients;
|
|
const { includeDetail, ...listOptions } = options;
|
|
|
|
const all = await listAllWorkflows(clients, listOptions);
|
|
const matched: WorkflowWithMatches[] = [];
|
|
const detailErrors: WorkflowListAllError[] = [];
|
|
|
|
for (const workflow of all.workflows) {
|
|
let tasks = workflow.tasks;
|
|
|
|
if (includeDetail) {
|
|
try {
|
|
const detail = await api.getWorkflowDetail(easoClient, workflow.id);
|
|
tasks = detail.tasks;
|
|
} catch (err) {
|
|
detailErrors.push({
|
|
platformId: workflow.platformId,
|
|
platformName: workflow.platformName,
|
|
error: err instanceof Error ? err.message : String(err),
|
|
});
|
|
continue;
|
|
}
|
|
}
|
|
|
|
const matchedTasks = collectTasksByType(tasks, taskType);
|
|
if (matchedTasks.length > 0) {
|
|
matched.push({ ...workflow, matchedTasks });
|
|
}
|
|
}
|
|
|
|
return { workflows: matched, errors: [...all.errors, ...detailErrors] };
|
|
}
|
|
|
|
/**
|
|
* 递归扁平化执行树节点(展开 children / tasks / items 等嵌套数组)
|
|
*/
|
|
export function flattenExecutionTree(nodes: WorkflowTaskExecution[]): WorkflowTaskExecution[] {
|
|
const result: WorkflowTaskExecution[] = [];
|
|
|
|
function visit(node: any) {
|
|
if (!node || typeof node !== "object") return;
|
|
result.push(node as WorkflowTaskExecution);
|
|
|
|
const children = node.children || node.tasks || node.subTasks || node.items;
|
|
if (Array.isArray(children)) {
|
|
for (const child of children) {
|
|
visit(child);
|
|
}
|
|
}
|
|
}
|
|
|
|
for (const node of nodes) {
|
|
visit(node);
|
|
}
|
|
|
|
return result;
|
|
}
|
|
|
|
/**
|
|
* 精准判定某个节点是否执行异常或报错
|
|
*/
|
|
export function isTaskExecutionFailed(node: WorkflowTaskExecution): boolean {
|
|
if (!node) return false;
|
|
const anyNode = node as any;
|
|
|
|
if (node.error?.message || anyNode.errorMessage) return true;
|
|
if (node.status === "FAILED" || anyNode.state === "FAILED" || anyNode.state === 2) return true;
|
|
if (typeof anyNode.errorTaskCount === "number" && anyNode.errorTaskCount > 0) return true;
|
|
if (anyNode.outputs && typeof anyNode.outputs === "object" && anyNode.outputs.error) return true;
|
|
if (anyNode.output && typeof anyNode.output === "object" && anyNode.output.error) return true;
|
|
|
|
return false;
|
|
}
|
|
|
|
/**
|
|
* 提取并去重执行树中的全部异常失败节点
|
|
*/
|
|
export function extractFailureExecutions(
|
|
tree: WorkflowTaskExecution[],
|
|
failedItems: WorkflowTaskExecution[] = []
|
|
): WorkflowTaskExecution[] {
|
|
const flattened = flattenExecutionTree(tree);
|
|
const map = new Map<string, WorkflowTaskExecution>();
|
|
|
|
for (const item of failedItems) {
|
|
if (item?.id) {
|
|
map.set(item.id, item);
|
|
}
|
|
}
|
|
|
|
for (const node of flattened) {
|
|
if (node?.id && isTaskExecutionFailed(node)) {
|
|
const existing = map.get(node.id);
|
|
if (!existing) {
|
|
map.set(node.id, node);
|
|
} else {
|
|
map.set(node.id, {
|
|
...node,
|
|
...existing,
|
|
error: existing.error ?? node.error,
|
|
inputs: existing.inputs ?? (node as any).inputs,
|
|
outputs: existing.outputs ?? (node as any).outputs,
|
|
});
|
|
}
|
|
}
|
|
}
|
|
|
|
return Array.from(map.values());
|
|
}
|
|
|
|
/**
|
|
* 按 ID、name、displayName 或 label 查找节点
|
|
*/
|
|
export function findExecutionNode(
|
|
tree: WorkflowTaskExecution[],
|
|
query: string
|
|
): WorkflowTaskExecution | undefined {
|
|
const flattened = flattenExecutionTree(tree);
|
|
const q = query.trim().toLowerCase();
|
|
if (!q) return undefined;
|
|
|
|
// 1. 精确匹配 ID 或 name
|
|
const exact = flattened.find(
|
|
(n) =>
|
|
n.id?.toLowerCase() === q ||
|
|
n.name?.toLowerCase() === q ||
|
|
n.displayName?.toLowerCase() === q
|
|
);
|
|
if (exact) return exact;
|
|
|
|
// 2. 包含匹配 name、label、displayName
|
|
return flattened.find(
|
|
(n) =>
|
|
n.name?.toLowerCase().includes(q) ||
|
|
n.label?.toLowerCase().includes(q) ||
|
|
n.displayName?.toLowerCase().includes(q)
|
|
);
|
|
}
|
|
|
|
// ── 工作流快照与 Job 差异比对核心算法 ──────────────────────────────────────────
|
|
|
|
/**
|
|
* 递归展开工作流配置节点(包括 condition 与 every 内嵌的子节点)
|
|
*/
|
|
export function flattenWorkflowTasks(tasks?: WorkflowTask[] | null): WorkflowTask[] {
|
|
if (!tasks || !Array.isArray(tasks)) return [];
|
|
const result: WorkflowTask[] = [];
|
|
|
|
function walk(list: WorkflowTask[]) {
|
|
for (const t of list) {
|
|
if (!t) continue;
|
|
result.push(t);
|
|
if (Array.isArray(t.tasks) && t.tasks.length > 0) {
|
|
walk(t.tasks);
|
|
}
|
|
}
|
|
}
|
|
|
|
walk(tasks);
|
|
return result;
|
|
}
|
|
|
|
/**
|
|
* 快速生成标准 Unified Diff 文本
|
|
*/
|
|
export function generateTextDiff(a: string, b: string, labelA = "from", labelB = "to"): string {
|
|
if (a === b) return "";
|
|
const linesA = a.split(/\r?\n/);
|
|
const linesB = b.split(/\r?\n/);
|
|
const output: string[] = [`--- ${labelA}`, `+++ ${labelB}`];
|
|
|
|
let start = 0;
|
|
while (start < linesA.length && start < linesB.length && linesA[start] === linesB[start]) {
|
|
start++;
|
|
}
|
|
let endA = linesA.length - 1;
|
|
let endB = linesB.length - 1;
|
|
while (endA >= start && endB >= start && linesA[endA] === linesB[endB]) {
|
|
endA--;
|
|
endB--;
|
|
}
|
|
|
|
const hunkStart = Math.max(0, start - 2);
|
|
const hunkEndA = Math.min(linesA.length, endA + 3);
|
|
const hunkEndB = Math.min(linesB.length, endB + 3);
|
|
|
|
output.push(`@@ -${hunkStart + 1},${hunkEndA - hunkStart} +${hunkStart + 1},${hunkEndB - hunkStart} @@`);
|
|
for (let i = hunkStart; i < start; i++) {
|
|
output.push(` ${linesA[i]}`);
|
|
}
|
|
for (let i = start; i <= endA; i++) {
|
|
output.push(`- ${linesA[i]}`);
|
|
}
|
|
for (let i = start; i <= endB; i++) {
|
|
output.push(`+ ${linesB[i]}`);
|
|
}
|
|
for (let i = endA + 1; i < hunkEndA; i++) {
|
|
output.push(` ${linesA[i]}`);
|
|
}
|
|
return output.join("\n");
|
|
}
|
|
|
|
/**
|
|
* 对比两个历史快照的节点、脚本代码(MVEL/JS)与参数配置差异
|
|
*/
|
|
export function diffWorkflowSnapshots(
|
|
snapshotA: WorkflowSnapshot,
|
|
snapshotB: WorkflowSnapshot
|
|
): WorkflowSnapshotDiff {
|
|
const tasksA = flattenWorkflowTasks(snapshotA.tasks);
|
|
const tasksB = flattenWorkflowTasks(snapshotB.tasks);
|
|
const indexPaths = (tasks: WorkflowTask[] = [], prefix = "tasks", paths = new Map<string, string>()): Map<string, string> => {
|
|
tasks.forEach((task, i) => {
|
|
const path = `${prefix}.${i}`;
|
|
if (task.name) paths.set(task.name, path);
|
|
if (task.tasks) indexPaths(task.tasks, `${path}.tasks`, paths);
|
|
});
|
|
return paths;
|
|
};
|
|
const pathsA = indexPaths(snapshotA.tasks || []);
|
|
const pathsB = indexPaths(snapshotB.tasks || []);
|
|
|
|
const mapA = new Map<string, WorkflowTask>();
|
|
for (const t of tasksA) {
|
|
if (t?.name) mapA.set(t.name, t);
|
|
}
|
|
|
|
const mapB = new Map<string, WorkflowTask>();
|
|
for (const t of tasksB) {
|
|
if (t?.name) mapB.set(t.name, t);
|
|
}
|
|
|
|
const addedTasks: string[] = [];
|
|
const removedTasks: string[] = [];
|
|
const modifiedTasks: TaskConfigDiff[] = [];
|
|
|
|
// 1. 查找新增节点
|
|
for (const [name, tB] of mapB) {
|
|
if (!mapA.has(name)) {
|
|
addedTasks.push(name);
|
|
modifiedTasks.push({
|
|
taskName: name,
|
|
displayName: tB.displayName || tB.label,
|
|
type: tB.type,
|
|
changeType: "ADDED",
|
|
configChanges: [],
|
|
});
|
|
}
|
|
}
|
|
|
|
// 2. 查找删除与修改节点
|
|
for (const [name, tA] of mapA) {
|
|
const tB = mapB.get(name);
|
|
if (!tB) {
|
|
removedTasks.push(name);
|
|
modifiedTasks.push({
|
|
taskName: name,
|
|
displayName: tA.displayName || tA.label,
|
|
type: tA.type,
|
|
changeType: "REMOVED",
|
|
configChanges: [],
|
|
});
|
|
continue;
|
|
}
|
|
|
|
// 两者均存在,深度比较配置与代码
|
|
const configChanges: Array<{ field: string; from?: unknown; to?: unknown }> = [];
|
|
let codeDiff: { from?: string; to?: string; unifiedDiff?: string } | undefined;
|
|
let filterDiff: { from?: unknown; to?: unknown } | undefined;
|
|
|
|
// 代码脚本比较
|
|
const codeA = typeof (tA as any).code === "string" ? (tA as any).code : undefined;
|
|
const codeB = typeof (tB as any).code === "string" ? (tB as any).code : undefined;
|
|
if (codeA !== codeB) {
|
|
codeDiff = {
|
|
from: codeA,
|
|
to: codeB,
|
|
unifiedDiff: generateTextDiff(
|
|
codeA || "",
|
|
codeB || "",
|
|
`${snapshotA.version || snapshotA.id}`,
|
|
`${snapshotB.version || snapshotB.id}`
|
|
),
|
|
};
|
|
}
|
|
|
|
// 过滤条件比较 (combineFilters / filters)
|
|
const filtersA = (tA as any).combineFilters ?? (tA as any).filters;
|
|
const filtersB = (tB as any).combineFilters ?? (tB as any).filters;
|
|
if (JSON.stringify(filtersA) !== JSON.stringify(filtersB)) {
|
|
filterDiff = { from: filtersA, to: filtersB };
|
|
}
|
|
|
|
// 关键字段变动比较
|
|
const checkFields = [...new Set([...Object.keys(tA), ...Object.keys(tB)])]
|
|
.filter(field => !["name", "tasks", "code", "combineFilters", "filters"].includes(field));
|
|
if (pathsA.get(name) !== pathsB.get(name)) {
|
|
configChanges.push({ field: "$path", from: pathsA.get(name), to: pathsB.get(name) });
|
|
}
|
|
for (const f of checkFields) {
|
|
const valA = (tA as any)[f];
|
|
const valB = (tB as any)[f];
|
|
if (JSON.stringify(valA) !== JSON.stringify(valB)) {
|
|
configChanges.push({ field: f, from: valA, to: valB });
|
|
}
|
|
}
|
|
|
|
if (codeDiff || filterDiff || configChanges.length > 0) {
|
|
modifiedTasks.push({
|
|
taskName: name,
|
|
displayName: tB.displayName || tB.label || tA.displayName || tA.label,
|
|
type: tB.type || tA.type,
|
|
changeType: "MODIFIED",
|
|
codeDiff,
|
|
filterDiff,
|
|
configChanges,
|
|
});
|
|
}
|
|
}
|
|
|
|
return {
|
|
snapshotA: {
|
|
id: snapshotA.id,
|
|
version: snapshotA.version,
|
|
updateTime: snapshotA.updateTime,
|
|
staffName: snapshotA.staffName || snapshotA.staffId || undefined,
|
|
},
|
|
snapshotB: {
|
|
id: snapshotB.id,
|
|
version: snapshotB.version,
|
|
updateTime: snapshotB.updateTime,
|
|
staffName: snapshotB.staffName || snapshotB.staffId || undefined,
|
|
},
|
|
addedTasks,
|
|
removedTasks,
|
|
modifiedTasks,
|
|
summary: {
|
|
totalA: tasksA.length,
|
|
totalB: tasksB.length,
|
|
changedCount: modifiedTasks.length,
|
|
},
|
|
};
|
|
}
|
|
|
|
/**
|
|
* 对比两个 Job 的执行分支、入参 Payload、下游输出及报错信息
|
|
*/
|
|
export function diffWorkflowJobs(
|
|
jobA: WorkflowJobDetail,
|
|
treeA: WorkflowTaskExecution[],
|
|
jobB: WorkflowJobDetail,
|
|
treeB: WorkflowTaskExecution[]
|
|
): WorkflowJobDiff {
|
|
const flatA = indexExecutionContexts(treeA);
|
|
const flatB = indexExecutionContexts(treeB);
|
|
const byKeyA = new Map(flatA.map(context => [context.key, context]));
|
|
const byKeyB = new Map(flatB.map(context => [context.key, context]));
|
|
const allKeys = new Set([...byKeyA.keys(), ...byKeyB.keys()]);
|
|
|
|
const nodes: NodeExecutionDiff[] = [];
|
|
let divergedNodesCount = 0;
|
|
let statusDiffCount = 0;
|
|
|
|
for (const key of allKeys) {
|
|
const contextA = byKeyA.get(key);
|
|
const contextB = byKeyB.get(key);
|
|
const nodeA = contextA?.node;
|
|
const nodeB = contextB?.node;
|
|
const name = nodeB?.name || nodeA?.name || nodeB?.type || nodeA?.type || "unnamed";
|
|
|
|
const statusA = nodeA?.status;
|
|
const statusB = nodeB?.status;
|
|
const isStatusDiff = statusA !== statusB;
|
|
if (isStatusDiff) statusDiffCount++;
|
|
|
|
// 比较 inputs
|
|
const inputsDiff: Array<{ field: string; from?: unknown; to?: unknown }> = [];
|
|
const payloadFields = (value: unknown): Record<string, unknown> => value === undefined ? {} : value !== null && typeof value === "object" ? value as Record<string, unknown> : { $value: value };
|
|
const inA = payloadFields(nodeA?.inputs);
|
|
const inB = payloadFields(nodeB?.inputs);
|
|
const inputKeys = Array.from(new Set([...Object.keys(inA), ...Object.keys(inB)]));
|
|
for (const k of inputKeys) {
|
|
if (JSON.stringify(inA[k]) !== JSON.stringify(inB[k])) {
|
|
inputsDiff.push({ field: k, from: inA[k], to: inB[k] });
|
|
}
|
|
}
|
|
|
|
// 比较 outputs
|
|
const outputsDiff: Array<{ field: string; from?: unknown; to?: unknown }> = [];
|
|
const outA = payloadFields(nodeA?.outputs ?? nodeA?.output);
|
|
const outB = payloadFields(nodeB?.outputs ?? nodeB?.output);
|
|
const outputKeys = Array.from(new Set([...Object.keys(outA), ...Object.keys(outB)]));
|
|
for (const k of outputKeys) {
|
|
if (JSON.stringify(outA[k]) !== JSON.stringify(outB[k])) {
|
|
outputsDiff.push({ field: k, from: outA[k], to: outB[k] });
|
|
}
|
|
}
|
|
|
|
const isDiverged =
|
|
!nodeA ||
|
|
!nodeB ||
|
|
isStatusDiff ||
|
|
JSON.stringify(nodeA.error) !== JSON.stringify(nodeB.error) ||
|
|
inputsDiff.length > 0 || outputsDiff.length > 0;
|
|
|
|
if (isDiverged) divergedNodesCount++;
|
|
|
|
nodes.push({
|
|
taskName: name,
|
|
instanceKey: key,
|
|
currentLoopPath: contextB?.loopPath || contextA?.loopPath || undefined,
|
|
displayName: (nodeB?.displayName || nodeA?.displayName || nodeB?.label || nodeA?.label) ?? undefined,
|
|
type: nodeB?.type || nodeA?.type,
|
|
statusA,
|
|
statusB,
|
|
durationMsA: nodeA?.executionTime,
|
|
durationMsB: nodeB?.executionTime,
|
|
errorA: nodeA?.error,
|
|
errorB: nodeB?.error,
|
|
inputsDiff,
|
|
outputsDiff,
|
|
diverged: isDiverged,
|
|
});
|
|
}
|
|
|
|
return {
|
|
jobA: {
|
|
id: jobA.id,
|
|
pipelineId: jobA.pipelineId,
|
|
state: typeof jobA.state === "string" || typeof jobA.state === "number" ? jobA.state : undefined,
|
|
startTime: jobA.startTime ? String(jobA.startTime) : undefined,
|
|
durationTime: typeof jobA.durationTime === "number" ? jobA.durationTime : undefined,
|
|
hasError: Boolean(jobA.hasError),
|
|
errorCount: typeof (jobA as any).errorTaskCount === "number" ? (jobA as any).errorTaskCount : undefined,
|
|
},
|
|
jobB: {
|
|
id: jobB.id,
|
|
pipelineId: jobB.pipelineId,
|
|
state: typeof jobB.state === "string" || typeof jobB.state === "number" ? jobB.state : undefined,
|
|
startTime: jobB.startTime ? String(jobB.startTime) : undefined,
|
|
durationTime: typeof jobB.durationTime === "number" ? jobB.durationTime : undefined,
|
|
hasError: Boolean(jobB.hasError),
|
|
errorCount: typeof (jobB as any).errorTaskCount === "number" ? (jobB as any).errorTaskCount : undefined,
|
|
},
|
|
nodes,
|
|
summary: {
|
|
totalNodesA: flatA.length,
|
|
totalNodesB: flatB.length,
|
|
divergedNodesCount,
|
|
statusDiffCount,
|
|
},
|
|
};
|
|
}
|
|
|
|
export function getWorkflowDebugSource(...args: Parameters<typeof api.getWorkflowDebugSource>) {
|
|
return api.getWorkflowDebugSource(...args);
|
|
}
|
|
|
|
export function triggerWorkflowDebug(...args: Parameters<typeof api.triggerWorkflowDebug>) {
|
|
return api.triggerWorkflowDebug(...args);
|
|
}
|
|
|
|
export async function runWorkflowDebugTest(
|
|
client: import("ky").KyInstance,
|
|
pipelineId: string,
|
|
options: {
|
|
flowCodeOrId?: string;
|
|
data?: Record<string, any>;
|
|
triggerCategory?: import("./types.js").WorkflowTriggerCategory;
|
|
triggerType?: string;
|
|
triggerLabel?: string;
|
|
autoPublish?: boolean;
|
|
timeoutMs?: number;
|
|
pollIntervalMs?: number;
|
|
} = {}
|
|
): Promise<import("./types.js").WorkflowTestReport> {
|
|
if (!Number.isFinite(options.timeoutMs ?? 15000) || (options.timeoutMs ?? 15000) < 0 || !Number.isFinite(options.pollIntervalMs ?? 500) || (options.pollIntervalMs ?? 500) <= 0) {
|
|
throw new ValidationError("timeoutMs 必须为非负数,pollIntervalMs 必须为正数");
|
|
}
|
|
let targetEntityId = options.flowCodeOrId ?? "";
|
|
const code = options.flowCodeOrId;
|
|
const isDirectCode = !code || code.includes("-") || code.startsWith("ID01");
|
|
if (code && !isDirectCode) {
|
|
try {
|
|
const source = await api.getWorkflowDebugSource(client, pipelineId, {
|
|
page: 1,
|
|
pageSize: 10,
|
|
keywords: code,
|
|
});
|
|
const matched = source.items.find(
|
|
(item) => item.id === code || (item as any).code === code || item.title?.includes(code) || (item as any).name?.includes(code)
|
|
);
|
|
if (matched) {
|
|
targetEntityId = matched.id;
|
|
}
|
|
} catch {
|
|
// 关键字搜索超时或失败时直接回退使用传入值
|
|
}
|
|
}
|
|
|
|
const jobId = await api.triggerWorkflowDebug(client, pipelineId, {
|
|
entityId: targetEntityId || undefined,
|
|
data: options.data,
|
|
autoPublish: options.autoPublish ?? false,
|
|
});
|
|
|
|
const timeoutMs = options.timeoutMs ?? 15000;
|
|
const pollIntervalMs = options.pollIntervalMs ?? 500;
|
|
const start = Date.now();
|
|
const diagnosticsErrors: Array<{ source: string; message: string }> = [];
|
|
const recordError = (source: string, error: unknown) => diagnosticsErrors.push({ source, message: error instanceof Error ? error.message : String(error) });
|
|
const terminal = new Set(["COMPLETED", "FAILED", "STOP", "STOPPED", "CANCELLED", "CANCELED"]);
|
|
const jobState = (job?: WorkflowJobDetail) => String(job?.status || job?.state || "UNKNOWN").toUpperCase();
|
|
let finalJob: WorkflowJobDetail | undefined;
|
|
let pollingFailed = false;
|
|
|
|
while (Date.now() - start < timeoutMs) {
|
|
try {
|
|
const job = await api.getJob(client, jobId);
|
|
finalJob = job;
|
|
if (terminal.has(jobState(job))) break;
|
|
} catch (error) {
|
|
// 任务刚创建可能存在短延时,继续轮询
|
|
const status = (error as { status?: number; response?: { status?: number } } | null)?.status
|
|
?? (error as { response?: { status?: number } } | null)?.response?.status;
|
|
if (status !== 404) {
|
|
recordError("job", error);
|
|
pollingFailed = true;
|
|
break;
|
|
}
|
|
}
|
|
await new Promise((resolve) => setTimeout(resolve, Math.min(pollIntervalMs, Math.max(0, timeoutMs - (Date.now() - start)))));
|
|
}
|
|
|
|
if (!finalJob && !pollingFailed) {
|
|
try { finalJob = await api.getJob(client, jobId); }
|
|
catch (error) { recordError("job", error); pollingFailed = true; }
|
|
}
|
|
const timedOut = !pollingFailed && !terminal.has(jobState(finalJob));
|
|
const [treeResult, failuresResult] = await Promise.allSettled([
|
|
api.getJobExecutionTree(client, jobId),
|
|
api.getJobFailedExecutions(client, jobId),
|
|
]);
|
|
const tree = treeResult.status === "fulfilled" ? treeResult.value : [];
|
|
const failedItems = failuresResult.status === "fulfilled" ? failuresResult.value.items : [];
|
|
if (treeResult.status === "rejected") recordError("executionTree", treeResult.reason);
|
|
if (failuresResult.status === "rejected") recordError("failedExecutions", failuresResult.reason);
|
|
|
|
const rawFailed = extractFailureExecutions(tree, failedItems);
|
|
const diagnosticsComplete = diagnosticsErrors.length === 0;
|
|
const status = jobState(finalJob);
|
|
const hasExecutionError = rawFailed.length > 0 || finalJob?.hasError === true || Number(finalJob?.errorTaskCount ?? 0) > 0;
|
|
let outcome: import("./types.js").WorkflowTestReport["outcome"] = "incomplete";
|
|
if (timedOut) outcome = "timed_out";
|
|
else if (terminal.has(status) && (status !== "COMPLETED" || hasExecutionError)) outcome = "failed";
|
|
else if (status === "COMPLETED" && diagnosticsComplete) outcome = "completed";
|
|
const conditionDiagnoses = explainConditionBranches(tree);
|
|
|
|
return {
|
|
jobId,
|
|
pipelineId,
|
|
status,
|
|
outcome,
|
|
timedOut,
|
|
diagnosticsComplete,
|
|
diagnosticsErrors,
|
|
runType: finalJob?.runType || "DEBUG",
|
|
durationTime: typeof finalJob?.durationTime === "number" ? finalJob.durationTime : undefined,
|
|
targetEntityId,
|
|
triggerCategory: options.triggerCategory,
|
|
triggerType: options.triggerType,
|
|
triggerLabel: options.triggerLabel,
|
|
executionTree: tree,
|
|
failedExecutions: rawFailed,
|
|
conditionDiagnoses,
|
|
};
|
|
}
|
|
|
|
export {
|
|
explainConditionBranches,
|
|
type ConditionBranchExplanation,
|
|
type ConditionRuleExplanation,
|
|
} from "./workflow/branch/index.js";
|
|
|
|
export {
|
|
classifyWorkflowTrigger,
|
|
type WorkflowTriggerCategory,
|
|
type WorkflowSampleRecord,
|
|
type WorkflowSampleDataResult,
|
|
} from "./types.js";
|
|
|
|
export async function getWorkflowSampleData(
|
|
client: import("ky").KyInstance,
|
|
pipelineId: string,
|
|
type = "webhook"
|
|
): Promise<import("./types.js").WorkflowSampleDataResult> {
|
|
return api.getWorkflowSampleData(client, pipelineId, type);
|
|
}
|
|
|
|
export function getWorkflowEnumOptions(...args: Parameters<typeof api.getWorkflowEnumOptions>) {
|
|
return api.getWorkflowEnumOptions(...args);
|
|
}
|
|
|
|
export async function resolveWorkflowEnumOptions(
|
|
client?: import("ky").KyInstance,
|
|
thirdId = "action",
|
|
platformId?: string
|
|
): Promise<Array<{ code: string; label: string; name: string; description?: string }>> {
|
|
if (client) {
|
|
try {
|
|
const remote = await api.getWorkflowEnumOptions(client, thirdId, platformId);
|
|
if (remote && remote.length > 0) {
|
|
return remote.map((item) => ({
|
|
code: item.code,
|
|
label: item.label,
|
|
name: item.name || item.label,
|
|
}));
|
|
}
|
|
} catch {
|
|
// 远程调用失败(如无权限/网络异常)时 Fallback 到内置字典
|
|
}
|
|
}
|
|
|
|
if (thirdId.toLowerCase() === "action") {
|
|
const { SYSTEM_WORKFLOW_ACTION_ENUMS } = await import("./workflow/enums.js");
|
|
return SYSTEM_WORKFLOW_ACTION_ENUMS.map((item) => ({
|
|
code: item.code,
|
|
label: item.label,
|
|
name: item.name,
|
|
description: item.description,
|
|
}));
|
|
}
|
|
|
|
return [];
|
|
}
|
|
|
|
// ── 工作流企业可用节点探针与灰度开通 ──────────────────────────────────────────
|
|
|
|
export async function getWorkflowAvailableNodes(
|
|
client: KyInstance
|
|
): Promise<import("./types.js").AvailableWorkflowNodes> {
|
|
const catalog = await api.listDslCatalog(client);
|
|
const allTypes = new Set<string>();
|
|
|
|
for (const item of catalog.action) {
|
|
if (item.type) allTypes.add(item.type);
|
|
}
|
|
for (const item of catalog.control) {
|
|
if (item.type) allTypes.add(item.type);
|
|
}
|
|
for (const item of catalog.trigger) {
|
|
if (item.type) allTypes.add(item.type);
|
|
}
|
|
|
|
return {
|
|
allTypes,
|
|
actionNodes: catalog.action,
|
|
controlNodes: catalog.control,
|
|
triggerNodes: catalog.trigger,
|
|
};
|
|
}
|
|
|
|
export async function grantWorkflowNodes(
|
|
corp: CorpConfig,
|
|
options: import("./types.js").GrantWorkflowNodesOptions
|
|
): Promise<import("./types.js").GrantWorkflowNodesResult> {
|
|
if (!options.nodes || options.nodes.length === 0) {
|
|
throw new ValidationError("必须指定至少一个需要开通的节点名称或类型");
|
|
}
|
|
|
|
// 1. 管理员密码保护预留设计
|
|
const adminPassword = process.env.HOSE_ADMIN_PASSWORD;
|
|
if (adminPassword) {
|
|
if (!options.password || options.password !== adminPassword) {
|
|
throw new PermissionError(
|
|
"灰度节点开通功能已启用管理员保护,请通过 --password 或配置输入正确的管理员密码"
|
|
);
|
|
}
|
|
}
|
|
|
|
// 2. 节点清洗与归一化(将可能传入的中文名映射为标准的 node type)
|
|
const { findGrayNode } = await import("./workflow/nodes/gray-nodes-catalog.js");
|
|
const normalizedNodes = options.nodes.map((node) => {
|
|
const matched = findGrayNode(node);
|
|
return matched ? matched.type : node.trim();
|
|
});
|
|
|
|
const token = corp.credentials?.accessToken;
|
|
const corpId = corp.corpId || corp.credentials?.corpId || corp.id;
|
|
const baseUrl = corp.baseUrl;
|
|
|
|
if (!token) {
|
|
throw new ValidationError("当前企业缺少 accessToken,无法发起节点开通申请");
|
|
}
|
|
|
|
// 3. 调用开通 API
|
|
const result = await api.grantWorkflowNodesApi({
|
|
token,
|
|
corpId,
|
|
nodes: normalizedNodes,
|
|
baseUrl,
|
|
});
|
|
|
|
return result;
|
|
}
|
|
|
|
export * from "./workflow/index.js";
|