- workflow: 修正终止节点 (stop) 模板 groupName 为 action,杜绝 Piper 前端 fallback 降级为灰色扳手图标 - skill: 补充三大凭证通道矩阵规范,明确 OpenAPI 永久凭证与动态直通链接机制 - skill: 补充工作流节点 Schema 契约与图标降级防范原则,更新 workflow node inspect/sample-save 参考文档
414 lines
12 KiB
TypeScript
414 lines
12 KiB
TypeScript
import type { WorkflowDetail, WorkflowTask } from "../types.js";
|
|
import { NotFoundError, ValidationError } from "../../../../core/errors.js";
|
|
import { findWorkflowTask } from "./locator.js";
|
|
|
|
/**
|
|
* 递归重算整棵树的 orderIndex 与 levelIndex
|
|
*/
|
|
export function reindexTasks(
|
|
tasks: WorkflowTask[],
|
|
parentLevel: number[] = [],
|
|
startOrder = 0
|
|
): number {
|
|
let currentOrder = startOrder;
|
|
for (let i = 0; i < tasks.length; i++) {
|
|
const task = tasks[i];
|
|
task.orderIndex = currentOrder++;
|
|
task.levelIndex = [...parentLevel, i];
|
|
if (task.tasks && Array.isArray(task.tasks)) {
|
|
currentOrder = reindexTasks(task.tasks, task.levelIndex, currentOrder);
|
|
}
|
|
}
|
|
return currentOrder;
|
|
}
|
|
|
|
/**
|
|
* 生成规范唯一的合思节点 ID
|
|
*/
|
|
export function generateNodeName(type: string): string {
|
|
const rand = Math.random().toString(36).substring(2, 8);
|
|
if (type === "every" || type === "condition") {
|
|
return `control_${rand}`;
|
|
}
|
|
if (type.includes("trigger") || type === "webhook" || type === "clock") {
|
|
return `trigger_${rand}`;
|
|
}
|
|
return `action_${rand}`;
|
|
}
|
|
|
|
export const MAX_NODE_DISPLAY_NAME_LENGTH = 20;
|
|
|
|
/**
|
|
* 服务端会按节点配置重建 desc 的节点类型。只有代码节点的 desc 可以稳定保留;
|
|
* 其它节点的描述写入后会在保存时被服务端覆盖,因此本地直接跳过,避免无效修改。
|
|
*/
|
|
const CODE_DESC_TYPES = new Set(["code", "code-js2"]);
|
|
|
|
export function isServerManagedDescType(type: string): boolean {
|
|
return !CODE_DESC_TYPES.has(type);
|
|
}
|
|
|
|
/** 设计器节点标题按 Unicode 字符计数(中文与 emoji 均算 1 个字符)。 */
|
|
export function displayNameLength(name: string): number {
|
|
return Array.from(name.trim()).length;
|
|
}
|
|
|
|
export function isDisplayNameTooLong(name: string): boolean {
|
|
return displayNameLength(name) > MAX_NODE_DISPLAY_NAME_LENGTH;
|
|
}
|
|
|
|
export interface AddTaskOptions {
|
|
type: string;
|
|
label?: string;
|
|
displayName?: string;
|
|
code?: string;
|
|
desc?: string;
|
|
parent?: string | number;
|
|
after?: string | number;
|
|
extra?: Record<string, any>;
|
|
}
|
|
|
|
/**
|
|
* 构建规范的新节点对象
|
|
*/
|
|
function buildWorkflowTaskBase(type: string, options: Partial<AddTaskOptions> = {}): WorkflowTask {
|
|
const normType = type.trim();
|
|
const name = generateNodeName(normType);
|
|
|
|
switch (normType) {
|
|
case "code-js2":
|
|
return {
|
|
name,
|
|
type: "code-js2",
|
|
label: options.label || "JS节点(新)",
|
|
desc: options.desc || "执行一段JavaScript代码",
|
|
groupName: "action",
|
|
code: options.code || "// 编写处理逻辑\nreturn items;",
|
|
orderIndex: 0,
|
|
levelIndex: [0],
|
|
status: "active",
|
|
...options.extra,
|
|
};
|
|
|
|
case "code":
|
|
return {
|
|
name,
|
|
type: "code",
|
|
label: options.label || "代码节点",
|
|
desc: options.desc || "执行一段MVEL代码",
|
|
groupName: "action",
|
|
code: options.code || "return true;",
|
|
orderIndex: 0,
|
|
levelIndex: [0],
|
|
status: "active",
|
|
...options.extra,
|
|
};
|
|
|
|
case "http":
|
|
return {
|
|
name,
|
|
type: "http",
|
|
label: options.label || "HTTP请求",
|
|
groupName: "action",
|
|
method: options.extra?.method || "POST",
|
|
url: options.extra?.url || "",
|
|
header: options.extra?.header || [],
|
|
params: options.extra?.params || [],
|
|
successCode: options.extra?.successCode || ["200"],
|
|
orderIndex: 0,
|
|
levelIndex: [0],
|
|
status: "active",
|
|
...options.extra,
|
|
};
|
|
|
|
case "stop":
|
|
return {
|
|
name,
|
|
type: "stop",
|
|
label: options.label || "终止节点",
|
|
desc: options.desc,
|
|
groupName: "action",
|
|
orderIndex: 0,
|
|
levelIndex: [0],
|
|
status: "active",
|
|
...options.extra,
|
|
};
|
|
|
|
case "every":
|
|
return {
|
|
name,
|
|
type: "every",
|
|
label: options.label || "依次执行",
|
|
desc: options.desc || "依次遍历每个对象",
|
|
groupName: "control",
|
|
mode: "sequence",
|
|
batch: false,
|
|
list: options.extra?.list || "@{choose('...$item')}",
|
|
filters: [],
|
|
tasksMaxLevel: 1,
|
|
tasks: [],
|
|
orderIndex: 0,
|
|
levelIndex: [0],
|
|
status: "active",
|
|
...options.extra,
|
|
};
|
|
|
|
case "condition":
|
|
return {
|
|
name,
|
|
type: "condition",
|
|
label: options.label || "条件分支",
|
|
desc: options.desc || "如果满足条件则执行以下动作",
|
|
groupName: "control",
|
|
combineFilters: options.extra?.combineFilters || { condition: "or", filters: [] },
|
|
tasksMaxLevel: 1,
|
|
tasks: [],
|
|
orderIndex: 0,
|
|
levelIndex: [0],
|
|
status: "active",
|
|
...options.extra,
|
|
};
|
|
|
|
case "webhook":
|
|
return {
|
|
name,
|
|
type: "webhook",
|
|
label: options.label || "Webhook触发",
|
|
groupName: "trigger",
|
|
orderIndex: 0,
|
|
levelIndex: [0],
|
|
status: "active",
|
|
urlPath: crypto.randomUUID(),
|
|
params: [],
|
|
...options.extra,
|
|
};
|
|
|
|
case "clock":
|
|
return {
|
|
name,
|
|
type: "clock",
|
|
label: options.label || "定时触发",
|
|
groupName: "trigger",
|
|
orderIndex: 0,
|
|
levelIndex: [0],
|
|
status: "active",
|
|
cron: options.extra?.cron || "0 0 * * *",
|
|
timeZone: options.extra?.timeZone || "Asia/Shanghai",
|
|
...options.extra,
|
|
};
|
|
|
|
case "task-dynamic-delay":
|
|
case "delay":
|
|
return {
|
|
name,
|
|
type: "task-dynamic-delay",
|
|
label: options.label || "延迟执行节点",
|
|
desc: options.desc || "在工作流中暂停等待指定秒数",
|
|
groupName: "action",
|
|
orderIndex: 0,
|
|
levelIndex: [0],
|
|
status: "active",
|
|
sleepTime: options.extra?.sleepTime ?? 60,
|
|
...options.extra,
|
|
};
|
|
|
|
default:
|
|
return {
|
|
name,
|
|
type: normType,
|
|
label: options.label || `${normType}节点`,
|
|
desc: options.desc || "",
|
|
groupName: normType.startsWith("control") ? "control" : "action",
|
|
orderIndex: 0,
|
|
levelIndex: [0],
|
|
status: "active",
|
|
...options.extra,
|
|
};
|
|
}
|
|
}
|
|
|
|
function applyDisplayName(task: WorkflowTask, displayName?: string): void {
|
|
if (displayName === undefined) return;
|
|
const trimmed = displayName.trim();
|
|
if (!trimmed) {
|
|
delete (task as any).displayName;
|
|
return;
|
|
}
|
|
if (isDisplayNameTooLong(trimmed)) {
|
|
throw new ValidationError(
|
|
`节点显示名称最多 ${MAX_NODE_DISPLAY_NAME_LENGTH} 个字符(前端设计器上限),当前 ${displayNameLength(trimmed)} 个字符: ${trimmed}`
|
|
);
|
|
}
|
|
(task as any).displayName = trimmed;
|
|
}
|
|
|
|
/**
|
|
* 构建规范的新节点对象
|
|
*/
|
|
export function buildWorkflowTask(type: string, options: Partial<AddTaskOptions> = {}): WorkflowTask {
|
|
const task = buildWorkflowTaskBase(type, options);
|
|
applyDisplayName(task, options.displayName);
|
|
return task;
|
|
}
|
|
|
|
/**
|
|
* 向工作流声明式追加或插入任务节点
|
|
*/
|
|
export function addWorkflowTask(
|
|
workflow: WorkflowDetail,
|
|
options: AddTaskOptions
|
|
): { workflow: WorkflowDetail; newTask: WorkflowTask } {
|
|
const cloned = JSON.parse(JSON.stringify(workflow)) as WorkflowDetail;
|
|
if (!cloned.tasks) cloned.tasks = [];
|
|
|
|
const newTask = buildWorkflowTask(options.type, options);
|
|
|
|
if (options.after !== undefined && options.after !== "") {
|
|
const target = findWorkflowTask(cloned.tasks, options.after);
|
|
if (!target) {
|
|
throw new NotFoundError(`未找到插入基准节点 (--after): ${options.after}`);
|
|
}
|
|
// 插入在该节点的下一个位置
|
|
target.parentTasks.splice(target.arrayIndex + 1, 0, newTask);
|
|
} else if (options.parent !== undefined && options.parent !== "") {
|
|
const parentTarget = findWorkflowTask(cloned.tasks, options.parent);
|
|
if (!parentTarget) {
|
|
throw new NotFoundError(`未找到父级容器节点 (--parent): ${options.parent}`);
|
|
}
|
|
if (!parentTarget.task.tasks) parentTarget.task.tasks = [];
|
|
parentTarget.task.tasks.push(newTask);
|
|
} else {
|
|
// 默认追加到顶级 tasks 末尾
|
|
cloned.tasks.push(newTask);
|
|
}
|
|
|
|
// 重排索引
|
|
reindexTasks(cloned.tasks);
|
|
return { workflow: cloned, newTask };
|
|
}
|
|
|
|
export interface EditTaskOptions {
|
|
label?: string;
|
|
displayName?: string;
|
|
code?: string;
|
|
desc?: string;
|
|
set?: Record<string, any>;
|
|
}
|
|
|
|
/**
|
|
* 定向修改工作流任务节点配置
|
|
*/
|
|
export function editWorkflowTask(
|
|
workflow: WorkflowDetail,
|
|
targetKey: string | number,
|
|
updates: EditTaskOptions
|
|
): { workflow: WorkflowDetail; editedTask: WorkflowTask } {
|
|
const cloned = JSON.parse(JSON.stringify(workflow)) as WorkflowDetail;
|
|
if (!cloned.tasks) cloned.tasks = [];
|
|
|
|
const target = findWorkflowTask(cloned.tasks, targetKey);
|
|
if (!target) {
|
|
throw new NotFoundError(`未找到目标工作流任务节点: ${targetKey}`);
|
|
}
|
|
|
|
const { task } = target;
|
|
if (updates.label !== undefined) task.label = updates.label;
|
|
if (updates.displayName !== undefined) applyDisplayName(task, updates.displayName);
|
|
if (updates.desc !== undefined && !isServerManagedDescType(task.type)) task.desc = updates.desc;
|
|
if (updates.code !== undefined) (task as any).code = updates.code;
|
|
|
|
if (updates.set && typeof updates.set === "object") {
|
|
for (const [k, v] of Object.entries(updates.set)) {
|
|
if (k === "displayName") {
|
|
applyDisplayName(task, typeof v === "string" ? v : v == null ? "" : String(v));
|
|
continue;
|
|
}
|
|
(task as any)[k] = v;
|
|
}
|
|
}
|
|
|
|
return { workflow: cloned, editedTask: task };
|
|
}
|
|
|
|
/**
|
|
* 安全剔除工作流任务节点
|
|
*/
|
|
export function removeWorkflowTask(
|
|
workflow: WorkflowDetail,
|
|
targetKey: string | number
|
|
): { workflow: WorkflowDetail; removedTask: WorkflowTask } {
|
|
const cloned = JSON.parse(JSON.stringify(workflow)) as WorkflowDetail;
|
|
if (!cloned.tasks || cloned.tasks.length === 0) {
|
|
throw new ValidationError("工作流中无任何任务节点,无法删除");
|
|
}
|
|
|
|
const target = findWorkflowTask(cloned.tasks, targetKey);
|
|
if (!target) {
|
|
throw new NotFoundError(`未找到待删除的工作流任务节点: ${targetKey}`);
|
|
}
|
|
|
|
// 触发器保护:如果工作流只有首节点且是触发器,或者删除首节点触发器
|
|
if (
|
|
target.parentTasks === cloned.tasks &&
|
|
target.arrayIndex === 0 &&
|
|
(target.task.groupName === "trigger" || target.task.type.includes("trigger") || target.task.type === "webhook" || target.task.type === "clock")
|
|
) {
|
|
throw new ValidationError(
|
|
`节点 [${target.task.name}] (${target.task.label || target.task.type}) 是工作流的触发源节点。直接移除会导致工作流缺少触发器,请使用 workflow save 或在设计器中调整触发器。`
|
|
);
|
|
}
|
|
|
|
const [removedTask] = target.parentTasks.splice(target.arrayIndex, 1);
|
|
reindexTasks(cloned.tasks);
|
|
return { workflow: cloned, removedTask };
|
|
}
|
|
|
|
export type MappingContent = Array<Record<string, any>> | Record<string, any>;
|
|
|
|
/**
|
|
* 批量映射节点字段配置 (支持数组格式替换 fields,或对象格式深度设置属性)
|
|
*/
|
|
export function applyNodeMapping(
|
|
workflow: WorkflowDetail,
|
|
targetKey: string | number,
|
|
mapping: MappingContent
|
|
): { workflow: WorkflowDetail; editedTask: WorkflowTask; changedKeys: string[] } {
|
|
const cloned = JSON.parse(JSON.stringify(workflow)) as WorkflowDetail;
|
|
if (!cloned.tasks) cloned.tasks = [];
|
|
|
|
const target = findWorkflowTask(cloned.tasks, targetKey);
|
|
if (!target) {
|
|
throw new NotFoundError(`未找到目标工作流任务节点: ${targetKey}`);
|
|
}
|
|
|
|
const { task } = target;
|
|
const changedKeys: string[] = [];
|
|
|
|
if (Array.isArray(mapping)) {
|
|
// 数组格式直接更新/替换 fields 数组
|
|
(task as any).fields = mapping;
|
|
changedKeys.push(`fields (${mapping.length} 项)`);
|
|
} else if (mapping && typeof mapping === "object") {
|
|
// 对象格式:合并/设置每个顶层键
|
|
for (const [key, value] of Object.entries(mapping)) {
|
|
if (key === "displayName") {
|
|
applyDisplayName(task, typeof value === "string" ? value : value == null ? "" : String(value));
|
|
} else if (key === "desc" && isServerManagedDescType(task.type)) {
|
|
changedKeys.push("desc (服务端托管,已跳过)");
|
|
continue;
|
|
} else {
|
|
(task as any)[key] = value;
|
|
}
|
|
if (Array.isArray(value)) {
|
|
changedKeys.push(`${key} (${value.length} 项)`);
|
|
} else {
|
|
changedKeys.push(key);
|
|
}
|
|
}
|
|
} else {
|
|
throw new ValidationError("映射内容必须为 JSON 数组或 JSON 对象");
|
|
}
|
|
|
|
return { workflow: cloned, editedTask: task, changedKeys };
|
|
}
|