## 背景
条件节点对「取值链要先穿过列表再往下取字段」的字段做大于/小于类比较时,上游
列表为空会让字段取到 `null`。MVEL 里 `null < 0` 返回的是 **null 而不是 false**,
引擎对 condition 做强 Boolean 校验,于是直接抛:
```
if 节点(xxx)的 condition 参数的解析结果必须为 Boolean 类型
```
流程在这里**中断**,而不是安静地走 false 分支。真实案例中一条链路跑到第 9 步
才炸,报错信息完全指不出是哪次取值拿到了 null。
## 关键实测结论:AND 不短路
直觉写法是 `AND(列表非空, 额度 < 0)`,指望布尔短路跳过后面的比较。实测证明
这条路走不通——合思引擎**逐叶子求值再合并**:
| 输入 | 条件 | 结果 |
|---|---|---|
| 列表为空 | `AND(列表 notNull, 额度 lt 0)` | FAILED,仍是同一个类型错误 |
| 额度 = -5 | 同上 | COMPLETED |
也就是说同一个条件节点里加「不为空」判断**完全无效**,null 比较照样会被算出来。
唯一可靠的是流程控制短路:外层套一个条件节点判「列表不为空」,把原节点放进它的
满足分支——列表为空时外层为 false,内层根本不被求值。
同时确认了判空本身的可用性:`notNull` 对空数组 `[]` 返回 false、对非空数组返回
true,且不需要 `value` 字段;条件为 false 时节点 COMPLETED、子节点跳过、流程继续。
## 实现
新增 `analysis/condition-null-safety.ts`:
- `readChoosePath()` 解析 `@{choose('{...}')}` 描述符,兼容前端多一个右花括号的形态,
取出取值链的根节点与 `properties` 层级;
- `goesThroughList()` 判定取值链是否「穿过 `DATA_LINK_LIST` 之后还有层级」——
单层字段取值和「只判列表本身」都不算风险;
- `hasAncestorListGuard()` 沿祖先链找对同一列表做过 `notNull` 判断的条件节点;
- 命中「有序比较(`gt/gte/lt/lte`)+ 穿过列表 + 无祖先守卫」时产出
`CONDITION_NULL_UNSAFE_COMPARE` 软提示,消息里明确否掉「用 AND 兜住」这个直觉解法,
并给出守卫上提的正确写法。
`analyzer.ts` 的遍历新增祖先链参数,在条件节点诊断段之后调用该检查。
## 为什么是软建议而不是硬门禁
静态分析无法确定上游列表一定为空(例如上游刚创建、或业务上保证有数据),硬阻断会
让合法流程无法发布。因此只提示、不改写配置、不推断数据非空。`eq`/`neq` 也不纳入
检查——null 与值做相等比较返回的是布尔,不会中断。
## 测试
新增 14 个用例:路径解析(含多花括号形态)、穿过列表判定、无守卫告警、同节点内
AND 组合仍告警、外层守卫不告警、守卫判断的是别的列表仍告警、单层取值不告警、
只判列表不告警、`gt/gte/lte` 覆盖、`eq` 不告警、同一路径去重。
另外用真实流程做了前后对照:改造前(无守卫)命中 2 条,加上守卫后命中 0 条。
`bun test` 1082 pass / 0 fail;`bun run check` 零错误;`check:readme` 通过。
943 lines
42 KiB
TypeScript
943 lines
42 KiB
TypeScript
import type { WorkflowDetail, WorkflowTask } from "../types.js";
|
||
import { addDiagnostic } from "./diagnostics.js";
|
||
import { checkEveryConfiguration, extractLeafFilters } from "./every.js";
|
||
import type {
|
||
WorkflowAnalysis,
|
||
WorkflowAstNode,
|
||
WorkflowDependency,
|
||
WorkflowDiagnostic,
|
||
WorkflowAnalysisSummary,
|
||
WorkflowFormSpecComponentLike,
|
||
AnalyzeWorkflowOptions,
|
||
} from "./types.js";
|
||
import { isKnownGrayNodeType } from "../nodes/gray-nodes-catalog.js";
|
||
import { matchAppRequirement } from "./openapi-app-requirements.js";
|
||
import { checkConditionNullSafety } from "./condition-null-safety.js";
|
||
|
||
const KNOWN_TYPES = new Set([
|
||
"webhook",
|
||
"crontab",
|
||
"clock",
|
||
"condition",
|
||
"every",
|
||
"stop",
|
||
"http",
|
||
"flow-detail",
|
||
"code",
|
||
"code-js2",
|
||
"apportion",
|
||
"flow-change-trigger",
|
||
"datalink-button-trigger",
|
||
"email",
|
||
"message",
|
||
"message-dingtalk",
|
||
"dmn",
|
||
"ekuaibao-datalink-filter",
|
||
"ekuaibao-datalink-create",
|
||
"ekuaibao-datalink-edit",
|
||
"ekuaibao-datalink-delete",
|
||
"ekuaibao-flowform-trigger",
|
||
"ekuaibao-ebot-trigger",
|
||
"ekuaibao-datalink-create-trigger",
|
||
"ekuaibao-datalink-time-trigger",
|
||
"ekuaibao-datalink-edit-trigger",
|
||
"ekuaibao-datalink-delete-trigger",
|
||
"data-convert",
|
||
"flow-create-task",
|
||
"task-dynamic-delay",
|
||
]);
|
||
|
||
interface ChooseReference {
|
||
raw: string;
|
||
key?: string;
|
||
descriptor?: boolean;
|
||
problem?: string;
|
||
invalidDescriptor?: boolean;
|
||
}
|
||
|
||
/** 只解析 choose 参数,不执行表达式;引号内的括号不参与标签边界匹配。 */
|
||
function extractChooseTags(val: unknown): ChooseReference[] {
|
||
if (typeof val !== "string") return [];
|
||
const results: ChooseReference[] = [];
|
||
const marker = /@\{\s*choose\s*\(/g;
|
||
let match: RegExpExecArray | null;
|
||
while ((match = marker.exec(val))) {
|
||
const from = marker.lastIndex;
|
||
let quote = "";
|
||
let escaped = false;
|
||
let depth = 1;
|
||
let end = from;
|
||
for (; end < val.length; end++) {
|
||
const ch = val[end];
|
||
if (quote) {
|
||
if (escaped) escaped = false;
|
||
else if (ch === "\\") escaped = true;
|
||
else if (ch === quote) quote = "";
|
||
} else if (ch === "'" || ch === '"') quote = ch;
|
||
else if (ch === "(") depth++;
|
||
else if (ch === ")" && --depth === 0) break;
|
||
}
|
||
const close = /^\s*\}/.exec(val.slice(end + 1));
|
||
if (depth !== 0 || !close) {
|
||
results.push({ raw: val.slice(match.index), problem: "choose 标签未闭合或缺少结束标记" });
|
||
continue;
|
||
}
|
||
marker.lastIndex = end + 1 + close[0].length;
|
||
const raw = val.slice(match.index, marker.lastIndex);
|
||
const argument = val.slice(from, end).trim();
|
||
let isDescriptor = false;
|
||
try {
|
||
let value = argument;
|
||
if (argument.startsWith('"')) value = JSON.parse(argument);
|
||
else if (argument.startsWith("'")) {
|
||
if (!argument.endsWith("'")) throw new Error("未闭合的参数字符串");
|
||
// 单引号是模板包裹符;保留 descriptor 内 JSON 自身的转义。
|
||
value = argument.slice(1, -1).replace(/\\'/g, "'");
|
||
}
|
||
if (typeof value !== "string") throw new Error("参数应为节点描述或路径");
|
||
if (value.trim().startsWith("{")) {
|
||
isDescriptor = true;
|
||
const descriptor: unknown = JSON.parse(value);
|
||
if (!descriptor || typeof descriptor !== "object" || Array.isArray(descriptor) || typeof (descriptor as Record<string, unknown>).key !== "string" || !(descriptor as { key: string }).key.trim()) throw new Error("节点描述缺少 key");
|
||
results.push({ raw, key: (descriptor as { key: string }).key.trim(), descriptor: true });
|
||
} else if (/^[$\p{L}_][$\p{L}\p{N}_]*(?:\.[$\p{L}\p{N}_]+)*$/u.test(value.trim())) {
|
||
results.push({ raw, key: value.trim(), descriptor: false });
|
||
} else throw new Error("参数不是可静态识别的节点路径");
|
||
} catch {
|
||
results.push({ raw, invalidDescriptor: isDescriptor,
|
||
problem: isDescriptor ? "choose 节点描述不是有效 JSON 对象或缺少有效 key" : "choose 参数不是可静态识别的节点描述或路径" });
|
||
}
|
||
}
|
||
return results;
|
||
}
|
||
|
||
function collectExpressionValues(value: unknown, path: string, result: Array<{ key: string; value: string }>, allowEntry = false): void {
|
||
if (typeof value === "string") result.push({ key: path, value });
|
||
else if (Array.isArray(value)) value.forEach((item, index) => {
|
||
collectExpressionValues(item, `${path}[${index}]`, result, true);
|
||
});
|
||
else if (value && typeof value === "object") {
|
||
const entry = value as Record<string, unknown>;
|
||
if (allowEntry && Object.hasOwn(entry, "key") && typeof entry.key === "string" && Object.hasOwn(entry, "value")) {
|
||
// 明确 key/value 条目的 label/type 是元信息;普通映射的 label 字段仍是业务值。
|
||
collectExpressionValues(entry.value, `${path}[${entry.key}].value`, result);
|
||
} else {
|
||
for (const [key, child] of Object.entries(value)) collectExpressionValues(child, `${path}.${key}`, result, true);
|
||
}
|
||
}
|
||
}
|
||
|
||
const CHOOSE_CONTEXT_ROOTS = new Set(["body", "input", "inputs", "output", "outputs", "context", "ctx"]);
|
||
|
||
function buildTaskNameMap(tasks: WorkflowTask[]): Map<string, WorkflowTask> {
|
||
const map = new Map<string, WorkflowTask>();
|
||
const walk = (list: WorkflowTask[]) => {
|
||
for (const t of list) {
|
||
if (t.name) map.set(t.name, t);
|
||
if (Array.isArray(t.tasks)) walk(t.tasks);
|
||
}
|
||
};
|
||
walk(tasks);
|
||
return map;
|
||
}
|
||
|
||
function referencesFromTask(task: WorkflowTask): string[] {
|
||
const code = typeof task.code === "string" ? task.code : "";
|
||
const values = [
|
||
...code.matchAll(
|
||
/\{\{\s*([^{}]+?)\s*\}\}|\b(?:ctx|input|output|context)\.([A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*)/g
|
||
),
|
||
]
|
||
.map((match) => (match[1] || match[2] || "").trim())
|
||
.filter(Boolean);
|
||
return [...new Set(values)];
|
||
}
|
||
|
||
function toAst(tasks: WorkflowTask[], parentPath = ""): WorkflowAstNode[] {
|
||
return tasks.map((task, index) => {
|
||
const path = parentPath ? `${parentPath}.${index}` : String(index);
|
||
return {
|
||
type: task.type,
|
||
name: task.name,
|
||
label: task.label || task.displayName || "",
|
||
path,
|
||
orderIndex: task.orderIndex,
|
||
levelIndex: task.levelIndex,
|
||
children: toAst(task.tasks || [], path),
|
||
};
|
||
});
|
||
}
|
||
|
||
function getTaskSpecificationId(task: WorkflowTask): string | undefined {
|
||
const raw = task as Record<string, unknown>;
|
||
if (typeof raw.specificationId === "string" && raw.specificationId.trim()) {
|
||
return raw.specificationId.trim();
|
||
}
|
||
if (Array.isArray(task.inputs)) {
|
||
const found = task.inputs.find((item) => item.key === "specificationId");
|
||
if (found && typeof found.value === "string" && found.value.trim()) {
|
||
return found.value.trim();
|
||
}
|
||
} else if (raw.inputs && typeof raw.inputs === "object") {
|
||
const specId = (raw.inputs as Record<string, unknown>).specificationId;
|
||
if (typeof specId === "string" && specId.trim()) {
|
||
return specId.trim();
|
||
}
|
||
}
|
||
return undefined;
|
||
}
|
||
|
||
function getTaskFormEntries(
|
||
task: WorkflowTask
|
||
): Array<{ key?: string; label?: string; type?: string; value?: unknown }> {
|
||
const raw = task as Record<string, unknown>;
|
||
if (Array.isArray(raw.form)) {
|
||
return raw.form.filter(
|
||
(item): item is { key?: string; label?: string; type?: string; value?: unknown } =>
|
||
Boolean(item && typeof item === "object")
|
||
);
|
||
}
|
||
if (raw.form && typeof raw.form === "object") {
|
||
return Object.entries(raw.form as Record<string, unknown>).map(([key, value]) => ({
|
||
key,
|
||
value,
|
||
}));
|
||
}
|
||
if (Array.isArray(task.inputs)) {
|
||
const formInput = task.inputs.find((item) => item.key === "form");
|
||
if (formInput && Array.isArray(formInput.value)) {
|
||
return formInput.value.filter(
|
||
(item: unknown): item is { key?: string; label?: string; type?: string; value?: unknown } =>
|
||
Boolean(item && typeof item === "object")
|
||
);
|
||
}
|
||
if (formInput && formInput.value && typeof formInput.value === "object") {
|
||
return Object.entries(formInput.value as Record<string, unknown>).map(([key, value]) => ({
|
||
key,
|
||
value,
|
||
}));
|
||
}
|
||
} else if (raw.inputs && typeof raw.inputs === "object") {
|
||
const formVal = (raw.inputs as Record<string, unknown>).form;
|
||
if (Array.isArray(formVal)) {
|
||
return formVal.filter(
|
||
(item): item is { key?: string; label?: string; type?: string; value?: unknown } =>
|
||
Boolean(item && typeof item === "object")
|
||
);
|
||
}
|
||
if (formVal && typeof formVal === "object") {
|
||
return Object.entries(formVal as Record<string, unknown>).map(([key, value]) => ({
|
||
key,
|
||
value,
|
||
}));
|
||
}
|
||
}
|
||
return [];
|
||
}
|
||
|
||
export function extractWorkflowSpecificationIds(detail: WorkflowDetail): string[] {
|
||
const ids = new Set<string>();
|
||
const walk = (tasks: WorkflowTask[]) => {
|
||
for (const task of tasks) {
|
||
if (task.type === "flow-create-task") {
|
||
const specId = getTaskSpecificationId(task);
|
||
if (specId) ids.add(specId);
|
||
}
|
||
if (Array.isArray(task.tasks) && task.tasks.length > 0) {
|
||
walk(task.tasks);
|
||
}
|
||
}
|
||
};
|
||
walk(detail.tasks || []);
|
||
return [...ids];
|
||
}
|
||
|
||
/** 合思条件里代表「上一步执行结果」的属性名。 */
|
||
const EXECUTION_STATUS_PROPERTIES = ["$status", "status", "result", "data"];
|
||
|
||
/** 条件数据来源:各处写法顺序不统一,这里固定为唯一的解析入口。 */
|
||
function collectFilterSource(task: WorkflowTask): unknown {
|
||
const raw = task as Record<string, unknown>;
|
||
return raw.combineFilters ?? raw.filters ?? raw.conditions ?? raw.inputs ?? {};
|
||
}
|
||
|
||
/** 收集条件节点内的全部字符串,用于逐个做引用判定。 */
|
||
function collectReferenceStrings(source: unknown, found: string[] = []): string[] {
|
||
if (typeof source === "string") {
|
||
found.push(source);
|
||
return found;
|
||
}
|
||
if (Array.isArray(source)) {
|
||
for (const item of source) collectReferenceStrings(item, found);
|
||
return found;
|
||
}
|
||
if (source && typeof source === "object") {
|
||
for (const value of Object.values(source as Record<string, unknown>)) {
|
||
collectReferenceStrings(value, found);
|
||
}
|
||
}
|
||
return found;
|
||
}
|
||
|
||
/** 取出 `${a.b}` 或 `a.b` 形态的引用目标;无法判定为引用时返回 undefined。 */
|
||
function referenceTargetOf(raw: string): string | undefined {
|
||
const trimmed = raw.trim();
|
||
const bracketed = /^\$\{([^}]+)\}$/.exec(trimmed);
|
||
const candidate = (bracketed ? bracketed[1] : trimmed).trim();
|
||
return candidate || undefined;
|
||
}
|
||
|
||
/**
|
||
* 判定条件节点是否真正守卫了某个节点的执行状态。
|
||
* 必须整体等于 `<节点名>.$status` 等形态,不能靠子串包含:
|
||
* 子串匹配会让 `task_1` 命中 `task_10` 之类无关引用,从而把「未守卫」误判为「已守卫」,
|
||
* 使这条安全建议静默失效。
|
||
*/
|
||
function taskGuardsStatusOf(task: WorkflowTask, targetTaskName: string): boolean {
|
||
if (task.type !== "condition") return false;
|
||
const expected = new Set(EXECUTION_STATUS_PROPERTIES.map((property) => `${targetTaskName}.${property}`));
|
||
return collectReferenceStrings(collectFilterSource(task)).some((item) => {
|
||
const target = referenceTargetOf(item);
|
||
return target !== undefined && expected.has(target);
|
||
});
|
||
}
|
||
|
||
function findUnguardedDatalinkEdits(
|
||
tasks: WorkflowTask[],
|
||
basePath: string,
|
||
createTaskName: string
|
||
): Array<{ task: WorkflowTask; path: string }> {
|
||
const found: Array<{ task: WorkflowTask; path: string }> = [];
|
||
tasks.forEach((task, idx) => {
|
||
const path = `${basePath}.${idx}`;
|
||
if (task.type === "ekuaibao-datalink-edit") {
|
||
found.push({ task, path });
|
||
return;
|
||
}
|
||
if (taskGuardsStatusOf(task, createTaskName)) {
|
||
return;
|
||
}
|
||
if (Array.isArray(task.tasks) && task.tasks.length > 0) {
|
||
found.push(...findUnguardedDatalinkEdits(task.tasks, path, createTaskName));
|
||
}
|
||
});
|
||
return found;
|
||
}
|
||
|
||
const FORMULA_REGEX =
|
||
/^(?:=\s*)?(AddMonths|dateDIF|DATEADD|DATEDIF|IF|SUM|ROUND|INT|TEXT|YEAR|MONTH|DAY)\s*\([\s\S]*\)$/i;
|
||
|
||
function checkMisplacedFormulasInDatalink(
|
||
task: WorkflowTask,
|
||
path: string,
|
||
diagnostics: WorkflowDiagnostic[]
|
||
): void {
|
||
if (!task.type.includes("datalink")) return;
|
||
const raw = task as Record<string, unknown>;
|
||
const inspectTargets: Array<{ key: string; value: unknown; type?: unknown }> = [];
|
||
|
||
// 1. inspect task.inputs
|
||
if (Array.isArray(task.inputs)) {
|
||
for (const inp of task.inputs) {
|
||
if (inp && typeof inp === "object") {
|
||
inspectTargets.push({ key: inp.key || (inp as any).name || "input", value: inp.value, type: (inp as any).type });
|
||
}
|
||
}
|
||
} else if (raw.inputs && typeof raw.inputs === "object") {
|
||
for (const [k, v] of Object.entries(raw.inputs as Record<string, unknown>)) {
|
||
inspectTargets.push({ key: k, value: v });
|
||
}
|
||
}
|
||
|
||
// 2. inspect task.form / formValues / mapping
|
||
const formEntries = getTaskFormEntries(task);
|
||
for (const entry of formEntries) {
|
||
if (entry.key) {
|
||
inspectTargets.push({ key: entry.key, value: entry.value, type: entry.type });
|
||
}
|
||
}
|
||
|
||
// 3. inspect raw.mapping / raw.data / raw.jsonMapping
|
||
if (Array.isArray(raw.mapping)) {
|
||
for (const m of raw.mapping) {
|
||
if (m && typeof m === "object") {
|
||
const item = m as Record<string, unknown>;
|
||
inspectTargets.push({
|
||
key: String(item.key || item.target || "field"),
|
||
value: item.value ?? item.source,
|
||
type: item.type,
|
||
});
|
||
}
|
||
}
|
||
}
|
||
|
||
// 4. inspect task.fields / raw.fields (合思业务对象新增/修改字段映射)
|
||
const fields = (task as any).fields ?? raw.fields;
|
||
if (Array.isArray(fields)) {
|
||
for (const f of fields) {
|
||
if (f && typeof f === "object") {
|
||
const item = f as Record<string, unknown>;
|
||
inspectTargets.push({
|
||
key: String(item.key || item.label || "field"),
|
||
value: item.value,
|
||
type: item.type,
|
||
});
|
||
}
|
||
}
|
||
}
|
||
|
||
for (const target of inspectTargets) {
|
||
if (typeof target.value === "string") {
|
||
const match = target.value.trim().match(FORMULA_REGEX);
|
||
const fieldType = typeof target.type === "string" ? target.type.toLowerCase() : "";
|
||
if (["text", "string", "textarea", "multiline", "richtext"].includes(fieldType)) continue;
|
||
const strongType = ["date", "datetime", "timestamp", "number", "numeric", "integer", "decimal", "float", "money"].includes(fieldType);
|
||
if (match) {
|
||
addDiagnostic(diagnostics, {
|
||
severity: strongType ? "error" : "warning",
|
||
code: "MISPLACED_FORMULA_IN_DATALINK_MAPPING",
|
||
path,
|
||
message: strongType
|
||
? `DataLink 任务 '${task.label || task.name}' 的 ${fieldType} 字段 '${target.key}' 配置了表单公式 '${match[0]}'。底层数据写入不求值表单公式,强类型字段不能接受该表达式;请前置添加【代码节点】计算该值并在此处引用。`
|
||
: `DataLink 任务 '${task.label || task.name}' 的字段 '${target.key}' 包含疑似公式 '${match[0]}',但缺少可验证的字段类型,仅作为建议。若需要计算,请前置添加【代码节点】;若为文本,请保留字面量。`,
|
||
});
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
const WELL_KNOWN_POWER_CODES: Record<string, string> = {
|
||
ticket_audit_switch: "单据审批 (TICKET_AUDIT_switch)",
|
||
staff_sync_switch: "通讯录同步 (STAFF_SYNC_switch)",
|
||
payment_switch: "资金付款 (PAYMENT_switch)",
|
||
invoice_switch: "发票管理 (INVOICE_switch)",
|
||
budget_switch: "预算管控 (BUDGET_switch)",
|
||
contract_switch: "合同管理 (CONTRACT_switch)",
|
||
};
|
||
|
||
export function analyzeWorkflow(
|
||
detail: WorkflowDetail,
|
||
options: AnalyzeWorkflowOptions = {}
|
||
): WorkflowAnalysis {
|
||
const ast = toAst(detail.tasks);
|
||
const dependencies: WorkflowDependency[] = [];
|
||
const diagnostics: WorkflowDiagnostic[] = [];
|
||
|
||
const availableSet: Set<string> | undefined = options.availableNodeTypes
|
||
? new Set(
|
||
(Array.isArray(options.availableNodeTypes)
|
||
? options.availableNodeTypes
|
||
: Array.from(options.availableNodeTypes)
|
||
).map((t) => t.trim().toLowerCase())
|
||
)
|
||
: undefined;
|
||
|
||
const openedPowerCodeSet: Set<string> | undefined = options.openedPowerCodes
|
||
? new Set(
|
||
(Array.isArray(options.openedPowerCodes)
|
||
? options.openedPowerCodes
|
||
: Array.from(options.openedPowerCodes)
|
||
).map((p) => p.trim().toLowerCase())
|
||
)
|
||
: undefined;
|
||
|
||
if (detail.state === 0) {
|
||
addDiagnostic(diagnostics, {
|
||
severity: "warning",
|
||
code: "WORKFLOW_DISABLED",
|
||
path: "workflow",
|
||
message:
|
||
"工作流当前处于未启用/草稿状态 (state=0),修改或排障后需 publish/toggle --state=1 方可生效",
|
||
});
|
||
}
|
||
|
||
const taskNameMap = buildTaskNameMap(detail.tasks);
|
||
|
||
const visit = (tasks: WorkflowTask[], parentPath = "", insideEvery = false, ancestors: WorkflowTask[] = []) => {
|
||
tasks.forEach((task, index) => {
|
||
const path = parentPath ? `${parentPath}.${index}` : String(index);
|
||
const refs = referencesFromTask(task);
|
||
if (refs.length) {
|
||
dependencies.push({ path, taskType: task.type, references: refs });
|
||
}
|
||
if ((task.type === "code" || task.type === "code-js2") && !String(task.code || "").trim()) {
|
||
addDiagnostic(diagnostics, {
|
||
severity: "error",
|
||
code: "EMPTY_CODE",
|
||
path,
|
||
message: "代码节点没有可执行脚本",
|
||
});
|
||
}
|
||
if ((task.type === "condition" || task.type === "every") && !(task.tasks || []).length) {
|
||
addDiagnostic(diagnostics, {
|
||
severity: "warning",
|
||
code: "EMPTY_BRANCH",
|
||
path,
|
||
message: `${task.type} 控制节点没有子节点`,
|
||
});
|
||
}
|
||
if (!KNOWN_TYPES.has(task.type) && !isKnownGrayNodeType(task.type)) {
|
||
addDiagnostic(diagnostics, {
|
||
severity: "warning",
|
||
code: "UNKNOWN_TASK_TYPE",
|
||
path,
|
||
message: `未收录的节点类型: ${task.type}`,
|
||
});
|
||
}
|
||
|
||
// 诊断:租户节点开通权限校验
|
||
if (availableSet && availableSet.size > 0 && !availableSet.has(task.type.toLowerCase())) {
|
||
addDiagnostic(diagnostics, {
|
||
severity: "error",
|
||
code: "PERMISSION_MISSING_NODE",
|
||
path,
|
||
message: `当前企业尚未开通节点类型 '${task.type}',工作流运行时将被合思引擎直接阻断。请先使用 'hose-use workflow nodes grant ${task.type}' 开通灰度权限,或替换为已开通的等价节点。`,
|
||
});
|
||
}
|
||
|
||
// 诊断:DataLink 字段误填表单公式硬校验
|
||
checkMisplacedFormulasInDatalink(task, path, diagnostics);
|
||
checkEveryConfiguration(task, path, diagnostics);
|
||
|
||
// 本地条件解释器支持的通用比较符,不等于真实设计器对应字段的枚举。
|
||
if (task.type === "ekuaibao-datalink-filter") {
|
||
const raw = task as Record<string, unknown>;
|
||
for (const filter of extractLeafFilters(raw.combineFilters ?? raw.filters)) {
|
||
if (filter.compare === "gte" || filter.compare === "lte") {
|
||
addDiagnostic(diagnostics, {
|
||
severity: "warning", code: "DATALINK_FILTER_COMPARISON_COMPATIBILITY", path,
|
||
message: `业务对象筛选字段 [${String(filter.key || "未知")}] 使用通用比较符 '${filter.compare}'。合思前端日期字段可能不识别该枚举,请在设计器核对支持的比较符;直接替换为 gt/lt 会改变等号边界,月份范围需同时核对月初及下月月初时间戳。`,
|
||
});
|
||
}
|
||
}
|
||
}
|
||
|
||
// 诊断 2: every 循环内 flow-create-task (SKIP) 后跟无状态守卫的 ekuaibao-datalink-edit
|
||
if (insideEvery && task.type === "flow-create-task") {
|
||
const onError = (task as Record<string, unknown>).onError as
|
||
| { defaultAction?: string }
|
||
| undefined;
|
||
if (onError?.defaultAction === "SKIP") {
|
||
const subsequentSiblings = tasks.slice(index + 1);
|
||
const unguardedEdits: Array<{ task: WorkflowTask; path: string }> = [];
|
||
subsequentSiblings.forEach((sibling, relIdx) => {
|
||
const siblingIndex = index + 1 + relIdx;
|
||
const siblingPath = parentPath ? `${parentPath}.${siblingIndex}` : String(siblingIndex);
|
||
if (sibling.type === "ekuaibao-datalink-edit") {
|
||
unguardedEdits.push({ task: sibling, path: siblingPath });
|
||
} else if (!taskGuardsStatusOf(sibling, task.name) && sibling.tasks?.length) {
|
||
unguardedEdits.push(
|
||
...findUnguardedDatalinkEdits(sibling.tasks, siblingPath, task.name)
|
||
);
|
||
}
|
||
});
|
||
|
||
for (const edit of unguardedEdits) {
|
||
addDiagnostic(diagnostics, {
|
||
severity: "warning",
|
||
code: "UNSAFE_SKIP_WITHOUT_STATUS_GUARD",
|
||
path: edit.path,
|
||
message: `节点 [${task.label || task.name}] (${task.name}) 配置了报错跳过(SKIP),但后续台账更新节点 [${edit.task.label || edit.task.name}] (${edit.task.name}) 未校验其执行状态(如 ${task.name}.$status),前序建单失败时仍会误改台账状态!`,
|
||
});
|
||
}
|
||
}
|
||
}
|
||
|
||
// 诊断 3: flow-create-task 表单字段联动覆盖告警 (LINKAGE_ASSIGNMENT > MANUALLY_FILL_IN)
|
||
if (task.type === "flow-create-task") {
|
||
const specId = getTaskSpecificationId(task);
|
||
const spec = specId ? options.specifications?.[specId] : undefined;
|
||
const formEntries = getTaskFormEntries(task).filter(
|
||
(entry) =>
|
||
entry.value !== undefined &&
|
||
entry.value !== null &&
|
||
String(entry.value).trim() !== ""
|
||
);
|
||
|
||
const specComponents =
|
||
spec?.components ??
|
||
(Array.isArray((spec as unknown as Record<string, unknown> | undefined)?.form)
|
||
? ((spec as unknown as Record<string, unknown>).form as WorkflowFormSpecComponentLike[])
|
||
: []);
|
||
|
||
if (spec && specComponents.length && formEntries.length > 0) {
|
||
const matchedComponents = specComponents.filter((comp) => {
|
||
const compKey = comp.name || comp.field || "";
|
||
return formEntries.some(
|
||
(entry) =>
|
||
(Boolean(compKey) && entry.key === compKey) ||
|
||
(Boolean(entry.label) && Boolean(comp.label) && entry.label === comp.label)
|
||
);
|
||
});
|
||
|
||
const linkageSources = matchedComponents.filter(
|
||
(comp) =>
|
||
Boolean(comp.assignmentRule) ||
|
||
(comp.type === "dataLink" && comp.isLinkageAssignment === true)
|
||
);
|
||
|
||
for (const src of linkageSources) {
|
||
const srcKey = src.name || src.field || src.label || "";
|
||
const overrideTargets = matchedComponents
|
||
.filter((comp) => (comp.name || comp.field || comp.label || "") !== srcKey)
|
||
.map((comp) => {
|
||
const list = comp.priorityList || comp.priority || [];
|
||
const linkage = list.find((p) => p.type === "LINKAGE_ASSIGNMENT");
|
||
const manual = list.find((p) => p.type === "MANUALLY_FILL_IN");
|
||
const linkagePriority = linkage?.priority ?? linkage?.value;
|
||
const manualPriority = manual?.priority ?? manual?.value;
|
||
if (
|
||
linkagePriority !== undefined &&
|
||
manualPriority !== undefined &&
|
||
linkagePriority > manualPriority
|
||
) {
|
||
return {
|
||
comp,
|
||
compKey: comp.name || comp.field || comp.label || "",
|
||
linkagePriority,
|
||
manualPriority,
|
||
};
|
||
}
|
||
return undefined;
|
||
})
|
||
.filter((item): item is NonNullable<typeof item> => Boolean(item));
|
||
|
||
if (overrideTargets.length > 0) {
|
||
const affectedDesc = overrideTargets
|
||
.map(
|
||
(t) =>
|
||
`${t.comp.label || t.compKey}(${t.compKey}: LINKAGE_ASSIGNMENT(${t.linkagePriority}) > MANUALLY_FILL_IN(${t.manualPriority}))`
|
||
)
|
||
.join("、");
|
||
addDiagnostic(diagnostics, {
|
||
severity: "warning",
|
||
code: "LINKAGE_PRIORITY_OVERRIDE",
|
||
path,
|
||
message: `表单模板 [${spec.name || spec.id}] 中字段 [${src.label || srcKey}] (${srcKey}) 存在业务对象联动配置 (isLinkageAssignment=${Boolean(src.isLinkageAssignment)}, assignmentRule=${src.assignmentRule || "-"}),且当前节点同时传入了 [${affectedDesc}],联动赋值优先级高于手动/API 传入,显式传入的值可能被关联对象中的字段值覆盖!`,
|
||
});
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
// 诊断 4: 触发器节点配置了无效的单据审批状态过滤 (DEADLOCK_TRIGGER_STATE_FILTER)
|
||
if (
|
||
(task.type === "ekuaibao-flowform-trigger" || task.type === "ekuaibao-ebot-trigger") &&
|
||
(task as Record<string, unknown>).combineFilters
|
||
) {
|
||
const rawFilters = JSON.stringify((task as Record<string, unknown>).combineFilters);
|
||
if (
|
||
rawFilters.includes('"key":"state"') &&
|
||
(rawFilters.includes('"APPROVING"') ||
|
||
rawFilters.includes('"approving"') ||
|
||
rawFilters.includes('"REJECTED"') ||
|
||
rawFilters.includes('"rejected"') ||
|
||
rawFilters.includes("被驳回") ||
|
||
rawFilters.includes("审批驳回"))
|
||
) {
|
||
addDiagnostic(diagnostics, {
|
||
severity: "error",
|
||
code: "DEADLOCK_TRIGGER_STATE_FILTER",
|
||
path,
|
||
message: `触发器节点 [${task.label || task.name}] (${task.name}) 配置了 state 状态过滤条件。合思单据审批出站事件属于动作事件(如 backlog.approving / flow.rejected),事件载荷中单据 state 字段在事件触发初始阶段可能为空或为大写英文 REJECTED,该过滤会导致出站事件被 100% 静默丢弃,下游审批流程永久无法触发!建议移除 state 过滤,改用通知类型(action)或后置条件节点。`,
|
||
});
|
||
}
|
||
}
|
||
|
||
// 诊断 5: 条件节点中单据审批状态过滤缺陷与纯文本枚举比对 (DEADLOCK_CONDITION_STATE_FILTER / INVALID_ACTION_ENUM_TEXT_VALUE)
|
||
if (task.type === "condition") {
|
||
const raw = task as Record<string, unknown>;
|
||
const filterSource = raw.combineFilters ?? raw.filters ?? raw.conditions ?? task.inputs;
|
||
if (filterSource) {
|
||
const leafFilters = extractLeafFilters(filterSource);
|
||
for (const leaf of leafFilters) {
|
||
const keyStr = String(leaf.key || "");
|
||
const valStr = typeof leaf.value === "string" ? leaf.value : JSON.stringify(leaf.value ?? "");
|
||
const isStateField =
|
||
keyStr === "state" ||
|
||
/"key":"state"/i.test(keyStr) ||
|
||
/"label":"[^"]*审批状态"/i.test(keyStr);
|
||
const isActionField =
|
||
keyStr === "action" ||
|
||
/"key":"action"/i.test(keyStr) ||
|
||
/"thirdId":"action"/i.test(keyStr) ||
|
||
/"label":"[^"]*通知类型"/i.test(keyStr);
|
||
|
||
if (isStateField && /被驳回|审批驳回|REJECTED|reject/i.test(valStr)) {
|
||
addDiagnostic(diagnostics, {
|
||
severity: "error",
|
||
code: "DEADLOCK_CONDITION_STATE_FILTER",
|
||
path,
|
||
message: `条件节点 [${task.label || task.name}] (${task.name}) 配置了使用单据审批状态 [state] 匹配驳回状态。合思单据出站事件为动作事件(Action Event),事件载荷中单据审批状态字段在事件触发初始阶段可能为空或为大写英文 REJECTED,使用中文 [被驳回/审批驳回] 匹配会导致条件 100% 判定为 false!建议改用触发器通知类型 [action],并在下拉选项中选中标准枚举宏(对应 code: flow.rejected)。`,
|
||
});
|
||
}
|
||
|
||
if (
|
||
isActionField &&
|
||
valStr &&
|
||
!valStr.includes("@{value(") &&
|
||
!valStr.includes("flow.") &&
|
||
!valStr.includes("freeflow.") &&
|
||
!valStr.includes("backlog.") &&
|
||
!valStr.includes("timeout.") &&
|
||
/被驳回|已支付|待审批|待支付|待收单|撤回|删除|催办/i.test(valStr)
|
||
) {
|
||
addDiagnostic(diagnostics, {
|
||
severity: "error",
|
||
code: "INVALID_ACTION_ENUM_TEXT_VALUE",
|
||
path,
|
||
message: `条件节点 [${task.label || task.name}] (${task.name}) 中通知类型 [action] 为 ENUM 枚举字段,但比对值被配置为了纯文本 [${valStr}]。Piper 运行时会使用底层英文枚举 Code (如 flow.rejected) 进行比对,纯文本将导致条件永远不匹配。请在条件节点右侧通过下拉列表选择标准枚举项。`,
|
||
});
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
// 诊断 5.3 条件节点空值安全(CONDITION_NULL_UNSAFE_COMPARE)
|
||
checkConditionNullSafety(task, path, ancestors, diagnostics);
|
||
|
||
// 诊断 6: HTTP 节点域名、中括号与功能权限校验
|
||
if (task.type === "http") {
|
||
const url = String((task as Record<string, unknown>).url || "");
|
||
|
||
// 6.1 拦截文档站点域名 docs.ekuaibao.com (DOCS_DOMAIN_USED)
|
||
if (url.includes("docs.ekuaibao.com")) {
|
||
addDiagnostic(diagnostics, {
|
||
severity: "error",
|
||
category: "hard_block",
|
||
code: "DOCS_DOMAIN_USED",
|
||
path,
|
||
message: `HTTP 任务 [${task.label || task.name}] (${task.name}) 的 URL 错误配置了开放平台文档站点域名 (docs.ekuaibao.com)。合思生产 API 网关域名为 app.ekuaibao.com,请求发往文档站点会导致 404/DNS 错误。请将 URL 修正为以 https://app.ekuaibao.com 开头的标准接口地址。`,
|
||
});
|
||
}
|
||
|
||
// 6.2 审批节点路径参数缺少中括号 (MISSING_BACKLOG_DATA_BRACKETS)
|
||
if (url.includes("api/openapi/v1/backlog/data")) {
|
||
const match = url.match(/api\/openapi\/v1\/backlog\/data\/([^?#]+)/);
|
||
const segment = match ? match[1] : "";
|
||
if (segment && (!segment.startsWith("[") || !segment.includes("]"))) {
|
||
addDiagnostic(diagnostics, {
|
||
severity: "warning",
|
||
category: "soft_advice",
|
||
code: "MISSING_BACKLOG_DATA_BRACKETS",
|
||
path,
|
||
message: `HTTP 自动审批节点 [${task.label || task.name}] 的 URL 路径参数缺少合思 OpenAPI 规范的方括号(规范要求: /api/openapi/v1/backlog/data/[{flowId}]),缺少方括号将导致服务端直接返回 404 Not Found。`,
|
||
});
|
||
}
|
||
}
|
||
|
||
// 6.3 开放接口 → 所需企业应用 开通状态校验
|
||
//
|
||
// ── 判定边界(重要,别放宽)────────────────────────────────────
|
||
// 1. 只对 HTTP 节点生效;
|
||
// 2. 只对「能静态读出接口路径」的 URL 生效 —— URL 若整体由上游节点
|
||
// 变量拼接(以 @{...} 开头),运行前无人知道会打到哪个接口,
|
||
// 一律跳过,不做任何猜测性告警;
|
||
// 3. 路径必须命中 OPENAPI_APP_REQUIREMENTS 里的已知映射才判断。
|
||
//
|
||
// 真实事故驱动:任子行「单据审批」应用未开通,流程跑到第 9 步才被网关
|
||
// 403「未开通功能,无权访问」拦下,而 403 报文里完全看不出缺哪个应用。
|
||
//
|
||
// 优先级:节点自己显式声明的 powerCode(params / URL query)优先;
|
||
// 没有显式声明时,才用接口路径去反查所需应用。
|
||
const httpMethod = String((task as Record<string, unknown>).method || "");
|
||
|
||
const paramPowerCodes: string[] = [];
|
||
const rawParams = (task as Record<string, unknown>).params;
|
||
if (Array.isArray(rawParams)) {
|
||
for (const param of rawParams) {
|
||
if (!param || typeof param !== "object") continue;
|
||
const entry = param as { key?: unknown; value?: unknown };
|
||
if (String(entry.key ?? "").trim().toLowerCase() !== "powercode") continue;
|
||
if (typeof entry.value !== "string") continue;
|
||
const value = entry.value.trim();
|
||
if (value) paramPowerCodes.push(value);
|
||
}
|
||
}
|
||
|
||
let urlPowerCode: string | undefined;
|
||
let powerCodeEncodingBroken = false;
|
||
const powerCodeMatch = url.match(/[?&]powerCode=([^&#]+)/);
|
||
if (powerCodeMatch) {
|
||
try {
|
||
urlPowerCode = decodeURIComponent(powerCodeMatch[1]);
|
||
} catch {
|
||
powerCodeEncodingBroken = true;
|
||
addDiagnostic(diagnostics, {
|
||
severity: "error",
|
||
category: "hard_block",
|
||
code: "INVALID_POWER_CODE_ENCODING",
|
||
path,
|
||
message: `HTTP 任务 [${task.label || task.name}] (${task.name}) 的 URL 中 powerCode 参数包含无效的百分号转义 [${powerCodeMatch[1]}],无法校验功能权限。请修正为有效的 URL 编码。`,
|
||
});
|
||
}
|
||
}
|
||
|
||
const explicitPowerCodes = powerCodeEncodingBroken
|
||
? []
|
||
: Array.from(
|
||
new Map(
|
||
[...paramPowerCodes, ...(urlPowerCode ? [urlPowerCode] : [])].map(
|
||
(code) => [code.trim().toLowerCase(), code.trim()] as const
|
||
)
|
||
).values()
|
||
).filter(Boolean);
|
||
|
||
// 没有显式声明、或显式声明的正是该接口要求的那一个 → 走「接口路径反查」,
|
||
// 这样报文里能带上应用名、productId 与判定依据路径(比只有 powerCode 更好排查)。
|
||
// 显式声明了别的 powerCode 时以声明为准,避免两套规则打架。
|
||
const matched = powerCodeEncodingBroken ? null : matchAppRequirement(url, httpMethod);
|
||
const preferPathRule =
|
||
matched !== null &&
|
||
(explicitPowerCodes.length === 0 ||
|
||
explicitPowerCodes.some(
|
||
(code) => code.toLowerCase() === matched.requirement.powerCode.toLowerCase()
|
||
));
|
||
|
||
if (matched && preferPathRule) {
|
||
// 6.3.1 按接口路径反查所需应用。
|
||
const { requirement, staticPath } = matched;
|
||
const powerCodeKey = requirement.powerCode.trim().toLowerCase();
|
||
const where = requirement.productId
|
||
? `「${requirement.appName}」(productId=${requirement.productId})`
|
||
: `「${requirement.appName}」`;
|
||
const evidence = `判定依据:URL 静态路径 '${staticPath}'`;
|
||
const methodLabel = httpMethod ? `${httpMethod.toUpperCase()} ` : "";
|
||
const hintSuffix = requirement.hint ? ` ${requirement.hint}` : "";
|
||
const declaredNote = explicitPowerCodes.length
|
||
? `(节点 ${paramPowerCodes.length ? "params" : "URL query"} 中已显式声明 powerCode=${requirement.powerCode})`
|
||
: "";
|
||
|
||
if (openedPowerCodeSet === undefined) {
|
||
addDiagnostic(diagnostics, {
|
||
severity: "warning",
|
||
category: "soft_advice",
|
||
code: "POWER_CODE_DEPENDENCY",
|
||
path,
|
||
message: `HTTP 任务 [${task.label || task.name}] (${task.name}) 调用的接口 [${requirement.apiName}](${methodLabel}${staticPath}…)属于${where}的开放能力,需要权限代码 powerCode=${requirement.powerCode}${declaredNote}。当前未提供企业已开通应用清单,无法确认是否可用;若未开通,运行时将返回 403 Forbidden。${evidence}。${hintSuffix}`,
|
||
});
|
||
} else if (!openedPowerCodeSet.has(powerCodeKey)) {
|
||
addDiagnostic(diagnostics, {
|
||
severity: "error",
|
||
category: "hard_block",
|
||
code: "UNLICENSED_POWER_CODE",
|
||
path,
|
||
message: `HTTP 任务 [${task.label || task.name}] (${task.name}) 调用的接口 [${requirement.apiName}](${methodLabel}${staticPath}…)属于${where}的开放能力${declaredNote},但当前企业尚未开通该应用(powerCode=${requirement.powerCode})。运行时合思开放平台网关将直接返回 403 Forbidden(未开通功能,无权访问),且报文不会提示缺哪个应用。请先在应用商店开通「${requirement.appName}」(或更换为已开通的等价接口)后重新发布。${evidence}。${hintSuffix}`,
|
||
});
|
||
}
|
||
} else if (explicitPowerCodes.length > 0) {
|
||
// 6.3.2 节点显式声明了该接口之外的 powerCode,以显式声明为准
|
||
for (const powerCode of explicitPowerCodes) {
|
||
const powerCodeKey = powerCode.toLowerCase();
|
||
const appName = WELL_KNOWN_POWER_CODES[powerCodeKey] || `权限代码 [${powerCode}] 对应的应用`;
|
||
const sourceHint = paramPowerCodes.includes(powerCode) ? "params" : "URL query";
|
||
|
||
if (openedPowerCodeSet !== undefined) {
|
||
if (!openedPowerCodeSet.has(powerCodeKey)) {
|
||
addDiagnostic(diagnostics, {
|
||
severity: "error",
|
||
category: "hard_block",
|
||
code: "UNLICENSED_POWER_CODE",
|
||
path,
|
||
message: `HTTP 任务 [${task.label || task.name}] (${task.name}) 携带了权限代码 'powerCode=${powerCode}'(声明于 ${sourceHint}),但当前企业尚未开通对应功能/应用(如 ${appName})。运行时合思开放平台网关将直接返回 403 Forbidden(未开通功能,无权访问)。请先在开放平台/应用商城中开通该应用,或更换为已开通的等价接口。`,
|
||
});
|
||
}
|
||
} else {
|
||
addDiagnostic(diagnostics, {
|
||
severity: "warning",
|
||
category: "soft_advice",
|
||
code: "POWER_CODE_DEPENDENCY",
|
||
path,
|
||
message: `HTTP 任务 [${task.label || task.name}] (${task.name}) 携带了权限代码 'powerCode=${powerCode}'(声明于 ${sourceHint})。调用此接口要求企业已开通 [${appName}],否则运行时将返回 403 Forbidden。`,
|
||
});
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
// 诊断 5: 字段变量引用失效校验 (BROKEN_CHOOSE_REFERENCE / BROKEN_LOOP_ITEM_REFERENCE)
|
||
const inspectFields: Array<{ key: string; value: string }> = [];
|
||
const rawTask = task as Record<string, unknown>;
|
||
for (const key of ["inputs", "fields", "mapping", "form", "combineFilters", "filters", "conditions", "flowCode", "list", "details"]) collectExpressionValues(rawTask[key], key, inspectFields);
|
||
|
||
for (const field of inspectFields) {
|
||
if (typeof field.value === "string") {
|
||
const chooseList = extractChooseTags(field.value);
|
||
for (const item of chooseList) {
|
||
const chooseKey = item.key;
|
||
if (!chooseKey) {
|
||
addDiagnostic(diagnostics, {
|
||
severity: item.invalidDescriptor ? "error" : "warning",
|
||
code: item.invalidDescriptor ? "INVALID_CHOOSE_DESCRIPTOR" : "UNRESOLVED_CHOOSE_REFERENCE", path,
|
||
message: item.invalidDescriptor
|
||
? `字段 [${field.key}] 的 choose 节点描述损坏:${item.problem}。请检查多余括号、JSON 转义和节点 key。`
|
||
: `字段 [${field.key}] 的引用无法静态检查:${item.problem}。请在真实流程设计器中确认。`,
|
||
});
|
||
continue;
|
||
}
|
||
const segments = chooseKey.split(".");
|
||
const root = segments[0];
|
||
const rootTask = taskNameMap.get(root);
|
||
|
||
// 5.1 循环内使用了旧版已弃用的 control_xxx.$item 语法,前端无法解析
|
||
if (segments[1] === "$item" && (item.descriptor || rootTask?.type === "every" || root.startsWith("control_"))) {
|
||
const baseNodeKey = root;
|
||
addDiagnostic(diagnostics, {
|
||
severity: "error",
|
||
category: "hard_block",
|
||
code: "BROKEN_LOOP_ITEM_REFERENCE",
|
||
path,
|
||
message: `字段 [${field.key || "未知"}] 引用了旧格式循环变量 '${chooseKey}'。新版合思流程设计器要求 key 必须指向循环节点 '${baseNodeKey}' 且 properties 中显式包含 { key: "$item", label: "单条数据", type: "MAP" },当前格式在前端页面将直接报错【引用变量不存在】并阻断保存发布。`,
|
||
});
|
||
continue;
|
||
}
|
||
|
||
// 5.2 引用了一个在当前工作流中根本不存在的上游节点
|
||
const sourceKey = item.descriptor ? chooseKey : root;
|
||
if (taskNameMap.has(sourceKey) || (!item.descriptor && CHOOSE_CONTEXT_ROOTS.has(root))) continue;
|
||
if (item.descriptor || /^(?:action|control|trigger)_/.test(root)) {
|
||
addDiagnostic(diagnostics, {
|
||
severity: "error",
|
||
category: "hard_block",
|
||
code: "BROKEN_CHOOSE_REFERENCE",
|
||
path,
|
||
message: `字段 [${field.key || "未知"}] 引用的上游节点 '${sourceKey}' 不存在于当前工作流中,前端设计器将报错【引用变量不存在】并阻断流程保存或运行。`,
|
||
});
|
||
} else {
|
||
addDiagnostic(diagnostics, {
|
||
severity: "warning", category: "soft_advice", code: "UNRESOLVED_CHOOSE_REFERENCE", path,
|
||
message: `字段 [${field.key}] 引用了 '${chooseKey}',无法静态确定根 '${root}' 是节点还是上下文;请在真实流程设计器中确认引用来源。`,
|
||
});
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
visit(task.tasks || [], path, insideEvery || task.type === "every", [...ancestors, task]);
|
||
});
|
||
};
|
||
|
||
visit(detail.tasks);
|
||
const hardBlocks = diagnostics.filter((d) => d.category === "hard_block").length;
|
||
const softAdvices = diagnostics.filter((d) => d.category === "soft_advice").length;
|
||
const summary: WorkflowAnalysisSummary = {
|
||
total: diagnostics.length,
|
||
hardBlocks,
|
||
softAdvices,
|
||
passed: hardBlocks === 0,
|
||
};
|
||
|
||
return {
|
||
workflow: {
|
||
id: detail.id,
|
||
label: detail.label,
|
||
state: detail.state,
|
||
version: detail.version,
|
||
},
|
||
ast,
|
||
dependencies,
|
||
diagnostics,
|
||
summary,
|
||
};
|
||
}
|