refactor: 将应用数据与工作流统一归入应用平台子模块

建立 applications 的应用模型和查询出口,保留基础及详情投影差异。
下沉 DataLink,将工作流模型、API、编排及执行上下文归回 workflow。
同步 CLI、SDK、生成脚本、测试和活跃文档引用,公开命令与 SDK 名称保持兼容。

验证:943 项测试、类型和版本检查通过;三份生成规范字节一致,README 审计通过。
This commit is contained in:
gitea committed 2026-10-30 16:56:09 +08:00
1 parent edf300b808
commit 4e03c9bcd7
107 files changed
+423 -496

No files matched your search

@@ -1,3 +1,5 @@
> 本模块归属自建应用平台;工作流模型、传输与编排现位于同级 `types.ts`、`api.ts`、`services.ts`,跨应用查询使用 applications 服务。上级入口见 [Platform 总览](../README.platform.md)。
# Workflow 工作流模块
Platform 域下工作流能力的命令、协议与诊断契约。总体边界见 [Platform 概览](../README.platform.md)。
@@ -1,4 +1,4 @@
import type { WorkflowDetail, WorkflowTask } from "../../types.js";
import type { WorkflowDetail, WorkflowTask } from "../types.js";
import type {
WorkflowAnalysis,
WorkflowAstNode,
@@ -1,5 +1,5 @@
import { describe, expect, test } from "bun:test";
import type { WorkflowDetail, WorkflowTask } from "../../types.js";
import type { WorkflowDetail, WorkflowTask } from "../types.js";
import { analyzeWorkflow } from "./analyzer.js";
const selector = (key: unknown, label?: unknown) => `@{value('${JSON.stringify({ key, label })}')}`;
@@ -1,6 +1,6 @@
import { describe, expect, it } from "bun:test";
import { analyzeWorkflow } from "./index.js";
import { PlatformSchema } from "../../types.js";
import { PlatformSchema } from "../../applications/types.js";
describe("Workflow static analysis", () => {
it("accepts nullable app center metadata", () => {
+40
View File
@@ -0,0 +1,40 @@
import { describe, expect, it } from "bun:test";
import { getWorkflowSnapshot, updateWorkflowChooses } from "./api.js";
describe("workflow snapshot API", () => {
it("uses the piper pipelines/snapshot endpoint first", async () => {
const calls: string[] = [];
const client = {
get: async (path: string) => {
calls.push(path);
if (path === "api/easo/pipelines/snapshot/snap-1") {
return new Response(JSON.stringify({
code: 200,
data: { id: "snap-1", pipelineId: "pipe-1", version: "26.10.7" },
}), { status: 200, headers: { "content-type": "application/json" } });
}
throw new Error("unexpected path");
},
} as any;
const snapshot = await getWorkflowSnapshot(client, "snap-1", "pipe-1");
expect(calls).toEqual(["api/easo/pipelines/snapshot/snap-1"]);
expect(snapshot.id).toBe("snap-1");
expect(snapshot.version).toBe("26.10.7");
});
it("refreshes chooses after the pipeline save", async () => {
const calls: string[] = [];
const client = {
put: async (path: string) => {
calls.push(path);
return new Response(JSON.stringify({ code: 200, data: [] }), { status: 200, headers: { "content-type": "application/json" } });
},
} as any;
await updateWorkflowChooses(client, "pipe-1");
expect(calls).toEqual(["api/easo/pipelines/pipe-1/chooses"]);
});
});
+531
View File
@@ -0,0 +1,531 @@
import { z } from "zod";
import ky, { KyInstance } from "ky";
import { AuthenticationError, BusinessError, EkbApiError } from "../../../core/errors.js";
import {
WorkflowPageSchema,
WorkflowStatsSchema,
WorkflowChargeSchema,
WorkflowDetailSchema,
WorkflowSnapshotSchema,
WorkflowSnapshotPageSchema,
WorkflowLogPageSchema,
WorkflowJobSchema,
WorkflowJobDetailSchema,
WorkflowTaskExecutionSchema,
WorkflowExecutionPageSchema,
WorkflowExecutionLogSchema,
WorkflowDslSchema,
WorkflowDslCatalogSchema,
StaffSchema,
WebhookInfoSchema,
WorkflowSampleDataSchema,
WorkflowSampleDataResultSchema,
type WorkflowSampleDataResult,
WorkflowDebugSourceResultSchema,
WorkflowEnumItemSchema,
type WorkflowEnumItem,
} from "./types.js";
import type { WorkflowState } from "./types.js";
function throwEasoResponseError(response: Response, record?: Record<string, unknown>): never {
const code = record?.code;
const status = typeof code === "number" ? code : response.status || 500;
const urlInfo = response.url ? ` [${response.url}]` : "";
const reason =
(typeof record?.msg === "string" && record.msg.trim()) ||
(typeof record?.errorMessage === "string" && record.errorMessage.trim()) ||
(typeof record?.message === "string" && record.message.trim()) ||
"服务端返回空数据 (可能凭证已过期或无该自建应用权限)";
const fullMsg = `EASO/Piper API 请求失败 (HTTP ${response.status || status}${urlInfo}): ${reason}`;
if (status === 401 || status === 403 || Number(code) === 401 || Number(code) === 403) {
throw new AuthenticationError(fullMsg);
}
throw new EkbApiError(fullMsg, "EASO_API_ERROR", status);
}
function checkEasoResponse(response: Response, raw: unknown) {
const record =
raw !== null && typeof raw === "object" && !Array.isArray(raw)
? (raw as Record<string, unknown>)
: undefined;
const code = record?.code;
const hasCodeError = code !== undefined && code !== null && Number(code) !== 200;
if (hasCodeError) throwEasoResponseError(response, record);
return { raw, record };
}
async function readEasoResponse(response: Response) {
return checkEasoResponse(response, await response.json());
}
/** 无返回值的写接口也要检查业务码;兼容 204 与空成功响应。 */
async function readEasoWriteResponse(response: Response): Promise<void> {
const text = await response.text();
if (response.ok === false) throwEasoResponseError(response);
if (!text.trim()) return;
let raw: unknown;
try { raw = JSON.parse(text); }
catch { throw new EkbApiError("EASO/Piper 写接口返回无效 JSON", "EASO_RESPONSE_INVALID", 502); }
checkEasoResponse(response, raw);
}
// Helper to unwrap { data: T } / { value: T } response with null/error defense
export async function unwrap<T>(response: Response, schema: z.ZodType<T>): Promise<T> {
const { raw, record } = await readEasoResponse(response);
const hasWrapper = Boolean(record && ("data" in record || "value" in record));
const payload = hasWrapper ? (record!.data ?? record!.value) : raw;
if (payload === null || payload === undefined) throwEasoResponseError(response, record);
return schema.parse(payload);
}
// Helper for simple success responses
async function ok(response: Response): Promise<{ success: boolean }> {
return { success: response.status === 200 };
}
// ── 工作流(EASO)─────────────────────────────────────────────────────────────
// 注意:EASO 客户端已自动注入 corpId,无需再传
export async function listWorkflows(
client: KyInstance,
platformId: string,
page: number = 1,
pageSize: number = 20
): Promise<import("./types.js").WorkflowPage> {
const response = await client.get("api/easo/pipelines/logs", {
searchParams: {
platformId,
number: String(page),
pageSize: String(pageSize),
},
});
return unwrap(response, WorkflowPageSchema);
}
export async function getWorkflowStats(
client: KyInstance,
platformId: string
): Promise<import("./types.js").WorkflowStats> {
const response = await client.get("api/easo/stats", {
searchParams: { platformId },
});
return unwrap(response, WorkflowStatsSchema);
}
export async function getWorkflowCharge(
client: KyInstance
): Promise<import("./types.js").WorkflowCharge> {
const response = await client.get("api/easo/charge");
return unwrap(response, WorkflowChargeSchema);
}
// ── 工作流详情(Piper)────────────────────────────────────────────────────────
export async function getWorkflowDetail(
client: KyInstance,
pipelineId: string
): Promise<import("./types.js").WorkflowDetail> {
const response = await client.get(`api/easo/pipelines/${pipelineId}`);
return unwrap(response, WorkflowDetailSchema);
}
// ── 工作流草稿保存(Piper)───────────────────────────────────────────────────
// Web 端“保存更新”会把完整 pipeline 原样 PUT 回服务端;节点不是独立资源。
export async function updateWorkflow(
client: KyInstance,
workflow: import("./types.js").WorkflowDetail
): Promise<import("./types.js").WorkflowDetail> {
const response = await client.put(`api/easo/pipelines/${workflow.id}`, {
json: workflow,
});
return unwrap(response, WorkflowDetailSchema);
}
/**
* 前端“保存更新”在主线 PUT 之后还会调用该接口(无 body),
* 由平台重新生成 choose/描述元数据;CLI 保存必须保持一致,否则内置节点 desc 会变成「」。
*/
export async function updateWorkflowChooses(
client: KyInstance,
pipelineId: string
): Promise<void> {
const response = await client.put(`api/easo/pipelines/${pipelineId}/chooses`);
await readEasoWriteResponse(response);
}
export async function copyWorkflow(
client: KyInstance,
pipelineId: string,
workflow: import("./types.js").WorkflowDetail
): Promise<import("./types.js").WorkflowDetail> {
const response = await client.put(`api/easo/pipelines/${pipelineId}/copy`, {
json: workflow,
});
return unwrap(response, WorkflowDetailSchema);
}
export async function createWorkflow(
client: KyInstance,
workflow: Record<string, any>
): Promise<import("./types.js").WorkflowDetail> {
const response = await client.post("api/easo/pipelines", {
json: workflow,
});
return unwrap(response, WorkflowDetailSchema);
}
export async function deleteWorkflow(
client: KyInstance,
pipelineId: string
): Promise<boolean> {
const response = await client.delete(`api/easo/pipelines/${pipelineId}`);
await readEasoWriteResponse(response);
return true;
}
export async function listWorkflowSnapshots(
client: KyInstance,
pipelineId: string,
page: number = 1,
pageSize: number = 10
): Promise<import("./types.js").WorkflowSnapshotPage> {
const response = await client.get(`api/easo/pipelines/${pipelineId}/snapshots`, {
searchParams: { number: String(page), pageSize: String(pageSize) },
});
return unwrap(response, WorkflowSnapshotPageSchema);
}
export async function getWorkflowSnapshot(
client: KyInstance,
snapshotId: string,
pipelineId?: string
): Promise<import("./types.js").WorkflowSnapshot> {
const paths = [
// 前端实际使用的快照接口:pipelines/snapshot/{id}
`api/easo/pipelines/snapshot/${snapshotId}`,
`api/easo/snapshots/${snapshotId}`,
...(pipelineId ? [`api/easo/pipelines/${pipelineId}/snapshots/${snapshotId}`] : []),
];
let lastError: unknown;
for (const path of paths) {
try {
const response = await client.get(path);
return unwrap(response, WorkflowSnapshotSchema);
} catch (error) {
lastError = error;
}
}
throw lastError instanceof Error ? lastError : new Error(String(lastError));
}
export async function listWorkflowLogs(
client: KyInstance,
pipelineId: string,
options: {
state?: string;
page?: number;
pageSize?: number;
startTime?: string;
endTime?: string;
} = {},
): Promise<import("./types.js").WorkflowLogPage> {
const response = await client.get(`api/easo/pipelines/${pipelineId}/log`, {
searchParams: {
state: options.state ?? "",
number: String(options.page ?? 1),
pageSize: String(options.pageSize ?? 10),
...(options.startTime ? { startTime: options.startTime } : {}),
...(options.endTime ? { endTime: options.endTime } : {}),
},
});
return unwrap(response, WorkflowLogPageSchema);
}
// ── 工作流启停(Piper)────────────────────────────────────────────────────────
export async function toggleWorkflow(
client: KyInstance,
pipelineId: string,
state: WorkflowState
): Promise<{ success: boolean }> {
const response = await client.put(`api/easo/pipelines/state/${pipelineId}`, {
searchParams: { state: String(state) },
});
return ok(response);
}
// ── 运行中的任务与单次 Job 执行详情(Piper)────────────────────────────────────
export async function listRunningJobs(
client: KyInstance,
pipelineId: string,
runType: "DEBUG" | "PROD" = "DEBUG"
): Promise<import("./types.js").WorkflowJob[]> {
const response = await client.get("api/easo/jobs/running", {
searchParams: { pipelineId, runType },
});
const { record } = await readEasoResponse(response);
const rawData = record?.data;
if (!rawData) return [];
if (Array.isArray(rawData)) {
return z.array(WorkflowJobSchema).parse(rawData);
}
if (typeof rawData === "object") {
return [WorkflowJobSchema.parse(rawData)];
}
return [];
}
export async function getJob(
client: KyInstance,
jobId: string
): Promise<import("./types.js").WorkflowJobDetail> {
const response = await client.get(`api/easo/jobs/${jobId}`);
return unwrap(response, WorkflowJobDetailSchema);
}
export async function getJobExecutionTree(
client: KyInstance,
jobId: string,
options: { page?: number; pageSize?: number } = {}
): Promise<import("./types.js").WorkflowTaskExecution[]> {
const response = await client.get(`api/easo/jobs/${jobId}/execution`, {
searchParams: {
number: String(options.page ?? 1),
pageSize: String(options.pageSize ?? 100),
},
});
const parsed = await unwrap(
response,
z.union([z.array(WorkflowTaskExecutionSchema), WorkflowExecutionPageSchema])
);
return Array.isArray(parsed) ? parsed : parsed.items;
}
export async function getJobFailedExecutions(
client: KyInstance,
jobId: string
): Promise<import("./types.js").WorkflowExecutionPage> {
const response = await client.get(`api/easo/jobs/${jobId}/execution/level/failed`);
const parsed = await unwrap(
response,
z.union([WorkflowExecutionPageSchema, z.array(WorkflowTaskExecutionSchema)])
);
if (Array.isArray(parsed)) {
return {
number: 1,
size: parsed.length,
totalPages: 1,
totalItems: parsed.length,
items: parsed,
};
}
return parsed;
}
export async function getJobExecutionLevel(
client: KyInstance,
jobId: string,
options: { parentId: string; page?: number; pageSize?: number }
): Promise<import("./types.js").WorkflowExecutionPage> {
const response = await client.get(`api/easo/jobs/${jobId}/execution/level`, {
searchParams: {
parentId: options.parentId,
number: String(options.page ?? 1),
pageSize: String(options.pageSize ?? 20),
},
});
return unwrap(response, WorkflowExecutionPageSchema);
}
export async function getExecutionLogs(
client: KyInstance,
executionId: string
): Promise<import("./types.js").WorkflowExecutionLog[]> {
const response = await client.get(`api/easo/executions/${executionId}/logs`);
const parsed = await unwrap(
response,
z.union([
z.array(WorkflowExecutionLogSchema),
z.object({ items: z.array(WorkflowExecutionLogSchema).default([]) }).passthrough(),
])
);
return Array.isArray(parsed) ? parsed : parsed.items;
}
// ── DSL 配置(Piper)──────────────────────────────────────────────────────────
export async function listDsl(
client: KyInstance
): Promise<import("./types.js").WorkflowDsl[]> {
const response = await client.get("api/easo/dsl/all");
const raw = await response.json<any>();
const payload = raw?.data ?? raw;
if (Array.isArray(payload)) {
return payload.map((item) => WorkflowDslSchema.parse(item));
}
// 若是对象结构,将各分类下的 items 拍平返回
const allItems: any[] = [
...(payload?.action || []),
...(payload?.control || []),
...(payload?.trigger || []),
];
return allItems.map((item) => WorkflowDslSchema.parse(item));
}
export async function listDslCatalog(
client: KyInstance
): Promise<import("./types.js").WorkflowDslCatalog> {
const response = await client.get("api/easo/dsl/all");
const raw = await response.json<any>();
const payload = raw?.data ?? raw;
if (Array.isArray(payload)) {
return {
action: payload,
control: [],
trigger: [],
};
}
return WorkflowDslCatalogSchema.parse(payload || {});
}
// ── 员工列表(Piper)──────────────────────────────────────────────────────────
export async function listStaffs(
client: KyInstance,
external: boolean = false
): Promise<import("./types.js").Staff[]> {
const response = await client.get("api/easo/common/staffs", {
searchParams: { external: String(external) },
});
return unwrap(response, z.array(StaffSchema));
}
// ── Webhook 信息(Piper)──────────────────────────────────────────────────────
export async function getWebhookInfo(
client: KyInstance,
pipelineId: string
): Promise<import("./types.js").WebhookInfo> {
const response = await client.get(`api/webhook/${pipelineId}`);
return unwrap(response, WebhookInfoSchema);
}
// ── 测试/采样数据(Piper)─────────────────────────────────────────────────────
export async function sampleWorkflowData(
client: KyInstance,
pipelineId: string
): Promise<import("./types.js").WorkflowSampleData> {
const response = await client.post(`api/easo/pipelines/${pipelineId}/sampleData`);
return WorkflowSampleDataSchema.parse(await response.json());
}
// ── 调试数据源与发起调试(Piper)─────────────────────────────────────────────
export async function getWorkflowDebugSource(
client: KyInstance,
pipelineId: string,
options: { page?: number; pageSize?: number; keywords?: string } = {}
): Promise<import("./types.js").WorkflowDebugSourceResult> {
const response = await client.post(`api/easo/pipelines/${pipelineId}/debugSource`, {
json: {
number: options.page ?? 1,
pageSize: options.pageSize ?? 20,
...(options.keywords ? { keywords: options.keywords } : {}),
},
});
return unwrap(response, WorkflowDebugSourceResultSchema);
}
export async function triggerWorkflowDebug(
client: KyInstance,
pipelineId: string,
options: { entityId?: string; data?: Record<string, any>; autoPublish?: boolean; dataLimit?: number } = {}
): Promise<string> {
const response = await client.post("api/easo/jobs", {
json: {
pipelineId,
inputs: {
id: options.entityId ?? "",
...(options.data !== undefined ? { data: options.data } : {}),
$autoPublish: options.autoPublish ?? false,
},
dataLimit: options.dataLimit ?? 20,
},
});
const data = await unwrap(response, z.union([z.string(), z.number(), z.record(z.string(), z.any())]));
if (typeof data === "string") return data;
if (typeof data === "number") return String(data);
if (data && typeof data === "object" && "id" in data) return String(data.id);
if (data && typeof data === "object" && "jobId" in data) return String(data.jobId);
return String(data);
}
export async function getWorkflowSampleData(
client: KyInstance,
pipelineId: string,
type = "webhook"
): Promise<WorkflowSampleDataResult> {
const response = await client.post(`api/easo/pipelines/${pipelineId}/sampleData`, {
json: { type },
});
return unwrap(response, WorkflowSampleDataResultSchema);
}
// ── 工作流/Piper 条件与触发器枚举字典 ──────────────────────────────────────────
export async function getWorkflowEnumOptions(
client: KyInstance,
thirdId: string,
platformId?: string
): Promise<WorkflowEnumItem[]> {
const jsonBody = platformId ? { $platformId: platformId } : {};
const response = await client.post(
`api/easo/dsl/condition/select/EKB_ENUM?thirdId=${encodeURIComponent(thirdId)}`,
{
json: jsonBody,
}
);
return unwrap(response, z.array(WorkflowEnumItemSchema));
}
// ── 灰度节点开通网关 ──────────────────────────────────────────────────────────
export async function grantWorkflowNodesApi(options: {
token: string;
corpId: string;
nodes: string[];
baseUrl?: string;
}): Promise<import("./types.js").GrantWorkflowNodesResult> {
const payload = {
token: options.token,
corpId: options.corpId,
nodes: options.nodes.join(","),
...(options.baseUrl ? { baseUrl: options.baseUrl } : {}),
};
try {
const response = await ky.post("https://d9jxeccs5j.sealosgzg.site/hose-workflow-node", {
json: payload,
timeout: 30000,
});
const json = (await response.json()) as any;
const data = json?.data ?? {};
return {
success: Boolean(json?.success ?? true),
saved: Array.isArray(data.saved) ? data.saved : [],
skipped: Array.isArray(data.skipped) ? data.skipped : [],
rawMessage: json?.msg || json?.message || "",
};
} catch (err: any) {
const message = err?.message || String(err);
throw new EkbApiError(`灰度节点开通网关调用失败: ${message}`, "GATEWAY_ERROR", 502);
}
}
@@ -1,5 +1,5 @@
import type { WorkflowTaskExecution } from "../../types.js";
import { indexExecutionContexts } from "../../execution-context.js";
import type { WorkflowTaskExecution } from "../types.js";
import { indexExecutionContexts } from "../execution-context.js";
import type { ConditionBranchExplanation, ConditionRuleExplanation } from "./types.js";
export const OP_MAP: Record<string, string> = {
@@ -1,6 +1,6 @@
import { describe, expect, it } from "bun:test";
import { explainConditionBranches } from "./index.js";
import type { WorkflowTaskExecution } from "../../types.js";
import type { WorkflowTaskExecution } from "../types.js";
describe("Workflow Condition Branch Diagnosis", () => {
const choose = (property = "value") => `@{choose('${JSON.stringify({ key: "source", properties: [{ key: property }] })}')}`;
+1 -1
View File
@@ -5,7 +5,7 @@ import {
isWorkflowActionCode,
matchWorkflowAction,
resolveWorkflowEnumOptions,
} from "../services.js";
} from "./services.js";
import { analyzeWorkflow } from "./analysis/index.js";
describe("Workflow Action Enums & Diagnostics", () => {
@@ -0,0 +1,45 @@
import type { WorkflowTaskExecution } from "./types.js";
export interface ExecutionContext {
node: WorkflowTaskExecution;
key: string;
scope: string[];
loopPath: string;
}
/** Index real executions by parent task path, loop context and repeated occurrence. */
export function indexExecutionContexts(tree: WorkflowTaskExecution[]): ExecutionContext[] {
const result: ExecutionContext[] = [];
const entries = new Map<string, { node: WorkflowTaskExecution; parentId?: string }>();
const occurrences = new Map<string, number>();
function collect(node: WorkflowTaskExecution, parentId?: string) {
if (!node || !node.id || entries.has(node.id)) return;
entries.set(node.id, { node, parentId: String(node.parentId || parentId || "") || undefined });
for (const key of ["children", "subTasks", "items", "tasks"]) {
const children = node[key];
if (Array.isArray(children)) for (const child of children) collect(child, node.id);
}
}
for (const node of tree) collect(node);
const scopes = new Map<string, { parts: string[]; loopPath: string }>();
function scopeOf(id: string, visited = new Set<string>()): { parts: string[]; loopPath: string } {
const cached = scopes.get(id);
if (cached) return cached;
const entry = entries.get(id);
if (!entry || visited.has(id)) return { parts: [JSON.stringify(["unresolved-parent", id])], loopPath: "" };
visited.add(id);
const parent = entry.parentId ? scopeOf(entry.parentId, visited) : { parts: [], loopPath: "" };
const loopPath = String(entry.node.currentLoopPath ?? parent.loopPath);
const scope = { parts: [...parent.parts, JSON.stringify([entry.node.name || entry.node.type || "unnamed", loopPath])], loopPath };
scopes.set(id, scope);
return scope;
}
for (const { node } of entries.values()) {
const { parts, loopPath } = scopeOf(node.id);
const base = JSON.stringify(parts);
const occurrence = occurrences.get(base) ?? 0;
occurrences.set(base, occurrence + 1);
result.push({ node, key: `${base}#${occurrence}`, scope: parts.slice(0, -1), loopPath });
}
return result;
}
@@ -0,0 +1,52 @@
import { describe, expect, it } from "bun:test";
import { diffWorkflowJobs } from "./services.js";
import type { WorkflowJobDetail, WorkflowTaskExecution } from "./types.js";
const job = { id: "job", status: "COMPLETED" } as WorkflowJobDetail;
const node = (id: string, loop: string, status = "COMPLETED", value = 1): WorkflowTaskExecution => ({ id, name: "edit", type: "code", status, currentLoopPath: loop, inputs: { value } });
describe("workflow diff execution identities", () => {
it("compares every loop instance rather than only the first task name", () => {
const result = diffWorkflowJobs(job, [node("a0", "0"), node("a1", "1", "FAILED", 2)], job, [node("b0", "0"), node("b1", "1", "COMPLETED", 3)]);
expect(result.nodes).toHaveLength(2);
expect(result.summary.divergedNodesCount).toBe(1);
expect(result.summary.statusDiffCount).toBe(1);
expect(result.nodes.find(n => n.diverged)?.currentLoopPath).toBe("1");
});
it("preserves repeated attempts and identifies missing instances", () => {
const result = diffWorkflowJobs(job, [node("a0", "0"), node("a1", "0", "FAILED")], job, [node("b0", "0")]);
expect(result.nodes).toHaveLength(2);
expect(result.summary.divergedNodesCount).toBe(1);
});
it("uses the parent task path when repeated names occur in different branches", () => {
const tree = (prefix: string, value: number): WorkflowTaskExecution[] => [
{ id: prefix + "left", name: "left", type: "condition", status: "COMPLETED", children: [node(prefix + "a", "0")] },
{ id: prefix + "right", name: "right", type: "condition", status: "COMPLETED", children: [node(prefix + "b", "0", "COMPLETED", value)] },
];
const result = diffWorkflowJobs(job, tree("a", 1), job, tree("b", 2));
expect(result.nodes).toHaveLength(4);
expect(result.summary.divergedNodesCount).toBe(1);
});
it("counts output-only changes, including the singular output wire format", () => {
const result = diffWorkflowJobs(job, [{ ...node("a", "0"), output: { value: 1 } }], job, [{ ...node("b", "0"), output: { value: 2 } }]);
expect(result.summary.divergedNodesCount).toBe(1);
expect(result.nodes[0]?.outputsDiff).toEqual([{ field: "value", from: 1, to: 2 }]);
});
it("resolves flat parentId relationships even when siblings change order", () => {
const tree = (prefix: string, reversed: boolean): WorkflowTaskExecution[] => {
const children = [
{ ...node(prefix + "childA", "0", "COMPLETED", 1), parentId: prefix + "left" },
{ ...node(prefix + "childB", "0", "COMPLETED", 2), parentId: prefix + "right" },
];
return [...(reversed ? children.reverse() : children), { id: prefix + "left", name: "left", type: "condition", status: "COMPLETED" }, { id: prefix + "right", name: "right", type: "condition", status: "COMPLETED" }];
};
const result = diffWorkflowJobs(job, tree("a", false), job, tree("b", true));
expect(result.summary.divergedNodesCount).toBe(0);
expect(result.nodes).toHaveLength(4);
});
it("does not discard scalar output changes", () => {
const result = diffWorkflowJobs(job, [{ ...node("a", "0"), output: 1 }], job, [{ ...node("b", "0"), output: 2 }]);
expect(result.summary.divergedNodesCount).toBe(1);
expect(result.nodes[0]?.outputsDiff).toEqual([{ field: "$value", from: 1, to: 2 }]);
});
});
@@ -12,7 +12,7 @@ import {
displayNameLength,
isDisplayNameTooLong,
} from "./index.js";
import type { WorkflowDetail, WorkflowTask } from "../../types.js";
import type { WorkflowDetail, WorkflowTask } from "../types.js";
const mockWorkflow: WorkflowDetail = {
id: "wf_test_100",
@@ -1,4 +1,4 @@
import type { WorkflowTask } from "../../types.js";
import type { WorkflowTask } from "../types.js";
import type { LocatedWorkflowTask } from "./types.js";
/**
@@ -1,4 +1,4 @@
import type { WorkflowDetail, WorkflowTask } from "../../types.js";
import type { WorkflowDetail, WorkflowTask } from "../types.js";
import { NotFoundError, ValidationError } from "../../../../core/errors.js";
import { findWorkflowTask } from "./locator.js";
+1 -1
View File
@@ -1,4 +1,4 @@
import type { WorkflowTask } from "../../types.js";
import type { WorkflowTask } from "../types.js";
import type { FlattenedWorkflowTask } from "./types.js";
/**
+1 -1
View File
@@ -1,4 +1,4 @@
import type { WorkflowTask } from "../../types.js";
import type { WorkflowTask } from "../types.js";
export interface FlattenedWorkflowTask {
task: WorkflowTask;
@@ -0,0 +1,81 @@
import { describe, expect, it } from "bun:test";
import type { KyInstance } from "ky";
import { z } from "zod";
import { AuthenticationError, EkbApiError } from "../../../core/errors.js";
import { classifyCliError } from "../../../cli/errors.js";
import { listRunningJobs, unwrap } from "./api.js";
import { watchWorkflowPipeline } from "./watch/pipeline-watcher.js";
const responding = (body: unknown) => ({ get: async () => Response.json(body) }) as unknown as KyInstance;
describe("running jobs response contract", () => {
for (const code of [401, 403, "401", "403"]) {
it(`rejects business authentication failure ${JSON.stringify(code)} before empty-data normalization`, async () => {
await expect(listRunningJobs(responding({ code, data: null, msg: "session expired" }), "wf"))
.rejects.toBeInstanceOf(AuthenticationError);
await expect(listRunningJobs(responding({ code, data: { id: "job" } }), "wf"))
.rejects.toBeInstanceOf(AuthenticationError);
});
}
it("preserves the API error category and server message for other business failures", async () => {
await expect(listRunningJobs(responding({ code: 500, data: null, errorMessage: "backend failed" }), "wf"))
.rejects.toMatchObject({ name: "EkbApiError", code: "EASO_API_ERROR", status: 500, message: expect.stringContaining("backend failed") });
});
it("preserves successful null, missing, single-job and array responses", async () => {
for (const body of [{ code: 200, data: null }, { code: 200 }, { data: [] }]) {
expect(await listRunningJobs(responding(body), "wf")).toEqual([]);
}
const single = await listRunningJobs(responding({ code: 200, data: { jobId: "job" } }), "wf");
expect(single.map((job) => job.id)).toEqual(["job"]);
const array = await listRunningJobs(responding({ code: "200", data: [{ id: "one" }, { id: "two" }] }), "wf");
expect(array.map((job) => job.id)).toEqual(["one", "two"]);
});
it("does not relax unwrap's nonempty-detail requirement", async () => {
await expect(unwrap(Response.json({ code: 200, data: null }), z.unknown())).rejects.toBeInstanceOf(EkbApiError);
await expect(unwrap(Response.json({ code: "401", data: [] }), z.array(z.unknown()))).rejects.toBeInstanceOf(AuthenticationError);
expect(await unwrap(Response.json({ code: 200, value: { id: "detail" } }), z.object({ id: z.string() })))
.toEqual({ id: "detail" });
});
});
describe("running job watcher error propagation", () => {
function watcherClient(running: unknown, otherFailure = false) {
let logCalls = 0;
const client = { get: async (path: string) => {
if (path === "api/easo/jobs/running") return Response.json(running);
if (path.endsWith("/log")) {
logCalls++;
return Response.json({ code: 200, data: { jobList: logCalls > 1 || otherFailure ? [{ jobId: "job", status: "COMPLETED" }] : [] } });
}
if (path.endsWith("/execution/level/failed")) return Response.json({ data: { items: [] } });
if (path.endsWith("/execution")) return Response.json({ data: [] });
if (path === "api/easo/jobs/job") return Response.json({ data: { id: "job", pipelineId: "wf", status: "COMPLETED" } });
return Response.json({ data: { id: "wf", label: "workflow" } });
} } as unknown as KyInstance;
return { client, logCalls: () => logCalls };
}
for (const once of [true, false]) {
it(`propagates running-job authentication failure in ${once ? "snapshot" : "continuous"} mode`, async () => {
const fixture = watcherClient({ code: 401, data: null });
try {
await watchWorkflowPipeline(fixture.client, "wf", { once, timeoutMs: 500 });
throw new Error("watcher unexpectedly succeeded");
} catch (error) {
expect(error).toBeInstanceOf(AuthenticationError);
expect(classifyCliError(error).exitCode).toBe(11);
}
expect(fixture.logCalls()).toBe(once ? 0 : 1);
});
it(`retains non-authentication log fallback in ${once ? "snapshot" : "continuous"} mode`, async () => {
const fixture = watcherClient({ code: 500, data: null }, once);
const report = await watchWorkflowPipeline(fixture.client, "wf", { once, timeoutMs: 500 });
expect(report.totalJobsWatched).toBe(1);
expect(report.jobs[0]?.jobId).toBe("job");
});
}
});
+1 -1
View File
@@ -1,5 +1,5 @@
import { EkbError } from "../../../core/errors.js";
import type { WorkflowDetail } from "../types.js";
import type { WorkflowDetail } from "./types.js";
/** 主保存已经提交,后续元数据刷新失败。调用方必须保留已保存版本。 */
export class WorkflowSavePartialError extends EkbError {
@@ -7,7 +7,7 @@ import {
executeJavaScriptSandbox,
executeMvelSandbox,
} from "./index.js";
import type { WorkflowDetail } from "../../types.js";
import type { WorkflowDetail } from "../types.js";
describe("workflow-script - 本地静态语法校验与沙箱仿真引擎", () => {
describe("hasReturnStatement", () => {
@@ -1,4 +1,4 @@
import type { WorkflowTask } from "../../types.js";
import type { WorkflowTask } from "../types.js";
import type { ScriptIssue } from "./types.js";
import { hasMvelFinalExpression } from "./mvel-subset.js";
@@ -1,4 +1,4 @@
import type { WorkflowDetail, WorkflowTask } from "../../types.js";
import type { WorkflowDetail, WorkflowTask } from "../types.js";
import type { NodeScriptLintReport, WorkflowScriptLintReport, ScriptIssue } from "./types.js";
import { lintJavaScriptCode } from "./lint-js.js";
import { lintMvelCode, collectAllWorkflowNodeNames } from "./lint-mvel.js";
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,19 @@
import { expect, test } from "bun:test";
import { diffWorkflowSnapshots } from "./services.js";
for (const field of ["mapping", "inputs", "fields", "form", "header", "params", "onError", "customConfig"]) {
test(`snapshot diff includes ${field} changes`, () => {
const before = { id: "a", tasks: [{ name: "node", type: "http", [field]: { target: "old" } }] } as any;
const after = structuredClone(before); after.id = "b"; after.tasks[0][field] = { target: "new" };
const result = diffWorkflowSnapshots(before, after);
expect(result.summary.changedCount).toBe(1);
expect(result.modifiedTasks[0].configChanges).toContainEqual({ field, from: { target: "old" }, to: { target: "new" } });
});
}
test("snapshot diff detects reordered and reparented nodes without relying on saved index metadata", () => {
const a = { id: "a", tasks: [{ name: "first", type: "http" }, { name: "branch", type: "condition", tasks: [{ name: "child", type: "http" }] }] } as any;
const b = { id: "b", tasks: [{ name: "branch", type: "condition", tasks: [] }, { name: "first", type: "http" }, { name: "child", type: "http" }] } as any;
const diff = diffWorkflowSnapshots(a, b);
expect(diff.summary.changedCount).toBe(3);
expect(diff.modifiedTasks.find(t => t.taskName === "child")?.configChanges).toContainEqual({ field: "$path", from: "tasks.1.tasks.0", to: "tasks.2" });
expect(diffWorkflowSnapshots(a, structuredClone(a)).summary.changedCount).toBe(0);
});
@@ -8,8 +8,8 @@ import {
hasWorkflowVersionConflict,
patchWorkflowDraft,
} from "./index.js";
import { WorkflowDetailSchema } from "../../types.js";
import type { WorkflowDetail } from "../../types.js";
import { WorkflowDetailSchema } from "../types.js";
import type { WorkflowDetail } from "../types.js";
import {
getExecutionLogs,
getJob,
@@ -20,7 +20,7 @@ import {
listWorkflowSnapshots,
listWorkflowLogs,
toggleWorkflow,
} from "../../api.js";
} from "../api.js";
import {
extractFailureExecutions,
findExecutionNode,
@@ -28,7 +28,7 @@ import {
isTaskExecutionFailed,
updateWorkflow,
sanitizeWorkflowSnapshot,
} from "../../services.js";
} from "../services.js";
import { AuthenticationError, EkbApiError } from "../../../../core/errors.js";
import { WorkflowAlertStore } from "../alert/index.js";
import { mkdtempSync, readFileSync, rmSync } from "node:fs";
+1 -1
View File
@@ -1,5 +1,5 @@
import { NotFoundError, ValidationError } from "../../../../core/errors.js";
import type { WorkflowDetail } from "../../types.js";
import type { WorkflowDetail } from "../types.js";
export type WorkflowDraftStatus = "clean" | "dirty" | "saving" | "saved" | "partial" | "failed";
@@ -0,0 +1,62 @@
import { describe, expect, it } from "bun:test";
import { FieldMappingSchema, EkuaibaoDatalinkCreateTaskSchema } from "./types.js";
describe("FieldMappingSchema 字段映射验证与序列化", () => {
it("正确解析仅含 key 的映射项", () => {
const raw = { key: "E_field_1" };
const parsed = FieldMappingSchema.parse(raw);
expect(parsed.key).toBe("E_field_1");
expect(parsed.value).toBeUndefined();
});
it("正确保留 value 表达式,不被剥离丢失 (防止 Piper 报错金额/必填字段为空)", () => {
const raw = {
key: "E_e716b9f4b67179b1fbc0_费用金额",
value: "control_stssrn.item.amortizationAmount",
};
const parsed = FieldMappingSchema.parse(raw);
expect(parsed.key).toBe("E_e716b9f4b67179b1fbc0_费用金额");
expect(parsed.value).toBe("control_stssrn.item.amortizationAmount");
});
it("正确保留复杂对象/数组或数字类型的 value 与扩展属性", () => {
const raw = {
key: "E_nested_field",
value: { subKey: "action_1.output", defaultVal: 100 },
type: "relateEntity",
required: true,
};
const parsed = FieldMappingSchema.parse(raw);
expect(parsed.key).toBe("E_nested_field");
expect(parsed.value).toEqual({ subKey: "action_1.output", defaultVal: 100 });
expect((parsed as any).type).toBe("relateEntity");
expect((parsed as any).required).toBe(true);
});
it("在 EkuaibaoDatalinkCreateTaskSchema 节点中完整保留所有字段映射的 key 与 value", () => {
const node = {
name: "action_create_test",
label: "创建摊销台账",
type: "ekuaibao-datalink-create",
groupName: "DEFAULT",
orderIndex: 1,
levelIndex: [1],
status: "NORMAL",
mode: "NORMAL",
entityId: "e716b9f4b67179b1fbc0",
combineFilters: { condition: "AND", filters: [] },
filters: [],
fields: [
{ key: "E_e716b9f4b67179b1fbc0_name", value: "control_stssrn.item.title" },
{ key: "E_e716b9f4b67179b1fbc0_费用金额", value: "control_stssrn.item.amortizationAmount" },
{ key: "E_e716b9f4b67179b1fbc0_摊销月份", value: "control_stssrn.item.amortizationMonth" },
],
};
const parsed = EkuaibaoDatalinkCreateTaskSchema.parse(node);
expect(parsed.fields).toHaveLength(3);
expect(parsed.fields[0].value).toBe("control_stssrn.item.title");
expect(parsed.fields[1].value).toBe("control_stssrn.item.amortizationAmount");
expect(parsed.fields[2].value).toBe("control_stssrn.item.amortizationMonth");
});
});
+770
View File
@@ -0,0 +1,770 @@
import { z } from "zod";
// ── 工作流任务节点(递归、按类型区分)─────────────────────────────────────────
export const BaseTaskSchema = z.object({
name: z.string(),
type: z.string(),
label: z.string(),
desc: z.string().optional(),
groupName: z.string(),
orderIndex: z.number(),
levelIndex: z.array(z.number()),
status: z.string(),
displayName: z.string().optional(),
});
// 任务节点运行时类型(用于递归结构中的类型标注)
export interface WorkflowTask {
name: string;
type: string;
label?: string;
desc?: string;
groupName: string;
orderIndex: number;
levelIndex: number[];
status: string;
displayName?: string;
tasks?: WorkflowTask[];
[key: string]: any;
}
// 条件/过滤的递归结构:condition / combineFilters
export const FilterConditionSchema = z.object({
key: z.string(),
value: z.any().optional(),
compare: z.string(),
});
export const FilterGroupSchema: z.ZodType<any> = z.lazy(() =>
z.object({
filters: z.array(z.union([FilterConditionSchema, FilterGroupSchema])),
condition: z.string(),
})
);
// 字段映射条目的两种形态:只读 key 或 key-value 映射(保留 value 及其余配置项)
export const FieldMappingSchema = z.object({
key: z.string(),
value: z.any().optional(),
}).passthrough();
// 错误处理配置
export const OnErrorSchema = z.object({
defaultAction: z.string(),
});
// ── 控制节点 ─────────────────────────────────────────────────────────────────
export const ConditionTaskSchema: z.ZodType<WorkflowTask> = BaseTaskSchema.extend({
type: z.literal("condition"),
tasksMaxLevel: z.number(),
combineFilters: FilterGroupSchema,
tasks: z.lazy(() => z.array(WorkflowTaskSchema)),
});
export const EveryTaskSchema: z.ZodType<WorkflowTask> = BaseTaskSchema.extend({
type: z.literal("every"),
batch: z.boolean(),
batchSize: z.number().optional(),
mode: z.string(),
list: z.string(),
filters: z.array(z.any()),
tasksMaxLevel: z.number(),
tasks: z.lazy(() => z.array(WorkflowTaskSchema)),
});
// ── 触发器节点 ─────────────────────────────────────────────────────────────────
export const WebhookTaskSchema = BaseTaskSchema.extend({
type: z.literal("webhook"),
sampleId: z.string(),
params: z.array(z.object({ key: z.string(), value: z.string() })),
urlPath: z.string(),
});
// ── 动作节点 ─────────────────────────────────────────────────────────────────
export const StopTaskSchema = BaseTaskSchema.extend({
type: z.literal("stop"),
});
export const HttpTaskSchema = BaseTaskSchema.extend({
type: z.literal("http"),
method: z.string(),
url: z.string(),
bodyType: z.string().optional(),
bodyRaw: z.record(z.string(), z.any()).optional(),
header: z.array(z.any()),
params: z.array(z.object({ key: z.string(), value: z.string() })),
successCode: z.array(z.string()),
sampleData: z.record(z.string(), z.any()).optional(),
});
export const FlowDetailTaskSchema = BaseTaskSchema.extend({
type: z.literal("flow-detail"),
specificationId: z.string(),
mapping: z.union([
z.boolean(),
z.array(z.object({ key: z.string(), value: z.string() })),
]),
flowCode: z.string(),
});
export const CodeTaskSchema = BaseTaskSchema.extend({
type: z.literal("code"),
code: z.string(),
});
export const CodeJs2TaskSchema = BaseTaskSchema.extend({
type: z.literal("code-js2"),
code: z.string(),
mapping: z.array(z.object({ key: z.string(), value: z.string() })).optional(),
onError: OnErrorSchema.optional(),
});
export const EkuaibaoDatalinkFilterTaskSchema = BaseTaskSchema.extend({
type: z.literal("ekuaibao-datalink-filter"),
mode: z.string(),
entityId: z.string(),
fields: z.array(FieldMappingSchema),
filters: z.array(z.any()),
selectFields: z.array(z.any()),
combineFilters: FilterGroupSchema,
orderKey: z.string(),
orderMode: z.string(),
limitCount: z.string(),
onError: OnErrorSchema.optional(),
});
export const EkuaibaoDatalinkCreateTaskSchema = BaseTaskSchema.extend({
type: z.literal("ekuaibao-datalink-create"),
mode: z.string(),
entityId: z.string(),
fields: z.array(FieldMappingSchema),
filters: z.array(z.any()),
combineFilters: FilterGroupSchema,
});
export const DataConvertTaskSchema = BaseTaskSchema.extend({
type: z.literal("data-convert"),
mode: z.string(),
path: z.array(z.string()),
fields: z.array(z.object({ key: z.string(), value: z.string() })),
onError: OnErrorSchema.optional(),
subType: z.string(),
itemType: z.string(),
targetType: z.string(),
feeFormType: z.string(),
});
export const FlowCreateTaskSchema = BaseTaskSchema.extend({
type: z.literal("flow-create-task"),
specificationId: z.string(),
formState: z.string(),
form: z.record(z.string(), z.string()),
details: z.record(z.string(), z.any()),
onError: OnErrorSchema.optional(),
});
export const DynamicDelayTaskSchema = BaseTaskSchema.extend({
type: z.literal("task-dynamic-delay"),
sleepTime: z.union([z.number(), z.string()]).optional(),
});
// 兜底节点:遇到未收录类型时仍保留全部字段
export const UnknownTaskSchema = z
.object({
name: z.string().default("task"),
type: z.string(),
label: z.string().optional(),
desc: z.string().optional(),
groupName: z.string().default("trigger"),
orderIndex: z.number().default(0),
levelIndex: z.array(z.number()).default([0]),
status: z.string().default("active"),
displayName: z.string().optional(),
})
.passthrough();
// 统一任务节点类型
export const WorkflowTaskSchema: z.ZodType<WorkflowTask> = z.union([
WebhookTaskSchema,
ConditionTaskSchema,
EveryTaskSchema,
StopTaskSchema,
HttpTaskSchema,
FlowDetailTaskSchema,
CodeTaskSchema,
CodeJs2TaskSchema,
EkuaibaoDatalinkFilterTaskSchema,
EkuaibaoDatalinkCreateTaskSchema,
DataConvertTaskSchema,
FlowCreateTaskSchema,
DynamicDelayTaskSchema,
UnknownTaskSchema,
]);
// ── 工作流(EASO Pipeline)───────────────────────────────────
export const WorkflowSchema = z.object({
id: z.string(),
pipelineName: z.string().default(""),
state: z.number().default(0),
runningCount: z.number().default(0),
errorCount: z.number().default(0),
updateTime: z.string().default(""),
updateUser: z.string().nullable().optional(),
tasks: z.array(WorkflowTaskSchema).default([]),
desc: z.string().nullable().optional(),
customDesc: z.string().nullable().optional(),
});
export const WorkflowPageSchema = z.object({
pipelineNum: z.number().default(0),
runningNum: z.number().default(0),
allRunCount: z.number().default(0),
errorCount: z.number().default(0),
number: z.number().default(1),
size: z.number().default(20),
totalPages: z.number().default(0),
totalItems: z.number().default(0),
pipelineList: z.array(WorkflowSchema).default([]),
});
export const WorkflowStatsSchema = z.object({
total: z.number().default(0),
completed: z.number().default(0),
failed: z.number().default(0),
started: z.number().default(0),
pipelineOpenCount: z.number().default(0),
pipelineCloseCount: z.number().default(0),
pipelineAllCount: z.number().default(0),
});
export const WorkflowAlarmSchema = z.object({
alarmUser: z.array(z.any()).default([]),
alarmType: z.array(z.string()).default([]),
active: z.boolean().default(true),
alarmScope: z.string().default(""),
});
export const WorkflowDetailSchema = z.object({
id: z.string(),
label: z.string().default(""),
desc: z.string().nullable().optional(),
customDesc: z.string().nullable().optional(),
state: z.coerce.number().default(0),
debugState: z.coerce.number().default(0),
runTimes: z.coerce.number().default(0),
errorTimes: z.coerce.number().default(0),
updateTime: z.string().default(""),
updateUser: z.string().nullable().optional(),
staffName: z.string().nullable().optional(),
version: z.string().default(""),
dataLimit: z.coerce.number().default(20),
source: z.coerce.number().default(0),
queueJobs: z.boolean().default(false),
tasksVersion: z.coerce.number().default(0),
tasks: z.array(WorkflowTaskSchema).default([]),
alarm: z.union([
WorkflowAlarmSchema,
z.string().transform((val) => {
try {
const parsed = JSON.parse(val);
return WorkflowAlarmSchema.safeParse(parsed).data ?? undefined;
} catch {
return undefined;
}
}),
z.null(),
]).optional(),
inputs: z.array(z.object({ key: z.string(), value: z.any() })).optional(),
"$snapshot": z.array(z.object({ key: z.string(), value: z.string() })).optional(),
}).passthrough();
export const WorkflowSnapshotSchema = z.object({
id: z.string(),
pipelineId: z.string(),
corporationId: z.string().default(""),
platformId: z.string().default(""),
triggerKey: z.string().default(""),
label: z.string().default(""),
tasks: z.array(WorkflowTaskSchema).nullable().optional(),
inputs: z.union([z.string(), z.array(z.any())]).default("[]"),
outputs: z.union([z.string(), z.array(z.any())]).default("[]"),
retry: z.number().default(0),
state: z.number().default(0),
debugState: z.number().default(0),
staffId: z.string().nullable().optional(),
staffName: z.string().nullable().optional(),
createTime: z.string().default(""),
updateTime: z.string().default(""),
version: z.string().default(""),
}).passthrough();
export const WorkflowSnapshotPageSchema = z.object({
number: z.number().default(1),
size: z.number().default(10),
totalPages: z.number().default(0),
totalItems: z.number().default(0),
items: z.array(WorkflowSnapshotSchema).default([]),
});
export const WorkflowLogItemSchema = z.record(z.string(), z.any());
export const WorkflowLogPageSchema = z.object({
number: z.number().default(1),
size: z.number().default(10),
totalPages: z.number().default(0),
totalItems: z.number().default(0),
items: z.array(WorkflowLogItemSchema).default([]),
executeCount: z.number().default(0),
successCount: z.number().default(0),
errorCount: z.number().default(0),
jobList: z.array(WorkflowLogItemSchema).default([]),
}).passthrough();
export const WorkflowChargeSchema = z.object({
corporationId: z.string().default(""),
status: z.string().default(""),
orderType: z.string().default(""),
total: z.number().default(0),
used: z.number().default(0),
remaining: z.number().default(0),
});
// ── 运行中的任务与单次 Job 执行详情 ──────────────────────────────────────────
export const WorkflowJobSchema = z
.object({
id: z.string().optional(),
jobId: z.string().optional(),
pipelineId: z.string().nullish().default(""),
jobName: z.string().nullish(),
status: z.string().default(""),
runType: z.string().default(""),
executeTime: z.union([z.string(), z.number()]).nullish(),
startTime: z.union([z.string(), z.number()]).nullish(),
endTime: z.union([z.string(), z.number()]).nullish(),
triggerType: z.string().default(""),
successTaskCount: z.number().nullish().default(0),
errorTaskCount: z.number().nullish().default(0),
hasError: z.union([z.string(), z.boolean()]).nullish(),
state: z.union([z.number(), z.string()]).nullish(),
autoPublish: z.boolean().nullish(),
version: z.string().nullish(),
snapshotId: z.string().nullish(),
})
.passthrough()
.transform((val) => ({
...val,
id: val.id || val.jobId || "",
jobId: val.jobId || val.id || "",
pipelineId: val.pipelineId || "",
}));
export const WorkflowJobDetailSchema = z
.object({
id: z.string(),
pipelineId: z.string().default(""),
label: z.string().default(""),
status: z.string().default(""),
runType: z.string().default(""),
startTime: z.union([z.number(), z.string()]).nullable().optional(),
endTime: z.union([z.number(), z.string()]).nullable().optional(),
createTime: z.union([z.number(), z.string()]).nullable().optional(),
inputs: z.any().optional(),
outputs: z.any().optional(),
})
.passthrough();
export const WorkflowExecutionErrorSchema = z
.object({
message: z.string().default(""),
stackTrace: z.array(z.string()).nullish().transform((v) => v ?? []),
})
.passthrough();
export const WorkflowExecutionLogSchema = z
.object({
id: z.union([z.string(), z.number()]).optional(),
level: z.string().default("INFO"),
message: z.string().default(""),
createAt: z.union([z.string(), z.number()]).optional(),
})
.passthrough();
export const WorkflowTaskExecutionSchema = z
.object({
id: z.string(),
parentId: z.string().nullable().optional(),
jobId: z.string().optional(),
pipelineId: z.string().optional(),
name: z.string().optional(),
displayName: z.string().nullable().optional(),
label: z.string().nullable().optional(),
type: z.string().default(""),
orderIndex: z.number().optional(),
levelIndex: z.array(z.number()).optional(),
status: z.string().default(""),
executionTime: z.number().optional(),
startTime: z.union([z.number(), z.string()]).nullable().optional(),
endTime: z.union([z.number(), z.string()]).nullable().optional(),
createTime: z.union([z.number(), z.string()]).nullable().optional(),
currentLoopPath: z.string().nullable().optional(),
error: WorkflowExecutionErrorSchema.nullable().optional(),
output: z.any().optional(),
form: z.union([z.record(z.string(), z.any()), z.array(z.any())]).nullable().optional(),
details: z.record(z.string(), z.any()).nullable().optional(),
executionLogs: z.array(z.any()).optional(),
})
.passthrough();
export const WorkflowExecutionPageSchema = z
.object({
number: z.number().default(1),
size: z.number().default(20),
totalPages: z.number().default(0),
totalItems: z.number().default(0),
items: z
.array(z.union([WorkflowTaskExecutionSchema, z.array(WorkflowTaskExecutionSchema)]))
.default([])
.transform((arr) => arr.flat()),
})
.passthrough();
// ── DSL 配置 ─────────────────────────────────────────────────────────────────
export const WorkflowDslSchema = z.object({
id: z.string().optional(),
name: z.string().default(""),
type: z.string().default(""),
config: z.record(z.string(), z.any()).default({}),
});
export const WorkflowNodeDefinitionSchema = z
.object({
id: z.string().nullable().optional(),
name: z.string().default(""),
type: z.string().default(""),
groupName: z.string().nullable().optional(),
icon: z.string().nullable().optional(),
iconColor: z.string().nullable().optional(),
remark: z.string().nullable().optional(),
platform: z.string().nullable().optional(),
version: z.number().nullable().optional(),
$json: z.string().nullable().optional(),
})
.passthrough();
export type WorkflowNodeDefinition = z.infer<typeof WorkflowNodeDefinitionSchema>;
export const WorkflowDslCatalogSchema = z
.object({
action: z.array(WorkflowNodeDefinitionSchema).default([]),
control: z.array(WorkflowNodeDefinitionSchema).default([]),
trigger: z.array(WorkflowNodeDefinitionSchema).default([]),
})
.passthrough();
export type WorkflowDslCatalog = z.infer<typeof WorkflowDslCatalogSchema>;
export interface AvailableWorkflowNodes {
allTypes: Set<string>;
actionNodes: WorkflowNodeDefinition[];
controlNodes: WorkflowNodeDefinition[];
triggerNodes: WorkflowNodeDefinition[];
}
export interface GrantWorkflowNodesOptions {
nodes: string[];
password?: string;
}
export interface GrantWorkflowNodesResult {
success: boolean;
saved: string[];
skipped: string[];
rawMessage: string;
}
// ── 员工 ─────────────────────────────────────────────────────────────────────
export const StaffSchema = z.object({
id: z.string(),
name: z.string().default(""),
email: z.string().nullable().optional(),
department: z.string().nullable().optional(),
});
// ── Webhook ──────────────────────────────────────────────────────────────────
export const WebhookInfoSchema = z.object({
id: z.string(),
pipelineId: z.string(),
url: z.string().default(""),
active: z.boolean().default(true),
});
// ── 工作流状态 ────────────────────────────────────────────────────────────────
export const WorkflowStateSchema = z.union([z.literal(0), z.literal(1)]);
// ── 测试/采样数据 ─────────────────────────────────────────────────────────────
export const WorkflowSampleDataSchema = z.record(z.string(), z.any());
// ── 跨应用聚合结果类型 ───────────────────────────────────────────────────────
export const WorkflowSummarySchema = WorkflowSchema.extend({
platformId: z.string(),
platformName: z.string(),
});
export const WorkflowListAllErrorSchema = z.object({
platformId: z.string(),
platformName: z.string(),
error: z.string(),
});
export const TaskMatchSchema = z.object({
taskName: z.string(),
taskType: z.string(),
levelIndex: z.array(z.number()),
});
export const WorkflowWithMatchesSchema = WorkflowSummarySchema.extend({
matchedTasks: z.array(TaskMatchSchema),
});
// ── 类型导出 ──────────────────────────────────────────────────────────────────
export type FilterGroup = z.infer<typeof FilterGroupSchema>;
export type WorkflowState = z.infer<typeof WorkflowStateSchema>;
export type Workflow = z.infer<typeof WorkflowSchema>;
export type WorkflowPage = z.infer<typeof WorkflowPageSchema>;
export type WorkflowStats = z.infer<typeof WorkflowStatsSchema>;
export type WorkflowAlarm = z.infer<typeof WorkflowAlarmSchema>;
export type WorkflowDetail = z.infer<typeof WorkflowDetailSchema>;
export type WorkflowSnapshot = z.infer<typeof WorkflowSnapshotSchema>;
export type WorkflowSnapshotPage = z.infer<typeof WorkflowSnapshotPageSchema>;
export type WorkflowLogItem = z.infer<typeof WorkflowLogItemSchema>;
export type WorkflowLogPage = z.infer<typeof WorkflowLogPageSchema>;
export type WorkflowCharge = z.infer<typeof WorkflowChargeSchema>;
export type WorkflowJob = z.infer<typeof WorkflowJobSchema>;
export type WorkflowJobDetail = z.infer<typeof WorkflowJobDetailSchema>;
export type WorkflowExecutionError = z.infer<typeof WorkflowExecutionErrorSchema>;
export type WorkflowExecutionLog = z.infer<typeof WorkflowExecutionLogSchema>;
export type WorkflowTaskExecution = z.infer<typeof WorkflowTaskExecutionSchema>;
export type WorkflowExecutionPage = z.infer<typeof WorkflowExecutionPageSchema>;
export type WorkflowDsl = z.infer<typeof WorkflowDslSchema>;
export type Staff = z.infer<typeof StaffSchema>;
export type WebhookInfo = z.infer<typeof WebhookInfoSchema>;
export type WorkflowSampleData = z.infer<typeof WorkflowSampleDataSchema>;
export type WorkflowSummary = z.infer<typeof WorkflowSummarySchema>;
export type WorkflowListAllError = z.infer<typeof WorkflowListAllErrorSchema>;
export type TaskMatch = z.infer<typeof TaskMatchSchema>;
export type WorkflowWithMatches = z.infer<typeof WorkflowWithMatchesSchema>;
// ── 工作流快照与 Job 差异比对模型 ──────────────────────────────────────────
export interface TaskConfigDiff {
taskName: string;
displayName?: string;
type: string;
changeType: "ADDED" | "REMOVED" | "MODIFIED";
codeDiff?: {
from?: string;
to?: string;
unifiedDiff?: string;
};
filterDiff?: {
from?: unknown;
to?: unknown;
};
configChanges: Array<{
field: string;
from?: unknown;
to?: unknown;
}>;
}
export interface WorkflowSnapshotDiff {
snapshotA: {
id: string;
version?: string;
updateTime?: string;
staffName?: string;
};
snapshotB: {
id: string;
version?: string;
updateTime?: string;
staffName?: string;
};
addedTasks: string[];
removedTasks: string[];
modifiedTasks: TaskConfigDiff[];
summary: {
totalA: number;
totalB: number;
changedCount: number;
};
}
export interface NodeExecutionDiff {
taskName: string;
instanceKey?: string;
currentLoopPath?: string;
displayName?: string;
type?: string;
statusA?: string;
statusB?: string;
durationMsA?: number;
durationMsB?: number;
errorA?: unknown;
errorB?: unknown;
inputsDiff?: Array<{
field: string;
from?: unknown;
to?: unknown;
}>;
outputsDiff?: Array<{
field: string;
from?: unknown;
to?: unknown;
}>;
diverged: boolean;
}
export interface WorkflowJobDiff {
jobA: {
id: string;
pipelineId?: string;
state?: string | number;
startTime?: string;
durationTime?: number;
hasError?: boolean;
errorCount?: number;
};
jobB: {
id: string;
pipelineId?: string;
state?: string | number;
startTime?: string;
durationTime?: number;
hasError?: boolean;
errorCount?: number;
};
nodes: NodeExecutionDiff[];
summary: {
totalNodesA: number;
totalNodesB: number;
divergedNodesCount: number;
statusDiffCount: number;
};
}
// ── 调试数据源与测试结果 ───────────────────────────────────────────────────────
export const WorkflowDebugSourceItemSchema = z
.object({
id: z.string(),
title: z.string().default(""),
flowState: z.string().default(""),
})
.passthrough();
export const WorkflowDebugSourceResultSchema = z
.object({
type: z.string().default(""),
total: z.number().default(0),
items: z.array(WorkflowDebugSourceItemSchema).default([]),
fields: z.array(z.object({ key: z.string(), label: z.string() })).default([]),
label: z.string().default(""),
})
.passthrough();
export type WorkflowDebugSourceItem = z.infer<typeof WorkflowDebugSourceItemSchema>;
export type WorkflowDebugSourceResult = z.infer<typeof WorkflowDebugSourceResultSchema>;
export interface WorkflowTestReport {
jobId: string;
pipelineId: string;
status: string;
outcome: "completed" | "failed" | "timed_out" | "incomplete";
timedOut: boolean;
diagnosticsComplete: boolean;
diagnosticsErrors: Array<{ source: string; message: string }>;
runType: string;
durationTime?: number;
targetEntityId: string;
triggerCategory?: WorkflowTriggerCategory;
triggerType?: string;
triggerLabel?: string;
executionTree: WorkflowTaskExecution[];
failedExecutions: WorkflowTaskExecution[];
conditionDiagnoses: import("./branch/index.js").ConditionBranchExplanation[];
}
// ── 触发器元类型分类与智能路径路由 ───────────────────────────────────────────────
export type WorkflowTriggerCategory =
| "FLOW_FORM" // 单据审批流转类 (ekuaibao-flowform-trigger, ekuaibao-ebot-trigger, other-event-trigger, flow-change-trigger)
| "DATALINK" // 业务对象/台账变更类 (ekuaibao-datalink-create-trigger, ekuaibao-datalink-change-trigger, ekuaibao-datalink-time-trigger, datalink-button-trigger, ekuaibao-tmc-datalink-change-trigger)
| "SCHEDULE" // 定时调度类 (clock)
| "WEBHOOK" // 外部调用/网关集成类 (webhook, hab-trigger-task, xrxs-trigger, fxiaoke-trigger)
| "CUSTOM"; // 其他自定义触发器 (pipeline-running-trigger, pipeline-save-trigger 等)
export function classifyWorkflowTrigger(triggerType?: string): WorkflowTriggerCategory {
if (!triggerType) return "CUSTOM";
const t = triggerType.toLowerCase();
if (t === "clock" || t.includes("timer") || t.includes("schedule")) {
return "SCHEDULE";
}
if (t.includes("flowform") || t.includes("ebot") || t.includes("flow-") || t === "other-event-trigger" || t.includes("requisition")) {
return "FLOW_FORM";
}
if (t.includes("datalink") || t.includes("entity")) {
return "DATALINK";
}
if (t.includes("webhook") || t.includes("hab-trigger") || t.includes("xrxs") || t.includes("fxiaoke")) {
return "WEBHOOK";
}
return "CUSTOM";
}
// ── Webhook 数据样本 (Sample Data) ─────────────────────────────────────────────
export const WorkflowSampleRecordSchema = z.object({
id: z.string(),
corporationId: z.string().optional(),
pipelineId: z.string().optional(),
taskName: z.string().optional(),
actived: z.number().optional(),
dataJson: z.string(),
createTime: z.number(),
updateTime: z.number().optional(),
});
export type WorkflowSampleRecord = z.infer<typeof WorkflowSampleRecordSchema>;
export const WorkflowSampleDataResultSchema = z.object({
records: z.array(WorkflowSampleRecordSchema).default([]),
total: z.number().optional(),
size: z.number().optional(),
current: z.number().optional(),
});
export type WorkflowSampleDataResult = z.infer<typeof WorkflowSampleDataResultSchema>;
// ── 工作流/Piper 枚举选项 (EKB_ENUM) ──────────────────────────────────────────
export const WorkflowEnumItemSchema = z.object({
label: z.string(),
code: z.string(),
name: z.string().optional().default(""),
});
export type WorkflowEnumItem = z.infer<typeof WorkflowEnumItemSchema>;
@@ -1,4 +1,4 @@
import type { WorkflowJobDetail, WorkflowTaskExecution } from "../../types.js";
import type { WorkflowJobDetail, WorkflowTaskExecution } from "../types.js";
export const TERMINAL_STATES = new Set(["COMPLETED", "FAILED", "STOP", "STOPPED", "CANCELLED", "CANCELED"]);
@@ -9,7 +9,7 @@ import {
watchWorkflowPipeline,
type WorkflowWatchEvent,
} from "./index.js";
import type { WorkflowTaskExecution } from "../../types.js";
import type { WorkflowTaskExecution } from "../types.js";
describe("workflow-watch - 实时监控与日志流跟踪引擎", () => {
describe("TaskExecutionTracker", () => {
@@ -1,6 +1,6 @@
import type { KyInstance } from "ky";
import { AuthenticationError } from "../../../../core/errors.js";
import * as api from "../../api.js";
import * as api from "../api.js";
import type { WatchWorkflowOptions, WatchedJobResult, WorkflowWatchReport, WorkflowWatchEvent } from "./types.js";
import { normalizeJobStatus, isJobTerminal } from "./helpers.js";
import { watchSingleJob } from "./single-job.js";
@@ -1,6 +1,6 @@
import type { KyInstance } from "ky";
import type { WorkflowJobDetail, WorkflowTaskExecution } from "../../types.js";
import * as api from "../../api.js";
import type { WorkflowJobDetail, WorkflowTaskExecution } from "../types.js";
import * as api from "../api.js";
import type { WatchWorkflowOptions, WatchedJobResult, WorkflowWatchEvent } from "./types.js";
import { normalizeJobStatus, isJobTerminal } from "./helpers.js";
import { TaskExecutionTracker } from "./tracker.js";
@@ -1,5 +1,5 @@
import type { WorkflowTaskExecution } from "../../types.js";
import { flattenExecutionTree, isTaskExecutionFailed } from "../../services.js";
import type { WorkflowTaskExecution } from "../types.js";
import { flattenExecutionTree, isTaskExecutionFailed } from "../services.js";
import type { WorkflowWatchEvent } from "./types.js";
import { extractTaskErrorMessage } from "./helpers.js";
+1 -1
View File
@@ -1,4 +1,4 @@
import type { WorkflowJobDetail } from "../../types.js";
import type { WorkflowJobDetail } from "../types.js";
export type WorkflowWatchEventType =
| "pipeline_watch_start"
@@ -0,0 +1,78 @@
import { describe, expect, it } from "bun:test";
import { runWorkflowDebugTest } from "./services.js";
function setup(status = "COMPLETED", errors: string[] = []) {
const posts: string[] = [];
const response = (data: unknown) => new Response(JSON.stringify({ code: 200, data }));
const client = {
post: async (path: string) => { posts.push(path); return response("job"); },
get: async (path: string) => {
if (path.endsWith("/level/failed")) {
if (errors.includes("failures")) throw new Error("403 failures unavailable");
return response([]);
}
if (path.endsWith("/execution")) {
if (errors.includes("tree")) throw new Error("403 execution unavailable");
return response([]);
}
if (errors.includes("job")) throw new Error("403 job unavailable");
return response({ id: "job", status });
},
} as any;
return { client, posts };
}
describe("workflow debug completion evidence", () => {
it("reports completed only when all diagnostics were fetched", async () => {
const { client } = setup();
const result = await runWorkflowDebugTest(client, "pipe", { flowCodeOrId: "ID01-record" });
expect(result.outcome).toBe("completed");
expect(result.timedOut).toBe(false);
expect(result.diagnosticsComplete).toBe(true);
});
it("reports a failed terminal job", async () => {
const { client } = setup("FAILED");
const result = await runWorkflowDebugTest(client, "pipe", { flowCodeOrId: "ID01-record" });
expect(result.outcome).toBe("failed");
});
it("keeps timed-out jobs queryable and exposes missing diagnostic evidence", async () => {
const { client } = setup("RUNNING", ["tree", "failures"]);
const result = await runWorkflowDebugTest(client, "pipe", { flowCodeOrId: "ID01-record", timeoutMs: 0 });
expect(result.jobId).toBe("job");
expect(result.status).toBe("RUNNING");
expect(result.outcome).toBe("timed_out");
expect(result.timedOut).toBe(true);
expect(result.diagnosticsComplete).toBe(false);
expect(result.diagnosticsErrors.map(error => error.source)).toEqual(["executionTree", "failedExecutions"]);
});
it("marks partial diagnostic reads as incomplete rather than clean success", async () => {
const { client } = setup("COMPLETED", ["tree"]);
const result = await runWorkflowDebugTest(client, "pipe", { flowCodeOrId: "ID01-record" });
expect(result.outcome).toBe("incomplete");
expect(result.diagnosticsErrors[0]?.message).toContain("403");
});
it("preserves job identity when polling fails and does not hide the error", async () => {
const { client } = setup("RUNNING", ["job"]);
const result = await runWorkflowDebugTest(client, "pipe", { flowCodeOrId: "ID01-record" });
expect(result.jobId).toBe("job");
expect(result.outcome).toBe("incomplete");
expect(result.diagnosticsErrors[0]?.source).toBe("job");
});
it("rejects invalid timing options before creating a mutating job", async () => {
const { client, posts } = setup();
await expect(runWorkflowDebugTest(client, "pipe", { flowCodeOrId: "ID01-record", timeoutMs: -1 })).rejects.toThrow("timeoutMs");
expect(posts).toEqual([]);
});
it("retries a newly created job's HTTP 404 instead of reporting an authorization failure", async () => {
const { client } = setup();
const get = client.get;
let jobReads = 0;
client.get = async (path: string) => {
if (path.endsWith("/job") && jobReads++ === 0) throw { response: { status: 404 } };
return get(path);
};
const result = await runWorkflowDebugTest(client, "pipe", { flowCodeOrId: "ID01-record", timeoutMs: 100, pollIntervalMs: 1 });
expect(result.outcome).toBe("completed");
expect(jobReads).toBe(2);
});
});
@@ -0,0 +1,54 @@
import { expect, test } from "bun:test";
import ky from "ky";
import { deleteWorkflow, updateWorkflowChooses } from "./api.js";
import { refreshWorkflowChooses, updateWorkflow } from "./services.js";
import { WorkflowDetailSchema } from "./types.js";
import { WorkflowSavePartialError } from "./save-error.js";
import { AuthenticationError } from "../../../core/errors.js";
test("Piper 无返回值写操作兼容空成功,拒绝业务失败与无效 JSON", async () => {
for (const action of [deleteWorkflow, updateWorkflowChooses]) {
for (const body of ["", JSON.stringify({ code: 200, data: [] })]) {
const client = ky.create({ prefix: "https://piper.invalid", retry: 0, fetch: async () => new Response(body) });
await action(client, "p");
}
for (const body of [JSON.stringify({ code: 500, msg: "拒绝写入" }), "{broken"]) {
const client = ky.create({ prefix: "https://piper.invalid", retry: 0, fetch: async () => new Response(body) });
await expect(action(client, "p")).rejects.toThrow();
}
const client = ky.create({ prefix: "https://piper.invalid", retry: 0, fetch: async () => Response.json({ code: 401, msg: "凭证失效" }) });
await expect(action(client, "p")).rejects.toBeInstanceOf(AuthenticationError);
}
});
test("两阶段保存保留已提交版本,恢复只刷新 chooses", async () => {
const workflow = WorkflowDetailSchema.parse({ id: "p", version: "v1", tasksVersion: 1 });
const calls: string[] = [];
let failRefresh = true;
const client = ky.create({ prefix: "https://piper.invalid", retry: 0, fetch: async input => {
const path = new URL(input instanceof Request ? input.url : input.toString()).pathname;
calls.push(path);
return path.endsWith("/chooses")
? Response.json(failRefresh ? { code: 500, msg: "刷新拒绝" } : { code: 200, data: [] })
: Response.json({ code: 200, data: { ...workflow, tasksVersion: 2 } });
} });
let partial: WorkflowSavePartialError | undefined;
try { await updateWorkflow(client, workflow); }
catch (error) { expect(error).toBeInstanceOf(WorkflowSavePartialError); partial = error as WorkflowSavePartialError; }
expect(partial?.savedWorkflow.tasksVersion).toBe(2);
expect(partial?.details).toMatchObject({ remoteSaved: true, failedStep: "chooses", saved: { tasksVersion: 2 } });
failRefresh = false;
await refreshWorkflowChooses(client, "p");
expect(calls).toEqual(["/api/easo/pipelines/p", "/api/easo/pipelines/p/chooses", "/api/easo/pipelines/p/chooses"]);
});
test("主保存失败不会刷新 chooses,也不报告部分成功", async () => {
const calls: string[] = [];
const client = ky.create({ prefix: "https://piper.invalid", retry: 0, fetch: async input => {
calls.push(input instanceof Request ? input.url : input.toString());
return Response.json({ code: 500, msg: "主保存拒绝" });
} });
const error = await updateWorkflow(client, WorkflowDetailSchema.parse({ id: "p" })).catch(error => error);
expect(error).not.toBeInstanceOf(WorkflowSavePartialError);
expect(calls).toHaveLength(1);
});