diff --git a/skills/hose-use/SKILL.md b/skills/hose-use/SKILL.md index bca9a8f..7d76a91 100644 --- a/skills/hose-use/SKILL.md +++ b/skills/hose-use/SKILL.md @@ -66,6 +66,12 @@ metadata: - **高阶管理人员权限风控识别**:合思协助平台具备直接借用企业任意员工身份(包含主管理员、企业法定代表人、财务负责人/总监、VP/总裁等高管身份)的高危能力。当获取的身份命中高管关键词(总监、主管、主管理员、总经理等)或具备 `SYS_ADMIN` / `CORP_PAYMENT_MANAGE` 权限时,系统会自动发出醒目的高管权限风控警示框; - **防范越权与误用硬约束**:一线实施、运维人员或 AI Agent 严禁借用高管特权身份在系统内代行审批通过、款项拨付或提交非授权配置!所有协助权限必须严格局限在系统排障、配置诊断、数据核验与接口联调,严禁进行越权业务审批; - **协助时长服务端硬性上限**:协助平台工单申请(`POST /api/assistPlatform/create`)受服务端硬性安全管控,单次最长有效时间为 24 小时(1天),超过 24 小时服务端直接返回 400 拒绝。如需持续维护,可在工单到期后再次发起或在端内续签。 +14. **工作流代码节点文件映射与 Token 防膨胀守则 (Workflow Code Node File Mapping & Zero-Token-Waste Rule)**: + - **严禁终端内联大段代码**:在新建或修改工作流代码节点(`code-js2` / `code`)时,**严禁使用 `--code="..."` 或在终端命令(如 `bun -e '...'`)中内联几十上百行的长代码**。内联大段代码会导致命令行参数急剧膨胀,在 Tool Calls 中产生严重的输入输出 Token 浪费,且极易因 Shell 引号转义损坏脚本语法; + - **必须走本地文件映射与 `--code-file`**: + 1. **导出/映射**:先将节点代码提取至本地独立文件(如 `scripts/clean.js` 或 `scripts/amortize.mvel`),或使用 `hose-use workflow node get > ./scripts/xxx.mvel`; + 2. **微创修改(Diff Edit)**:在本地文件上使用编辑工具进行精准、局部的差异修改(仅消耗几行 diff 的极少 Token); + 3. **一键同步**:使用 `hose-use workflow node edit --code-file=./scripts/xxx.mvel --yes`(或 `node add ... --code-file=...`)通过文件流同步至云端。 --- @@ -227,8 +233,8 @@ hose-use workflow webhook send wf_01k83y... --bill=<单号> --yes # 向 Webhoo hose-use workflow delete wf_01k83y... --yes # 安全删除工作流 (支持 rm, remove, 带 --dry-run 预览) hose-use workflow node list wf_01k83y... # 树形层级索引查看工作流任务节点树与摘要 (别名 ls) hose-use workflow node get wf_01k83y... <节点name或#序号> # 查看指定节点的完整配置 (别名 show, info) -hose-use workflow node add wf_01k83y... --type=code-js2 --label="清洗" --code="return items;" --yes # 声明式追加节点 (--after/--parent 插入) -hose-use workflow node edit wf_01k83y... <节点name或#序号> --label="新标题" --yes # 定向修改节点配置 +hose-use workflow node add wf_01k83y... --type=code-js2 --label="清洗" --code-file=./clean.js --yes # 声明式追加节点 (支持 --code-file 导入) +hose-use workflow node edit wf_01k83y... <节点name或#序号> --code-file=./clean.js --yes # 从本地文件同步最新脚本 (推荐,零 Token 浪费) hose-use workflow node rm wf_01k83y... <节点name或#序号> --yes # 安全移除任务节点 (首节点触发器安全防御) hose-use workflow tail wf_01k83y... # 类似 tail -f 实时监听新任务派发与节点执行日志流 (别名 watch, follow) hose-use workflow tail wf_01k83y... --job= # 针对单个执行中的 Job 实时跟踪直至终态 diff --git a/skills/hose-use/multi/ekuaibao-mvel/SKILL.md b/skills/hose-use/multi/ekuaibao-mvel/SKILL.md index 871ef0b..fe5340f 100644 --- a/skills/hose-use/multi/ekuaibao-mvel/SKILL.md +++ b/skills/hose-use/multi/ekuaibao-mvel/SKILL.md @@ -144,3 +144,11 @@ result; Then add one field access at a time. For code nodes nested inside a condition branch, still return a normal object from the code node; only condition expressions themselves must return boolean. Treat tenant-specific behavior as evidence, not a universal rule. Say what assumption the code is using when syntax compatibility is uncertain. + +## Deployment & CLI Integration (Zero-Token-Waste Rule) + +- **Always maintain MVEL scripts in local dedicated files** (e.g. `./scripts/node_calc.mvel`), never pass long scripts inline in `--code="..."` or in terminal `bun -e '...'` expressions. +- **Local syntax check**: `hose-use workflow lint-script --file=./scripts/node_calc.mvel --type=code` +- **Deploy to workflow node**: `hose-use workflow node edit --code-file=./scripts/node_calc.mvel --yes` +- **End-to-end cloud simulation test**: `hose-use workflow test --flow --yes --force` + diff --git a/skills/hose-use/references/workflow.md b/skills/hose-use/references/workflow.md index 6bde065..8a33c82 100644 --- a/skills/hose-use/references/workflow.md +++ b/skills/hose-use/references/workflow.md @@ -321,15 +321,17 @@ hose-use workflow node get 2 --json # 3. 声明式向工作流追加或定向插入新节点 (别名: append, insert) # 默认追加至流程末尾;支持通过 --parent=<容器节点> 插入循环/分支内,或 --after=<节点> 插入指定节点后 -hose-use workflow node add --type=code-js2 --label="数据过滤" --code="return items.filter(x => x.amount > 0);" --dry-run -hose-use workflow node add --type=code-js2 --label="数据过滤" --code="return items.filter(x => x.amount > 0);" --yes +# 推荐做法(零 Token 浪费 & 避开命令行转义):从本地脚本文件导入代码 +hose-use workflow node add --type=code-js2 --label="数据过滤" --code-file=./scripts/filter.js --yes hose-use workflow node add --type=stop --label="超额阻断" --after=action_dx9cci --yes hose-use workflow node add --type=http --label="外部通知" --parent=control_every_1 --yes # 4. 定向修改指定节点配置 (别名: update, set) -# 支持修改 --label, --desc, --code, 或通过 --set="key=value" 定向覆盖任意属性 -hose-use workflow node edit action_dx9cci --label="清洗增强版" --code="return items;" --dry-run -hose-use workflow node edit action_dx9cci --label="清洗增强版" --code="return items;" --yes +# 支持修改 --label, --desc, --code, --code-file, 或通过 --set="key=value" 定向覆盖任意属性 +# 推荐做法(零 Token 浪费 & 避开命令行转义):从本地文件导入脚本 +hose-use workflow node edit action_dx9cci --code-file=./scripts/clean.js --dry-run +hose-use workflow node edit action_dx9cci --code-file=./scripts/clean.js --yes +hose-use workflow node edit action_dx9cci --label="清洗增强版" --yes hose-use workflow node edit 2 --set="method=GET" --yes # 5. 安全移除指定任务节点 (别名: remove, delete, del) diff --git a/src/cli/command-metadata.ts b/src/cli/command-metadata.ts index 2d3d988..b97bca3 100644 --- a/src/cli/command-metadata.ts +++ b/src/cli/command-metadata.ts @@ -272,7 +272,7 @@ export const COMMAND_METADATA: Record = { "dictionary": "enum", "dict": "enum" }, - flags: { ...flagList("all allow-prod allow-production auto-publish autoPublish compare detail diff empty errors f fail fail-on-alert failOnAlert failed failed-only failedOnly follow force force-write forceWrite full has-error hasError in-place inPlace includeDetail json none once publish snapshot v value-json valueJson verbose with-tasks withTasks timeline progress steps", "boolean"), ...flagList("a admin-key adminKey after app app-id appId b bill body c code code-file container count d data desc description end-time endTime entity execution-logs field file filter flow flow-code flowCode from i id input input-file insert-after interval job job-id job1 job2 jobA jobB jobId keyword l label limit log logs max-jobs maxJobs n name node node-id nodeId nodes output output-file outputFile p page page-size pageSize parent parent-id parentId password path payload pipeline pipeline-id pipelineId platform platform-id platformId pwd q query record s sample sample-id sampleId set size snapshot1 snapshot2 snapshotA snapshotB source start-time startTime state state-file stateFile t target targetName targetPlatformId task taskType third-id thirdId timeout timeout-ms timeoutMs to trigger type types value workflowId", "value") } + flags: { ...flagList("all allow-prod allow-production auto-publish autoPublish compare detail diff empty errors f fail fail-on-alert failOnAlert failed failed-only failedOnly follow force force-write forceWrite full has-error hasError in-place inPlace includeDetail json none once publish snapshot v value-json valueJson verbose with-tasks withTasks timeline progress steps", "boolean"), ...flagList("a admin-key adminKey after app app-id appId b bill body c code code-file container count d data desc description end-time endTime entity execution-logs field file filter flow flow-code flowCode from i id input input-file insert-after interval job job-id job1 job2 jobA jobB jobId json-file keyword l label limit log logs mapping mapping-file max-jobs maxJobs n name node node-id nodeId nodes output output-file outputFile p page page-size pageSize parent parent-id parentId password path payload pipeline pipeline-id pipelineId platform platform-id platformId pwd q query record s sample sample-id sampleId set size snapshot1 snapshot2 snapshotA snapshotB source start-time startTime state state-file stateFile t target targetName targetPlatformId task taskType third-id thirdId timeout timeout-ms timeoutMs to trigger type types value workflowId", "value") } }, "bill": { "summary": "单据检索、表单规格诊断与审批动作", @@ -445,7 +445,7 @@ export const COMMAND_METADATA: Record = { "costtype" ], "commandAliases": {}, - flags: { ...flagList("a all fields flat flatten include-disabled r recursive spec specs table", "boolean"), ...flagList("code color desc description en-name enName icon id keyword name parent parent-id parentId q query target title to", "value") } + flags: { ...flagList("a all fields flat flatten ids ids-only include-disabled r recursive spec specs table", "boolean"), ...flagList("code color desc description en-name enName icon id keyword name parent parent-id parentId q query subtree subtree-id target title to", "value") } }, "role": { "summary": "企业角色定义与成员", @@ -541,6 +541,7 @@ export const COMMAND_METADATA: Record = { "records": "查询记录(支持 --all / --ndjson 流式 / --stats 画像)", "record": "查看或安全修改单条/批量记录 (get/create/edit/batch-edit)", "audit": "业务对象健康度巡检(必填缺失/禁用引用/跨表同步差异)", + "gen-props": "生成业务对象字段常量与代码模板 (支持 MVEL / JS)", "permissions": "查看权限", "imports": "查看导入任务", "get": "查看应用详情" @@ -580,11 +581,13 @@ export const COMMAND_METADATA: Record = { "update": "record", "batch-update": "record", "record-recompute": "record", + "gen-mvel-props": "gen-props", + "props": "gen-props", "permission": "permissions", "auth": "permissions", "import-jobs": "imports" }, - flags: { ...flagList("a active active-only activeOnly all flat ndjson normalize normalized profile raw state stats stream w workbench", "boolean"), ...flagList("aggregate baseline c check-continuous check-fields checkContinuous checkFields concurrency continuous count d data expect expect-value expectValue f field fields file filter filter-by filterBy form group-by groupBy id ids keyword limit name offset page-size pageSize q query search-field searchField search-fields searchFields select seq sequence set start sum where", "value") } + flags: { ...flagList("a active active-only activeOnly all flat ndjson normalize normalized profile raw state stats stream w workbench", "boolean"), ...flagList("aggregate baseline c check-continuous check-fields checkContinuous checkFields concurrency continuous count d data expect expect-value expectValue f field fields file filter filter-by filterBy form group-by groupBy id ids keyword lang language limit name offset page-size pageSize q query search-field searchField search-fields searchFields select seq sequence set start sum where", "value") } }, "app": { "summary": "桌面端工作台应用管理", diff --git a/src/cli/commands/feetype.test.ts b/src/cli/commands/feetype.test.ts index 4584019..a30abd6 100644 --- a/src/cli/commands/feetype.test.ts +++ b/src/cli/commands/feetype.test.ts @@ -106,6 +106,7 @@ describe("CLI - feetype 费用类型管理命令", () => { total: 3, items: mockTree, rawTree: mockTree, + ids: ["COST01", "COST02", "COST19"], }); const res = await handleFeeTypeCommand( @@ -134,6 +135,7 @@ describe("CLI - feetype 费用类型管理命令", () => { total: 2, items: mockTree, rawTree: mockTree, + ids: ["COST01", "COST02"], }); const jsonRuntime = { ...dummyRuntimeWithCorp, jsonMode: true }; diff --git a/src/cli/commands/feetype.ts b/src/cli/commands/feetype.ts index 4cf92fb..fc99e74 100644 --- a/src/cli/commands/feetype.ts +++ b/src/cli/commands/feetype.ts @@ -84,11 +84,15 @@ export async function handleFeeTypeCommand( booleanOption(parsed.options, ["flat", "flatten", "table"]) || false; const keyword = stringOption(parsed.options, ["keyword", "q", "query"]) || parsed.args[0]; + const subtree = stringOption(parsed.options, ["subtree", "subtree-id", "parent-id"]); + const idsOnly = booleanOption(parsed.options, ["ids-only", "ids"]) || false; const result = await listFeeTypes(await getClient(), corpId, { all: includeAll, - flat: isFlat, + flat: isFlat || Boolean(subtree) || idsOnly, keyword, + subtreeParentId: subtree || undefined, + idsOnly, }); if (runtime.jsonMode) { @@ -100,7 +104,7 @@ export async function handleFeeTypeCommand( total: result.total, includeDisabled: includeAll, keyword: keyword || null, - items: result.items, + ...(idsOnly ? { ids: result.ids } : { items: result.items }), }, runtime.outputOptions ), @@ -109,8 +113,16 @@ export async function handleFeeTypeCommand( }; } + if (idsOnly) { + return { + stdout: JSON.stringify(result.ids) + "\n", + stderr: "", + exitCode: 0, + }; + } + let rows: (string | number)[][] = []; - if (!isFlat && !keyword) { + if (!isFlat && !keyword && !subtree) { rows = renderTreeRows(result.rawTree); } else { const flatItems = (result.items as FlatFeeTypeItem[]) || []; @@ -126,7 +138,7 @@ export async function handleFeeTypeCommand( const title = `====== 费用类型列表 (企业: ${corp.name} | 共 ${result.total} 个${ includeAll ? ",含停用" : "" - }${keyword ? `,过滤: "${keyword}"` : ""}) ======`; + }${keyword ? `,过滤: "${keyword}"` : ""}${subtree ? `,子树: "${subtree}"` : ""}) ======`; const tableStr = rows.length ? printTable(["#", "名称 / 层级路径", "编码", "ID", "状态", "子节点"], rows) : "暂无匹配的费用类型"; diff --git a/src/cli/commands/platform.test.ts b/src/cli/commands/platform.test.ts index e195c90..5e010c3 100644 --- a/src/cli/commands/platform.test.ts +++ b/src/cli/commands/platform.test.ts @@ -525,5 +525,38 @@ describe("CLI - platform 命令与 record 动作", () => { expect(fetch).not.toHaveBeenCalled(); expect(write).not.toHaveBeenCalled(); }); + + it("platform gen-props 生成 MVEL 和 JS 格式的字段模板", async () => { + spies.push(spyOn(helpers, "createClientsForCorp").mockResolvedValue({ ekbClient: {} } as any)); + spies.push(spyOn(services, "resolvePlatform").mockResolvedValue(mockPlatform as any)); + spies.push(spyOn(services, "resolveEntity").mockResolvedValue({ + id: "E_contract", + name: "合同", + code: "CONTRACT", + fields: [ + { name: "E_contract_name", label: "合同名称", type: "text", optional: false }, + { name: "E_contract_amount", label: "合同金额", type: "money", optional: true }, + ], + } as any)); + + // MVEL 模板 (默认) + const mvelRes = await handlePlatformCommand( + { area: "platform", action: "gen-props", args: ["platform-1", "contract"], options: {}, raw: [] }, + dummyRuntime + ); + expect(mvelRes.exitCode).toBe(0); + expect(mvelRes.stdout).toContain('String TARGET_ENTITY_ID = "E_contract";'); + expect(mvelRes.stdout).toContain('String FIELD_合同名称 = FIELD_PREFIX + "name";'); + expect(mvelRes.stdout).toContain('row.put(FIELD_合同名称, "");'); + + // JS 模板 + const jsRes = await handlePlatformCommand( + { area: "platform", action: "gen-props", args: ["platform-1", "contract"], options: { lang: "js" }, raw: [] }, + dummyRuntime + ); + expect(jsRes.exitCode).toBe(0); + expect(jsRes.stdout).toContain('const ENTITY_ID = "E_contract";'); + expect(jsRes.stdout).toContain('"合同名称": FIELD_PREFIX + "name"'); + }); }); diff --git a/src/cli/commands/platform/app-info.ts b/src/cli/commands/platform/app-info.ts index 7931414..cecb4e0 100644 --- a/src/cli/commands/platform/app-info.ts +++ b/src/cli/commands/platform/app-info.ts @@ -122,3 +122,90 @@ export async function handleImports(parsed: CliParsedArgs, runtime: CliRuntime): if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 }; return { stdout: `====== 导入任务: ${resolved.platform.name} / ${resolved.entity.name} ======\n${printTable(["#", "任务"], jobs.map((job, i) => [i + 1, cell(job)]))}\n`, stderr: "", exitCode: 0 }; } + +export async function handleGenProps(parsed: CliParsedArgs, runtime: CliRuntime): Promise { + const resolved = await resolveAppAndEntity(parsed, runtime); + if (!resolved.entity) { + throw new Error("请提供业务对象 ID、编码或名称: hose-use platform gen-props <应用> <业务对象> [--lang=mvel|js]"); + } + + const lang = (stringOption(parsed.options, ["lang", "language"]) || "mvel").toLowerCase(); + const entity = resolved.entity; + const entityId = entity.id; + const entityName = entity.name; + const prefix = entityId ? `${entityId}_` : ""; + + if (runtime.jsonMode) { + return { + stdout: printJson( + { + platform: resolved.platform, + entity: { + id: entity.id, + name: entity.name, + code: entity.code, + prefix, + fields: entity.fields.map((f) => ({ + fieldKey: f.name, + label: f.label, + type: f.type, + suffix: f.name.startsWith(prefix) ? f.name.slice(prefix.length) : f.name, + })), + }, + }, + runtime.outputOptions + ), + stderr: "", + exitCode: 0, + }; + } + + const lines: string[] = []; + if (lang === "js" || lang === "javascript") { + lines.push(`// ====== 自建应用实体代码模板 [${entityName}] (JS / QuickJS) ======`); + lines.push(`const ENTITY_ID = "${entityId}";`); + lines.push(`const FIELD_PREFIX = "${prefix}";`); + lines.push(""); + lines.push("// ── 字段物理键定义 ──"); + lines.push("const FIELDS = {"); + for (const f of entity.fields) { + const suffix = f.name.startsWith(prefix) ? f.name.slice(prefix.length) : f.name; + const safeLabel = f.label.replace(/"/g, '\\"'); + lines.push(` "${safeLabel}": FIELD_PREFIX + "${suffix}", // ${f.type || "text"}${f.optional === false ? " [必填]" : ""}`); + } + lines.push("};"); + lines.push(""); + lines.push("// ── 写入数据对象示例 ──"); + lines.push("const recordData = {"); + for (const f of entity.fields) { + const safeLabel = f.label.replace(/"/g, '\\"'); + lines.push(` [FIELDS["${safeLabel}"]]: "", // ${f.label}`); + } + lines.push("};"); + } else { + // 默认 MVEL 模板 + lines.push(`// ====== 自建应用实体代码模板 [${entityName}] (MVEL) ======`); + lines.push(`String TARGET_ENTITY_ID = "${entityId}";`); + lines.push(`String FIELD_PREFIX = "${prefix}";`); + lines.push(""); + lines.push("// ── 物理字段键常量 ──"); + for (const f of entity.fields) { + const suffix = f.name.startsWith(prefix) ? f.name.slice(prefix.length) : f.name; + const constName = `FIELD_${f.label.replace(/[^a-zA-Z0-9_\u4e00-\u9fa5]/g, "_")}`; + lines.push(`String ${constName} = FIELD_PREFIX + "${suffix}"; // ${f.label} (${f.type || "text"})${f.optional === false ? " [必填]" : ""}`); + } + lines.push(""); + lines.push("// ── DataLink 行构建模板 (row.put) ──"); + lines.push("Map row = new HashMap();"); + for (const f of entity.fields) { + const constName = `FIELD_${f.label.replace(/[^a-zA-Z0-9_\u4e00-\u9fa5]/g, "_")}`; + lines.push(`row.put(${constName}, ""); // ${f.label}`); + } + } + + return { + stdout: `${lines.join("\n")}\n`, + stderr: "", + exitCode: 0, + }; +} diff --git a/src/cli/commands/platform/index.ts b/src/cli/commands/platform/index.ts index 995ecf4..6838a24 100644 --- a/src/cli/commands/platform/index.ts +++ b/src/cli/commands/platform/index.ts @@ -1,6 +1,6 @@ import { booleanOption } from "../../parser.js"; import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js"; -import { handleList, handleGet, handleEntities, handleSchema, handlePermissions, handleImports } from "./app-info.js"; +import { handleList, handleGet, handleEntities, handleSchema, handlePermissions, handleImports, handleGenProps } from "./app-info.js"; import { handleRecords, handleAudit } from "./records.js"; import { handleRecordAction } from "./record-actions.js"; @@ -47,9 +47,12 @@ export async function handlePlatformCommand(parsed: CliParsedArgs, runtime: CliR case "permissions": case "permission": case "auth": return handlePermissions(parsed, runtime); + case "gen-props": + case "gen-mvel-props": + case "props": return handleGenProps(parsed, runtime); case "imports": case "import-jobs": return handleImports(parsed, runtime); default: - return { stdout: "", stderr: `未知 platform 子命令: ${action}。支持: list, get, entities, schema, records, audit, record, permissions, imports\n`, exitCode: 1 }; + return { stdout: "", stderr: `未知 platform 子命令: ${action}。支持: list, get, entities, schema, records, audit, record, gen-props, permissions, imports\n`, exitCode: 1 }; } } diff --git a/src/cli/commands/workflow.test.ts b/src/cli/commands/workflow.test.ts index 99db543..7cd0cd7 100644 --- a/src/cli/commands/workflow.test.ts +++ b/src/cli/commands/workflow.test.ts @@ -1656,6 +1656,42 @@ describe("CLI - workflow job 执行详情与异常精准透视", () => { expect(editRes.exitCode).toBe(0); expect(editRes.stdout).toContain("修改已保存至工作流"); + // 5.1 node map + const mapRes = await handleWorkflowCommand( + { + area: "workflow", + action: "node", + args: ["map", "pipe_node_test", "action_js_1"], + options: { yes: true }, + raw: ["workflow", "node", "map", "pipe_node_test", "action_js_1", "--yes"], + }, + mockRuntime + ); + expect(mapRes.exitCode).toBe(1); + expect(mapRes.stderr).toContain("请通过 --mapping-file=<路径> 指定"); + + const tmpMappingFile = (await import("os")).tmpdir() + "/test-fields-" + Date.now() + ".json"; + await (await import("fs/promises")).writeFile( + tmpMappingFile, + JSON.stringify([{ name: "test_field", label: "测试字段", value: "test_val" }]), + "utf-8" + ); + + const mapSuccessRes = await handleWorkflowCommand( + { + area: "workflow", + action: "node", + args: ["map", "pipe_node_test", "action_js_1"], + options: { "mapping-file": tmpMappingFile, yes: true }, + raw: ["workflow", "node", "map", "pipe_node_test", "action_js_1", `--mapping-file=${tmpMappingFile}`, "--yes"], + }, + mockRuntime + ); + expect(mapSuccessRes.exitCode).toBe(0); + expect(mapSuccessRes.stdout).toContain("已批量应用映射"); + + await (await import("fs/promises")).unlink(tmpMappingFile).catch(() => {}); + // 6. node rm const rmRes = await handleWorkflowCommand( { diff --git a/src/cli/commands/workflow/job.ts b/src/cli/commands/workflow/job.ts index 90750b3..f3cdefa 100644 --- a/src/cli/commands/workflow/job.ts +++ b/src/cli/commands/workflow/job.ts @@ -17,7 +17,7 @@ import { stringOption, numberOption, booleanOption } from "../../parser.js"; import { createClientsForCorp, createPiperClientForCorp } from "../../helpers.js"; import { printJson, printTable, printKeyValue } from "../../printer.js"; import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js"; -import { PLATFORM_ID_OPTION_KEYS } from "./shared.js"; +import { PLATFORM_ID_OPTION_KEYS, extractCodeNodeSummaries, formatCodeNodeSummariesCard } from "./shared.js"; async function createJobPiperClient( parsed: CliParsedArgs, @@ -629,6 +629,11 @@ export async function handleJob(parsed: CliParsedArgs, runtime: CliRuntime): Pro } } + const codeSummaries = extractCodeNodeSummaries(tree, flattenExecutionTree); + if (codeSummaries.length > 0) { + outLines.push(...formatCodeNodeSummariesCard(codeSummaries, job.id)); + } + return { stdout: `${outLines.join("\n")}\n`, stderr: "", diff --git a/src/cli/commands/workflow/node.ts b/src/cli/commands/workflow/node.ts index 49cf7f1..9f0ddf7 100644 --- a/src/cli/commands/workflow/node.ts +++ b/src/cli/commands/workflow/node.ts @@ -6,6 +6,7 @@ import { addWorkflowTask, editWorkflowTask, removeWorkflowTask, + applyNodeMapping, getWorkflowAvailableNodes, grantWorkflowNodes, } from "../../../domains/platform/services.js"; @@ -20,7 +21,7 @@ import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js"; import { createPiperClientForCorp } from "../../helpers.js"; import { createWorkflowDetailClient } from "./shared.js"; -const SUB_ACTIONS = new Set(["list", "ls", "get", "show", "info", "add", "append", "insert", "edit", "update", "set", "rm", "remove", "delete", "del"]); +const SUB_ACTIONS = new Set(["list", "ls", "get", "show", "info", "add", "append", "insert", "edit", "update", "set", "map", "rm", "remove", "delete", "del"]); const CORP_LEVEL_ACTIONS = new Set(["available", "list-available", "catalog", "probe", "grant", "open"]); export async function handleNodeCommand( @@ -78,6 +79,7 @@ export async function handleNodeCommand( " get <节点标识> 查看指定节点的完整配置 (别名: show, info)", " add [选项] 声明式追加或插入新任务节点 (别名: append, insert)", " edit <节点标识> 定向修改指定节点配置 (别名: update, set)", + " map <节点标识> 从映射文件批量更新深层字段 (别名: node map --mapping-file)", " rm <节点标识> 安全移除指定任务节点 (别名: remove, delete)", "", "子命令 (企业灰度节点级别):", @@ -110,6 +112,8 @@ export async function handleNodeCommand( case "update": case "set": return handleEditNode(pipelineId, nodeTarget, parsed, runtime); + case "map": + return handleMapNode(pipelineId, nodeTarget, parsed, runtime); case "rm": case "remove": case "delete": @@ -248,7 +252,17 @@ async function handleAddNode( stderr: [ "请指定新增节点类型: --type=<类型>", "常见类型: code-js2 (JS脚本), code (MVEL代码), http (HTTP请求), stop (终止流程), every (循环遍历), condition (分支条件)", - "示例: hose-use workflow node add 896398895352487950 --type=code-js2 --label='数据清洗' --yes", + "", + "常用选项:", + " --type= 节点类型 (如 code-js2 / code)", + " --label=<标题> 节点显示名称", + " --code-file=<脚本路径> (推荐) 从本地文件导入代码,避免终端转义与 Token 浪费", + " --code=<代码片段> 传入代码字符串(仅限简短代码)", + " --parent=<容器节点name> 插入指定容器节点内部 (如 every 循环)", + " --after=<前置节点name> 插入指定节点之后", + " --yes 确认追加", + "", + "示例: hose-use workflow node add 896398895352487950 --type=code-js2 --label='数据清洗' --code-file=./clean.js --yes", ].join("\n") + "\n", exitCode: 1, }; @@ -329,7 +343,21 @@ async function handleEditNode( if (!nodeTarget) { return { stdout: "", - stderr: "请提供节点标识 (name 或层级序号): hose-use workflow node edit [选项]\n", + stderr: [ + "请提供节点标识 (name 或层级序号): hose-use workflow node edit [选项]", + "", + "常用选项:", + " --label=<新名称> 更新节点显示标题", + " --code-file=<脚本路径> (推荐) 从本地文件导入最新脚本,避免终端转义与 Token 浪费", + " --code=<行内代码> 直接传入代码片段(短脚本)", + " --desc=<描述> 更新节点描述", + " --set='key=value' 定向修改节点自定义属性", + " --dry-run 只预览变更", + " --yes 确认保存修改", + "", + "示例:", + " hose-use workflow node edit 900682164608835609 action_cdd6fv --code-file=./clean.mvel --yes", + ].join("\n") + "\n", exitCode: 1, }; } @@ -359,6 +387,14 @@ async function handleEditNode( } } + const mappingFile = stringOption(parsed.options, ["mapping-file", "mapping", "file", "json-file"]); + if (mappingFile) { + const fs = await import("fs/promises"); + const rawContent = await fs.readFile(mappingFile, "utf-8"); + const mappingData = JSON.parse(rawContent); + return handleMapNode(pipelineId, nodeTarget, parsed, runtime, mappingData); + } + requireMutationConfirmation( parsed, runtime, @@ -384,7 +420,7 @@ async function handleEditNode( updatedFields: { ...(label ? { label } : {}), ...(desc ? { desc } : {}), - ...(code !== undefined ? { code: `${code.length} 字符` } : {}), + ...(code !== undefined ? { code: `${code.length} 字符${!codeFile && code.length > 300 ? " [TIP: 建议使用 --code-file= 从本地文件载入以规避转义错误并节省 Token]" : ""}` } : {}), ...customSet, }, }); @@ -400,8 +436,103 @@ async function handleEditNode( }; } + let codeTip = ""; + if (!codeFile && code && code.length > 300) { + codeTip = `\n💡 提示: 检测到通过命令行行内传入大段代码 (${code.length} 字符)。建议将脚本落地为本地文件并通过 --code-file=<路径> 传入,避免 Token 浪费与 Shell 转义风险。\n`; + } + return { - stdout: `✅ 节点 [${editedTask.name}] (${editedTask.label}) 修改已保存至工作流 [${pipelineId}]。\n`, + stdout: `✅ 节点 [${editedTask.name}] (${editedTask.label}) 修改已保存至工作流 [${pipelineId}]。\n${codeTip}`, + stderr: "", + exitCode: 0, + }; +} + +async function handleMapNode( + pipelineId: string, + nodeTarget: string, + parsed: CliParsedArgs, + runtime: CliRuntime, + injectedMappingData?: any +): Promise { + if (!nodeTarget) { + return { + stdout: "", + stderr: [ + "请提供目标节点标识 (name 或层级序号): hose-use workflow node map --mapping-file= [选项]", + "", + "常用选项:", + " --mapping-file=<路径> 包含字段映射的本地 JSON 文件 (可为字段数组或属性对象)", + " --dry-run 只预览变更", + " --yes 确认保存修改", + "", + "示例:", + " hose-use workflow node map 900682164608835609 action_datalink_create --mapping-file=./fields.json --yes", + ].join("\n") + "\n", + exitCode: 1, + }; + } + + let mappingData = injectedMappingData; + if (!mappingData) { + const mappingFile = stringOption(parsed.options, ["mapping-file", "mapping", "file", "json-file"]); + if (!mappingFile) { + return { + stdout: "", + stderr: "错误: 请通过 --mapping-file=<路径> 指定本地字段映射 JSON 文件\n", + exitCode: 1, + }; + } + const fs = await import("fs/promises"); + try { + const content = await fs.readFile(mappingFile, "utf-8"); + mappingData = JSON.parse(content); + } catch (e: any) { + return { + stdout: "", + stderr: `错误: 读取或解析映射文件失败: ${e.message}\n`, + exitCode: 1, + }; + } + } + + requireMutationConfirmation( + parsed, + runtime, + "批量映射工作流节点配置", + `hose-use workflow node map ${pipelineId} ${nodeTarget} --yes` + ); + + const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId); + const detail = await getWorkflowDetail(client, pipelineId); + + const { workflow: updatedWorkflow, editedTask, changedKeys } = applyNodeMapping(detail, nodeTarget, mappingData); + + if (isDryRun(parsed, runtime)) { + return mutationPreview(parsed, runtime, "批量映射工作流节点配置", `${pipelineId}:${editedTask.name}`, { + pipelineId, + nodeName: editedTask.name, + label: editedTask.label, + nodeType: editedTask.type, + changedKeys, + mappingSummary: Array.isArray(mappingData) + ? `数组格式更新 (${mappingData.length} 项)` + : `对象属性更新 (${Object.keys(mappingData).join(", ")})`, + }); + } + + const saveResult = await updateWorkflow(client, updatedWorkflow); + + if (runtime.jsonMode) { + return { + stdout: printJson({ success: true, pipelineId, editedTask, changedKeys, workflow: saveResult }, runtime.outputOptions), + stderr: "", + exitCode: 0, + }; + } + + return { + stdout: `✅ 节点 [${editedTask.name}] (${editedTask.label}) 已批量应用映射: ${changedKeys.join(", ")},并已保存至工作流 [${pipelineId}]。\n`, stderr: "", exitCode: 0, }; diff --git a/src/cli/commands/workflow/script.ts b/src/cli/commands/workflow/script.ts index b66d1e6..f364192 100644 --- a/src/cli/commands/workflow/script.ts +++ b/src/cli/commands/workflow/script.ts @@ -7,6 +7,7 @@ import { lintJavaScriptCode, lintMvelCode, executeJavaScriptSandbox, + executeMvelSandbox, } from "../../../domains/platform/services.js"; import { stringOption, booleanOption } from "../../parser.js"; import { printJson, printKeyValue } from "../../printer.js"; @@ -196,6 +197,8 @@ export async function handleWorkflowEvalScript( const codeInline = stringOption(parsed.options, ["code"]); const timeoutStr = stringOption(parsed.options, ["timeout"]); const timeoutMs = timeoutStr ? parseInt(timeoutStr, 10) : 3000; + const explicitType = (stringOption(parsed.options, ["type"]) || "").toLowerCase(); + const isMvel = explicitType === "code" || explicitType === "mvel" || (filePath ? filePath.endsWith(".mvel") : false); // 1. 获取输入参数 inputs let inputs: Record = {}; @@ -245,7 +248,9 @@ export async function handleWorkflowEvalScript( code = fs.readFileSync(filePath, "utf-8"); } - const evalResult = await executeJavaScriptSandbox(code, inputs, { timeoutMs }); + const evalResult = isMvel + ? await executeMvelSandbox(code, inputs, { timeoutMs }) + : await executeJavaScriptSandbox(code, inputs, { timeoutMs }); if (isJson) { return { stdout: printJson(evalResult, runtime.outputOptions), stderr: "", exitCode: evalResult.success ? 0 : 1 }; @@ -296,18 +301,7 @@ export async function handleWorkflowEvalScript( } const task = located.task; - if (task.type !== "code-js2") { - if (task.type === "code") { - return { - stdout: "", - stderr: [ - `节点 [${task.name}] 是 MVEL (code) 节点。`, - "当前本地离线沙箱仅支持 JavaScript (code-js2) 运行时仿真。", - "提示: 您可以使用 hose-use workflow lint-script 检查其括号与上游引用,或使用 hose-use workflow test 进行全链路调试。", - ].join("\n") + "\n", - exitCode: 1, - }; - } + if (task.type !== "code-js2" && task.type !== "code") { return { stdout: "", stderr: `节点 [${task.name}] 不是代码节点,类型为: ${task.type}\n`, @@ -316,6 +310,7 @@ export async function handleWorkflowEvalScript( } const code: string = (task as any).code || ""; + const isNodeMvel = task.type === "code"; // 如果没有显式传 input,尝试提取工作流样本数据 if (Object.keys(inputs).length === 0) { @@ -352,7 +347,9 @@ export async function handleWorkflowEvalScript( } } - const evalResult = await executeJavaScriptSandbox(code, inputs, { timeoutMs }); + const evalResult = isNodeMvel + ? await executeMvelSandbox(code, inputs, { timeoutMs }) + : await executeJavaScriptSandbox(code, inputs, { timeoutMs }); if (isJson) { return { stdout: printJson(evalResult, runtime.outputOptions), stderr: "", exitCode: evalResult.success ? 0 : 1 }; diff --git a/src/cli/commands/workflow/shared.ts b/src/cli/commands/workflow/shared.ts index b8dac45..5d0f13c 100644 --- a/src/cli/commands/workflow/shared.ts +++ b/src/cli/commands/workflow/shared.ts @@ -56,3 +56,105 @@ export async function createJobPiperClient( } return clients.easoClient; } + +export interface CodeNodeSummary { + id: string; + name: string; + label: string; + type: string; + status: string; + rawOutput: unknown; + summaryLines: string[]; +} + +export function extractCodeNodeSummaries( + nodes: Array, + flattenExecutionTreeFn?: (nodes: any[]) => any[] +): CodeNodeSummary[] { + const flattened = flattenExecutionTreeFn ? flattenExecutionTreeFn(nodes) : nodes; + const summaries: CodeNodeSummary[] = []; + + for (const node of flattened) { + if (!node) continue; + const type = String(node.type || ""); + if (type !== "code" && type !== "code-js2") continue; + + const rawOutput = node.output ?? node.outputs ?? node.details; + const summaryLines: string[] = []; + + if (rawOutput === undefined || rawOutput === null) { + summaryLines.push(" 出参: (无返回值或 null)"); + } else if (Array.isArray(rawOutput)) { + summaryLines.push(` 出参类型: Array (${rawOutput.length} 项)`); + if (rawOutput.length > 0) { + const first = rawOutput[0]; + if (first && typeof first === "object") { + const keys = ["planCode", "code", "id", "name", "title", "totalAmount", "amount"]; + const matchedKey = keys.find((k) => (first as Record)[k] !== undefined); + if (matchedKey) { + summaryLines.push(` 首项 ${matchedKey}: ${String((first as Record)[matchedKey])}`); + } + if ((first as any).amount !== undefined && matchedKey !== "amount") { + summaryLines.push(` 首项金额: ${String((first as any).amount)}`); + } + } else { + summaryLines.push(` 首项值: ${String(first)}`); + } + } + } else if (typeof rawOutput === "object") { + const obj = rawOutput as Record; + summaryLines.push(" 出参类型: Object"); + if (Array.isArray(obj.items)) { + summaryLines.push(` items.length: ${obj.items.length}`); + } + for (const k of ["planCode", "totalAmount", "count", "code", "total", "amount", "success"]) { + if (obj[k] !== undefined) { + summaryLines.push(` ${k}: ${String(obj[k])}`); + } + } + const allKeys = Object.keys(obj); + if (summaryLines.length === 1 && allKeys.length > 0) { + summaryLines.push(` 字段列表 (${allKeys.length} 个): ${allKeys.slice(0, 5).join(", ")}${allKeys.length > 5 ? "..." : ""}`); + } + } else { + summaryLines.push(` 出参值: ${String(rawOutput)}`); + } + + summaries.push({ + id: node.id || "-", + name: node.name || "-", + label: node.label || node.displayName || (type === "code" ? "MVEL代码节点" : "JS代码节点"), + type, + status: node.status || "UNKNOWN", + rawOutput, + summaryLines, + }); + } + + return summaries; +} + +export function formatCodeNodeSummariesCard( + summaries: CodeNodeSummary[], + jobId?: string +): string[] { + if (summaries.length === 0) return []; + + const lines: string[] = [ + "", + "── 🧮 核心代码节点出参即时摘要 (Code Return Values) ──", + ]; + + for (const s of summaries) { + const statusIcon = s.status === "COMPLETED" || s.status === "SUCCESS" ? "✅" : s.status === "FAILED" ? "❌" : "⏳"; + lines.push(` ${statusIcon} [${s.name}] ${s.label} (${s.type}, 状态: ${s.status})`); + for (const l of s.summaryLines) { + lines.push(` ${l}`); + } + if (jobId) { + lines.push(` ↳ 完整出参查看: hose-use workflow job ${jobId} --node=${s.name} --full`); + } + } + + return lines; +} diff --git a/src/cli/commands/workflow/test.ts b/src/cli/commands/workflow/test.ts index e7e6692..252e234 100644 --- a/src/cli/commands/workflow/test.ts +++ b/src/cli/commands/workflow/test.ts @@ -11,7 +11,7 @@ import { import { stringOption, booleanOption, numberOption } from "../../parser.js"; import { printJson, printTable, printKeyValue } from "../../printer.js"; import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js"; -import { createWorkflowDetailClient } from "./shared.js"; +import { createWorkflowDetailClient, extractCodeNodeSummaries, formatCodeNodeSummariesCard } from "./shared.js"; import { isDryRun, mutationPreview, requireMutationConfirmation } from "../../mutation.js"; export async function handleWorkflowTest( @@ -484,6 +484,11 @@ export async function handleWorkflowTest( } } + const codeSummaries = extractCodeNodeSummaries(report.executionTree); + if (codeSummaries.length > 0) { + outLines.push(...formatCodeNodeSummariesCard(codeSummaries, report.jobId)); + } + return { stdout: `${outLines.join("\n")}\n`, stderr: "", diff --git a/src/domains/feetype/feetype.test.ts b/src/domains/feetype/feetype.test.ts index 6af0416..f5bdb6e 100644 --- a/src/domains/feetype/feetype.test.ts +++ b/src/domains/feetype/feetype.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect } from "bun:test"; -import { flattenFeeTypeTree } from "./tools.js"; +import { flattenFeeTypeTree, collectSubtreeNodes } from "./tools.js"; import { FeeTypeNode } from "./types.js"; describe("domains/feetype > tools & helpers", () => { @@ -71,4 +71,15 @@ describe("domains/feetype > tools & helpers", () => { expect(flat[3].parentName).toBe(""); expect(flat[3].active).toBe(false); }); + + it("collectSubtreeNodes 正确收集指定子树及其全部后代", () => { + const subtree = collectSubtreeNodes(sampleTree, "node_1"); + expect(subtree.map((s) => s.id)).toEqual(["node_1", "node_1_1", "node_1_1_1"]); + + const leafSubtree = collectSubtreeNodes(sampleTree, "node_1_1_1"); + expect(leafSubtree.map((s) => s.id)).toEqual(["node_1_1_1"]); + + const missingSubtree = collectSubtreeNodes(sampleTree, "not_exist"); + expect(missingSubtree).toEqual([]); + }); }); diff --git a/src/domains/feetype/tools.ts b/src/domains/feetype/tools.ts index 080704c..2508674 100644 --- a/src/domains/feetype/tools.ts +++ b/src/domains/feetype/tools.ts @@ -60,6 +60,41 @@ export function flattenFeeTypeTree( return result; } +/** + * 递归收集 parentId 节点及其所有子孙节点的 FlatFeeTypeItem + */ +export function collectSubtreeNodes( + nodes: FeeTypeNode[], + parentId: string, + parentPath = "", + parentName = "" +): FlatFeeTypeItem[] { + for (const node of nodes) { + const item = node.feeType; + if (!item || !item.id) continue; + const currentPath = parentPath ? `${parentPath} / ${item.name}` : item.name; + const children = Array.isArray(node.children) ? node.children : []; + if (item.id === parentId || item.name === parentId || item.code.toLowerCase() === parentId.toLowerCase()) { + const result: FlatFeeTypeItem[] = []; + result.push({ + ...item, + path: currentPath, + parentName, + childrenCount: children.length, + }); + if (children.length > 0) { + result.push(...flattenFeeTypeTree(children, currentPath, item.name)); + } + return result; + } + if (children.length > 0) { + const found = collectSubtreeNodes(children, parentId, currentPath, item.name); + if (found.length > 0) return found; + } + } + return []; +} + /** * 清理组件字段 (参照易快报前端规范:删除内部状态与只读引用) */ @@ -127,12 +162,15 @@ export async function listFeeTypes( total: number; items: FlatFeeTypeItem[] | FeeTypeNode[]; rawTree: FeeTypeNode[]; + ids: string[]; }> { const rawTree = options.all ? await getFullFeeTypeTree(client, corpId) : await getActiveFeeTypeTree(client, corpId); - let flat = flattenFeeTypeTree(rawTree); + let flat = options.subtreeParentId + ? collectSubtreeNodes(rawTree, options.subtreeParentId) + : flattenFeeTypeTree(rawTree); if (options.keyword?.trim()) { const kw = options.keyword.trim().toLowerCase(); @@ -145,10 +183,14 @@ export async function listFeeTypes( ); } + const ids = flat.map((item) => item.id); + const useFlat = options.flat || Boolean(options.subtreeParentId) || Boolean(options.idsOnly); + return { total: flat.length, - items: options.flat ? flat : (options.keyword ? flat : rawTree), + items: useFlat ? flat : (options.keyword ? flat : rawTree), rawTree, + ids, }; } diff --git a/src/domains/feetype/types.ts b/src/domains/feetype/types.ts index da2e066..36e73f9 100644 --- a/src/domains/feetype/types.ts +++ b/src/domains/feetype/types.ts @@ -151,6 +151,8 @@ export interface FeeTypeQueryOptions { all?: boolean; keyword?: string; flat?: boolean; + subtreeParentId?: string; + idsOnly?: boolean; } export interface FeeTypeView { diff --git a/src/domains/platform/workflow/nodes/mutations.ts b/src/domains/platform/workflow/nodes/mutations.ts index c04fe14..56c253b 100644 --- a/src/domains/platform/workflow/nodes/mutations.ts +++ b/src/domains/platform/workflow/nodes/mutations.ts @@ -310,3 +310,45 @@ export function removeWorkflowTask( reindexTasks(cloned.tasks); return { workflow: cloned, removedTask }; } + +export type MappingContent = Array> | Record; + +/** + * 批量映射节点字段配置 (支持数组格式替换 fields,或对象格式深度设置属性) + */ +export function applyNodeMapping( + workflow: WorkflowDetail, + targetKey: string | number, + mapping: MappingContent +): { workflow: WorkflowDetail; editedTask: WorkflowTask; changedKeys: string[] } { + const cloned = JSON.parse(JSON.stringify(workflow)) as WorkflowDetail; + if (!cloned.tasks) cloned.tasks = []; + + const target = findWorkflowTask(cloned.tasks, targetKey); + if (!target) { + throw new NotFoundError(`未找到目标工作流任务节点: ${targetKey}`); + } + + const { task } = target; + const changedKeys: string[] = []; + + if (Array.isArray(mapping)) { + // 数组格式直接更新/替换 fields 数组 + (task as any).fields = mapping; + changedKeys.push(`fields (${mapping.length} 项)`); + } else if (mapping && typeof mapping === "object") { + // 对象格式:合并/设置每个顶层键 + for (const [key, value] of Object.entries(mapping)) { + (task as any)[key] = value; + if (Array.isArray(value)) { + changedKeys.push(`${key} (${value.length} 项)`); + } else { + changedKeys.push(key); + } + } + } else { + throw new ValidationError("映射内容必须为 JSON 数组或 JSON 对象"); + } + + return { workflow: cloned, editedTask: task, changedKeys }; +} diff --git a/src/domains/platform/workflow/script/index.test.ts b/src/domains/platform/workflow/script/index.test.ts index 35a859d..4f5f495 100644 --- a/src/domains/platform/workflow/script/index.test.ts +++ b/src/domains/platform/workflow/script/index.test.ts @@ -5,6 +5,7 @@ import { lintMvelCode, lintWorkflowScripts, executeJavaScriptSandbox, + executeMvelSandbox, } from "./index.js"; import type { WorkflowDetail } from "../../types.js"; @@ -275,4 +276,30 @@ describe("isolated script runtime boundaries", () => { expect((await executeJavaScriptSandbox('return Promise.resolve(1);')).success).toBe(false); expect((await executeJavaScriptSandbox('return 1;')).returnValue).toBe(1); }); + + describe("executeMvelSandbox", () => { + it("executes basic MVEL variable assignments, collections and return statements", async () => { + const mvel = [ + 'String planCode = "AMORT-001";', + 'int periods = 3;', + 'Map row = new HashMap();', + 'row.put("code", planCode);', + 'row.put("periods", periods);', + 'return row;', + ].join("\n"); + const result = await executeMvelSandbox(mvel); + expect(result.success).toBe(true); + expect(result.returnValue).toEqual({ code: "AMORT-001", periods: 3 }); + }); + + it("accesses inputs in MVEL code", async () => { + const mvel = [ + 'int total = amount * 2;', + 'return total;', + ].join("\n"); + const result = await executeMvelSandbox(mvel, { amount: 50 }); + expect(result.success).toBe(true); + expect(result.returnValue).toBe(100); + }); + }); }); diff --git a/src/domains/platform/workflow/script/sandbox.ts b/src/domains/platform/workflow/script/sandbox.ts index a51aa04..f817520 100644 --- a/src/domains/platform/workflow/script/sandbox.ts +++ b/src/domains/platform/workflow/script/sandbox.ts @@ -122,3 +122,54 @@ export async function executeJavaScriptSandbox( runtime?.dispose(); } } + +/** + * 转换 MVEL 常用语法为 QuickJS 可执行的 JavaScript,实现轻量仿真 + */ +export function transpileMvelToJs(mvelCode: string): string { + let js = mvelCode; + + // 1. 移除 Java 类型声明:如 String x =, int y =, List z =, Map m =, boolean b =, double d =, long l = + js = js.replace(/\b(String|int|Integer|long|Long|double|Double|float|Float|boolean|Boolean|List|Map|HashMap|ArrayList|Object)\s+([a-zA-Z_$][a-zA-Z0-9_$]*\s*=)/g, "var $2"); + js = js.replace(/\b(String|int|Integer|long|Long|double|Double|float|Float|boolean|Boolean|List|Map|HashMap|ArrayList|Object)\s+([a-zA-Z_$][a-zA-Z0-9_$]*\s*;)/g, "var $2"); + + // 2. 转换 new HashMap() / new ArrayList() + js = js.replace(/new\s+(?:HashMap|Map)\s*(?:\([^)]*\)|<[^>]*>\s*\([^)]*\))/g, "({})"); + js = js.replace(/new\s+(?:ArrayList|List)\s*(?:\([^)]*\)|<[^>]*>\s*\([^)]*\))/g, "([])"); + + // 3. 常见 Map/List 方法调用模拟: + // .put(k, v) -> [k] = v (包装为安全赋值辅助) + // 注入轻量 helper + const preamble = [ + "function _mvel_put(obj, key, val) { if (obj && typeof obj === 'object') { obj[key] = val; } return val; }", + "function _mvel_get(obj, key) { return obj ? obj[key] : undefined; }", + "function _mvel_size(obj) { if (!obj) return 0; if (Array.isArray(obj)) return obj.length; if (typeof obj === 'object') return Object.keys(obj).length; return 0; }", + "function _mvel_add(arr, item) { if (Array.isArray(arr)) arr.push(item); return arr; }", + "", + ].join("\n"); + + js = js.replace(/\.put\s*\(\s*([^,]+)\s*,\s*([^)]+)\s*\)/g, ""); // 避免直接正则冲突,使用下面逐行或更精确替换 + // 恢复并使用 helper + js = mvelCode; + js = js.replace(/\b(String|int|Integer|long|Long|double|Double|float|Float|boolean|Boolean|List|Map|HashMap|ArrayList|Object)\s+([a-zA-Z_$][a-zA-Z0-9_$]*\s*=)/g, "var $2"); + js = js.replace(/\b(String|int|Integer|long|Long|double|Double|float|Float|boolean|Boolean|List|Map|HashMap|ArrayList|Object)\s+([a-zA-Z_$][a-zA-Z0-9_$]*\s*;)/g, "var $2"); + js = js.replace(/new\s+(?:HashMap|Map)\s*(?:\([^)]*\)|<[^>]*>\s*\([^)]*\))/g, "({})"); + js = js.replace(/new\s+(?:ArrayList|List)\s*(?:\([^)]*\)|<[^>]*>\s*\([^)]*\))/g, "([])"); + js = js.replace(/\.put\s*\(\s*([^,]+)\s*,\s*([^)]+)\s*\)/g, "[$1] = $2"); + js = js.replace(/\.size\s*\(\s*\)/g, ".length"); + + return `${preamble}${js}`; +} + +/** + * 轻量仿真执行 MVEL 节点 + */ +export async function executeMvelSandbox( + code: string, + inputs: Record = {}, + options: { timeoutMs?: number } = {} +): Promise { + const transpiled = transpileMvelToJs(code); + const result = await executeJavaScriptSandbox(transpiled, inputs, options); + return result; +}