496 lines
17 KiB
TypeScript
496 lines
17 KiB
TypeScript
import { z } from "zod";
|
|
import ky, { KyInstance } from "ky";
|
|
import { AuthenticationError, BusinessError, EkbApiError } from "../../core/errors.js";
|
|
import {
|
|
PlatformSchema,
|
|
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";
|
|
|
|
// 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 = await response.json();
|
|
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;
|
|
const hasWrapper = Boolean(record && ("data" in record || "value" in record));
|
|
const payload = hasWrapper ? (record!.data ?? record!.value) : raw;
|
|
|
|
if (hasCodeError || payload === null || payload === undefined) {
|
|
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);
|
|
}
|
|
|
|
return schema.parse(payload);
|
|
}
|
|
|
|
// Helper for simple success responses
|
|
async function ok(response: Response): Promise<{ success: boolean }> {
|
|
return { success: response.status === 200 };
|
|
}
|
|
|
|
// ── 自建应用 ──────────────────────────────────────────────────────────────────
|
|
|
|
export async function listPlatforms(
|
|
client: KyInstance,
|
|
corpId: string
|
|
): Promise<import("./types.js").Platform[]> {
|
|
const response = await client.get("api/v2/datalink/platform/search", {
|
|
searchParams: { scope: "enable", corpId },
|
|
});
|
|
const json = (await response.json()) as { items: unknown[] };
|
|
return z.array(PlatformSchema).parse(json.items);
|
|
}
|
|
|
|
// ── 工作流(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);
|
|
}
|
|
|
|
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 response.text().catch(() => "");
|
|
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> {
|
|
try {
|
|
const response = await client.get(`api/easo/snapshots/${snapshotId}`);
|
|
return unwrap(response, WorkflowSnapshotSchema);
|
|
} catch (err) {
|
|
if (pipelineId) {
|
|
const response = await client.get(`api/easo/pipelines/${pipelineId}/snapshots/${snapshotId}`);
|
|
return unwrap(response, WorkflowSnapshotSchema);
|
|
}
|
|
throw err;
|
|
}
|
|
}
|
|
|
|
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 },
|
|
});
|
|
return unwrap(response, z.array(WorkflowJobSchema));
|
|
}
|
|
|
|
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);
|
|
}
|
|
}
|
|
|
|
|
|
|