import { readFileSync, writeFileSync } from "node:fs"; import { EkbError } from "../../../core/errors.js"; import { getWorkflowDetail, listAllWorkflows, refreshWorkflowChooses, updateWorkflow, lintWorkflowScripts } from "../../../domains/platform/workflow/services.js"; import { WorkflowSavePartialError } from "../../../domains/platform/workflow/management/save-error.js"; import { WorkflowDetailSchema } from "../../../domains/platform/workflow/types.js"; import { applyWorkflowPathPatch, beginWorkflowSave, commitWorkflowSave, createWorkflowDraft, failWorkflowSave, hasWorkflowVersionConflict, } from "../../../domains/platform/workflow/state/index.js"; import { stringOption, booleanOption } from "../../parser.js"; import { createClientsForCorp, createPiperClientForCorp } from "../../helpers.js"; import { printJson } from "../../printer.js"; import { isDryRun, mutationPreview, requireMutationConfirmation } from "../../mutation.js"; import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js"; import { PLATFORM_ID_OPTION_KEYS, formatWorkflowVersion } from "./shared.js"; export async function handlePatch(parsed: CliParsedArgs, runtime: CliRuntime): Promise { const pipelineId = parsed.args[0] || stringOption(parsed.options, ["id", "pipelineId"]); const file = stringOption(parsed.options, ["file", "input", "from"]); const path = stringOption(parsed.options, ["path", "field"]); const rawValue = parsed.options.value; const output = stringOption(parsed.options, ["output", "output-file", "outputFile"]); const inPlace = booleanOption(parsed.options, ["in-place", "inPlace"]); if (!pipelineId || !file || !path || typeof rawValue !== "string" || (!output && !inPlace)) { return { stdout: "", stderr: "用法: hose-use workflow patch --file= --path= --value=<值> (--output=|--in-place) [--value-json]\n", exitCode: 1, }; } let source: unknown; try { source = JSON.parse(readFileSync(file, "utf8")); } catch (error) { throw new Error(`无法读取工作流 JSON 文件 [${file}]: ${error instanceof Error ? error.message : String(error)}`); } const sourceWorkflow = WorkflowDetailSchema.parse(source); if (sourceWorkflow.id !== pipelineId) { throw new Error(`工作流 ID 不匹配:参数为 [${pipelineId}],文件中为 [${sourceWorkflow.id}]`); } let value: unknown = rawValue; if (booleanOption(parsed.options, ["value-json", "valueJson"])) { try { value = JSON.parse(rawValue); } catch (error) { throw new Error(`--value-json 不是合法 JSON: ${error instanceof Error ? error.message : String(error)}`); } } const patched = applyWorkflowPathPatch(sourceWorkflow, path, value); const target = inPlace ? file : output!; requireMutationConfirmation( parsed, runtime, "写入工作流草稿文件", `hose-use workflow patch ${pipelineId} --file=${file} --path=${path} --value='${rawValue}' ${inPlace ? "--in-place" : `--output=${target}`} --yes` ); if (isDryRun(parsed, runtime)) { return mutationPreview(parsed, runtime, "写入工作流草稿文件", target, { pipelineId, path, value, tasksVersion: patched.tasksVersion, }); } writeFileSync(target, `${JSON.stringify(patched, null, 2)}\n`, "utf8"); const result = { success: true, pipelineId, path, output: target, tasksVersion: patched.tasksVersion }; if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 }; return { stdout: `✅ 已生成工作流草稿 [${target}],修改路径: ${path}\n`, stderr: "", exitCode: 0 }; } export async function handleSave(parsed: CliParsedArgs, runtime: CliRuntime): Promise { const pipelineId = parsed.args[0] || stringOption(parsed.options, ["id", "pipelineId"]); const file = stringOption(parsed.options, ["file", "input", "from"]); if (!pipelineId || !file) { return { stdout: "", stderr: "用法: hose-use workflow save --file= [--force-write] [--in-place]\n", exitCode: 1, }; } let draftWorkflow: unknown; try { draftWorkflow = JSON.parse(readFileSync(file, "utf8")); } catch (error) { throw new Error(`无法读取工作流 JSON 文件 [${file}]: ${error instanceof Error ? error.message : String(error)}`); } const parsedWorkflow = WorkflowDetailSchema.parse(draftWorkflow); if (parsedWorkflow.id !== pipelineId) { throw new Error(`工作流 ID 不匹配:参数为 [${pipelineId}],文件中为 [${parsedWorkflow.id}]`); } const forceWrite = booleanOption(parsed.options, ["force-write", "forceWrite"]); const syncFile = booleanOption(parsed.options, ["in-place", "inPlace"]); // 保存前静态代码健康度检查 const scriptLintReport = lintWorkflowScripts(parsedWorkflow as any); const scriptWarnings: string[] = []; if (scriptLintReport.totalCodeNodes > 0) { for (const node of scriptLintReport.reports) { if (node.issues.length > 0) { for (const iss of node.issues) { const icon = iss.level === "error" ? "❌" : "⚠️"; const loc = iss.line ? `(L${iss.line})` : ""; scriptWarnings.push(`${icon} 节点 [${node.nodeName}] ${loc}: [${iss.rule}] ${iss.message}`); } } } } requireMutationConfirmation( parsed, runtime, "保存工作流草稿到远端", `hose-use workflow save ${pipelineId} --file=${file} --yes` ); if (isDryRun(parsed, runtime)) { return mutationPreview(parsed, runtime, "保存工作流草稿到远端", pipelineId, { file, version: parsedWorkflow.version, tasksVersion: parsedWorkflow.tasksVersion, forceWrite, syncFile, ...(scriptWarnings.length > 0 ? { scriptWarnings } : {}), }); } const clients = await createClientsForCorp(runtime.selectedCorp!); const platformId = await resolveWorkflowPlatformId(parsed, clients, pipelineId); const piperClient = await createPiperClientForCorp(runtime.selectedCorp!, platformId); const remote = await getWorkflowDetail(piperClient, pipelineId); let state = createWorkflowDraft(parsedWorkflow); state = { ...state, revision: 1, status: "dirty", dirtyPaths: ["*"], }; if (!forceWrite && hasWorkflowVersionConflict(state, remote)) { throw new Error( `工作流版本已变化,拒绝覆盖:远端 tasksVersion=${remote.tasksVersion}, 文件 tasksVersion=${parsedWorkflow.tasksVersion}。请重新导出最新工作流后再改;后续保存可加 --in-place 自动同步本地文件版本。确认要覆盖时使用 --force-write。` ); } state = beginWorkflowSave(state); const localWorkflowForSync = state.workflow; try { const payload = state.workflow.inputs?.length ? state.workflow : { ...state.workflow, inputs: [{ key: "$platformId", value: platformId }] }; let partialError: WorkflowSavePartialError | undefined; const saved = await updateWorkflow(piperClient, payload).catch((error: unknown) => { if (!(error instanceof WorkflowSavePartialError)) throw error; partialError = error; return error.savedWorkflow; }); state = commitWorkflowSave(state, saved); if (partialError) state = { ...state, status: "partial", error: partialError.message }; let fileSynced = false; let fileSyncWarning = ""; if (syncFile) { try { const syncedWorkflow = { ...localWorkflowForSync, version: saved.version, tasksVersion: saved.tasksVersion, updateTime: saved.updateTime, }; writeFileSync(file, `${JSON.stringify(syncedWorkflow, null, 2)}\n`, "utf8"); fileSynced = true; } catch (error) { fileSyncWarning = `本地文件同步失败: ${error instanceof Error ? error.message : String(error)}`; } } const quoteArg = (value: string) => `'${value.replaceAll("'", "'\\''")}'`; const nextAction = `hose-use workflow refresh-chooses ${quoteArg(pipelineId)} --platform-id=${quoteArg(platformId)} --corp=${quoteArg(runtime.selectedCorp!.id)} --yes`; const result = { success: !partialError, ...(partialError ? { remoteSaved: true, failedStep: "chooses", nextAction, message: partialError.message } : {}), pipelineId, status: state.status, version: saved.version, tasksVersion: saved.tasksVersion, updateTime: saved.updateTime, fileSynced, ...(fileSyncWarning ? { fileSyncWarning } : {}), }; if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: fileSyncWarning, exitCode: partialError ? 1 : 0 }; if (partialError) return { stdout: `⚠️ ${partialError.message}\n${fileSynced ? "已同步本地文件版本。\n" : ""}恢复命令: ${nextAction}\n`, stderr: fileSyncWarning, exitCode: 1, }; return { stdout: `✅ 工作流 [${pipelineId}] 草稿保存成功:${formatWorkflowVersion(saved)}。${fileSynced ? "\n📝 已同步更新本地文件。" : ""}${fileSyncWarning ? `\n⚠️ ${fileSyncWarning}` : ""}\n`, stderr: fileSyncWarning, exitCode: 0, }; } catch (error) { state = failWorkflowSave(state, error); if (error instanceof EkbError) throw error; throw new Error(`工作流保存失败(${state.status}): ${state.error}`); } } export async function handleRefreshChooses(parsed: CliParsedArgs, runtime: CliRuntime): Promise { const pipelineId = parsed.args[0] || stringOption(parsed.options, ["id", "pipelineId"]); if (!pipelineId) throw new Error("请提供工作流 ID: hose-use workflow refresh-chooses --yes"); requireMutationConfirmation(parsed, runtime, "刷新工作流元数据", `hose-use workflow refresh-chooses ${pipelineId} --yes`); if (isDryRun(parsed, runtime)) return mutationPreview(parsed, runtime, "刷新工作流元数据", pipelineId, { retryStep: "chooses", saveWorkflow: false }); const clients = await createClientsForCorp(runtime.selectedCorp!); const platformId = await resolveWorkflowPlatformId(parsed, clients, pipelineId); const client = await createPiperClientForCorp(runtime.selectedCorp!, platformId); await refreshWorkflowChooses(client, pipelineId); return { stdout: runtime.jsonMode ? printJson({ success: true, pipelineId, metadataRefreshed: true }, runtime.outputOptions) : `工作流 [${pipelineId}] 元数据刷新成功,未重新提交快照。\n`, stderr: "", exitCode: 0 }; } async function resolveWorkflowPlatformId( parsed: CliParsedArgs, clients: Awaited>, pipelineId: string ): Promise { const explicit = stringOption(parsed.options, PLATFORM_ID_OPTION_KEYS); if (explicit) return explicit; const all = await listAllWorkflows(clients, { page: 1, pageSize: 100 }); const match = all.workflows.find((workflow) => workflow.id === pipelineId); if (!match?.platformId) { throw new Error(`无法确定工作流 [${pipelineId}] 所属自建应用,请使用 --platform-id= 或 --app-id=`); } return match.platformId; }