import { describe, expect, it } from "bun:test"; import { hasReturnStatement, lintJavaScriptCode, lintMvelCode, lintWorkflowScripts, executeJavaScriptSandbox, } from "./index.js"; import type { WorkflowDetail } from "../../types.js"; describe("workflow-script - 本地静态语法校验与沙箱仿真引擎", () => { describe("hasReturnStatement", () => { it("identifies return statement correctly", () => { expect(hasReturnStatement("const x = 1;\nreturn x + 2;")).toBe(true); expect(hasReturnStatement("// return 123;\nconst x = 1;")).toBe(false); expect(hasReturnStatement("/*\n * return false;\n */\nconst y = 2;")).toBe(false); expect(hasReturnStatement("const x = 'returning';")).toBe(false); }); }); describe("lintJavaScriptCode", () => { it("reports error for empty script", () => { const res = lintJavaScriptCode(" "); expect(res.issues.some((i) => i.rule === "empty-script")).toBe(true); expect(res.hasReturn).toBe(false); }); it("warns about missing return statement", () => { const res = lintJavaScriptCode("const a = 1; const b = 2;"); expect(res.issues.some((i) => i.rule === "missing-return")).toBe(true); expect(res.hasReturn).toBe(false); }); it("catches syntax errors with line numbers", () => { const res = lintJavaScriptCode("const a = 1;\nconst b = ;\nreturn a + b;"); expect(res.issues.some((i) => i.rule === "syntax-error" && i.level === "error")).toBe(true); }); it("accepts valid JavaScript with declared bound variables", () => { const code = ` const filtered = items.filter(x => x.amount > 0); return { count: filtered.length, items: filtered }; `; const res = lintJavaScriptCode(code, ["items"]); expect(res.issues).toHaveLength(0); expect(res.hasReturn).toBe(true); }); }); describe("lintMvelCode", () => { it("detects unclosed brackets in MVEL code", () => { const code = "var a = HashMap();\na.put('key', 123;"; const res = lintMvelCode(code); expect(res.issues.some((i) => i.rule === "unclosed-bracket")).toBe(true); }); it("detects mismatched brackets", () => { const code = "var a = (1 + 2]; return a;"; const res = lintMvelCode(code); expect(res.issues.some((i) => i.rule === "unmatched-brackets")).toBe(true); }); it("flags dangling node references if node does not exist in workflow", () => { const code = ` var upstream = action_non_existent; var r = new HashMap(); r.put("data", upstream); return r; `; const existing = new Set(["trigger_webhook", "action_calc"]); const res = lintMvelCode(code, existing); expect(res.issues.some((i) => i.rule === "dangling-node-reference")).toBe(true); expect(res.referencedNodes).toHaveLength(1); expect(res.referencedNodes[0].name).toBe("action_non_existent"); expect(res.referencedNodes[0].exists).toBe(false); }); it("passes clean MVEL code referencing existing nodes", () => { const code = ` import java.util.HashMap; var upstream = action_calc; var result = new HashMap(); result.put("val", upstream); return result; `; const existing = new Set(["trigger_webhook", "action_calc"]); const res = lintMvelCode(code, existing); expect(res.issues).toHaveLength(0); expect(res.referencedNodes[0].exists).toBe(true); }); }); describe("lintWorkflowScripts", () => { it("scans and reports issues across all workflow code nodes", () => { const mockWorkflow = { id: "pipe_lint_test", label: "测试流程", state: 0, tasks: [ { name: "trigger_1", type: "webhook", label: "触发器", groupName: "trigger", orderIndex: 0, levelIndex: [0], status: "active", }, { name: "action_js_bad", type: "code-js2", label: "语法错误JS", groupName: "action", orderIndex: 1, levelIndex: [1], status: "active", code: "const x = ; return x;", mapping: [], }, { name: "action_mvel_good", type: "code", label: "正常MVEL", groupName: "action", orderIndex: 2, levelIndex: [2], status: "active", code: "var a = trigger_1; return a;", }, ], } as unknown as WorkflowDetail; const report = lintWorkflowScripts(mockWorkflow); expect(report.totalCodeNodes).toBe(2); expect(report.validCount).toBe(1); expect(report.invalidCount).toBe(1); expect(report.allValid).toBe(false); const badReport = report.reports.find((r) => r.nodeName === "action_js_bad"); expect(badReport?.valid).toBe(false); expect(badReport?.issues.some((i) => i.rule === "syntax-error")).toBe(true); const goodReport = report.reports.find((r) => r.nodeName === "action_mvel_good"); expect(goodReport?.valid).toBe(true); }); }); describe("executeJavaScriptSandbox", () => { it("executes code in sandbox and returns computed values", async () => { const code = ` console.log("Processing records:", items.length); const total = items.reduce((sum, item) => sum + item.amount, 0); return { total, count: items.length }; `; const inputs = { items: [{ amount: 100 }, { amount: 250 }, { amount: 50 }], }; const res = await executeJavaScriptSandbox(code, inputs); expect(res.success).toBe(true); expect(res.returnValue).toEqual({ total: 400, count: 3 }); expect(res.logs).toHaveLength(1); expect(res.logs[0].message).toContain("Processing records: 3"); expect(res.durationMs).toBeGreaterThanOrEqual(0); }); it("catches runtime errors and reports line number", async () => { const code = ` const a = 10; const b = undefined; return b.nonExistentField.subField; `; const res = await executeJavaScriptSandbox(code, {}); expect(res.success).toBe(false); expect(res.error).toBeDefined(); expect(res.error?.name).toBe("TypeError"); expect(res.error?.message).toContain("undefined"); expect(res.error?.line).toBe(4); }); it("terminates on infinite loops via timeout", async () => { const code = "while (true) {}"; const res = await executeJavaScriptSandbox(code, {}, { timeoutMs: 100 }); expect(res.success).toBe(false); expect(res.error?.message).toContain("timed out"); }); }); }); describe("MVEL lexical boundaries", () => { for (const code of [ 'return "{";', 'return wrap("https://example.test/path");', '/* { action_missing */\nreturn 1;', 'return "action_missing";', "return 'escaped \\' { action_missing';", '/* comment with "quotes" and // */\r\nreturn [1, 2]; // { action_missing', ]) { it(`ignores literals and comments in ${JSON.stringify(code)}`, () => { const result = lintMvelCode(code, new Set()); expect(result.issues).toEqual([]); expect(result.referencedNodes).toEqual([]); expect(result.hasReturn).toBe(true); }); } it("does not count quoted or commented return as executable code", () => { const result = lintMvelCode('value = "return"; /* return 1; */ // return 2;'); expect(result.hasReturn).toBe(false); expect(result.issues.map(i => i.rule)).toEqual(["missing-return"]); }); it("keeps real references and error coordinates while diagnosing unfinished literals", () => { const result = lintMvelCode('// ]\nreturn action_missing;]', new Set()); expect(result.issues.find(i => i.rule === "unmatched-brackets")).toMatchObject({ line: 2, column: 23 }); expect(result.issues.find(i => i.rule === "dangling-node-reference")?.level).toBe("error"); expect(lintMvelCode('return "unfinished').issues.some(i => i.rule === "unterminated-string")).toBe(true); expect(lintMvelCode('return 1;\n /* unfinished').issues.find(i => i.rule === "unterminated-comment")).toMatchObject({ line: 2, column: 3 }); }); it("does not invalidate an entire workflow for literal-only node names", () => { const result = lintWorkflowScripts({ id: "lexical", tasks: [{ name: "action_code", type: "code", code: 'return "action_missing {";' }] } as unknown as WorkflowDetail); expect(result.allValid).toBe(true); }); });