fix: address Codex PR review findings
This commit is contained in:
1 parent
0f164b6de5
commit
a7974abb08
44 files changed
+3317
-667
No files matched your search
@@ -230,7 +230,7 @@ describe("MVEL lexical boundaries", () => {
|
||||
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"]);
|
||||
expect(result.issues).toEqual([]); // 赋值本身可作为末尾表达式,仍不算显式 return。
|
||||
});
|
||||
|
||||
it("keeps real references and error coordinates while diagnosing unfinished literals", () => {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { WorkflowTask } from "../../types.js";
|
||||
import type { ScriptIssue } from "./types.js";
|
||||
import { hasMvelFinalExpression } from "./mvel-subset.js";
|
||||
|
||||
/** Mask literals/comments without moving offsets used by diagnostics. */
|
||||
function scanMvelCode(code: string, issues: ScriptIssue[]): string {
|
||||
@@ -84,10 +85,10 @@ export function lintMvelCode(
|
||||
|
||||
const executableCode = scanMvelCode(code, issues);
|
||||
const hasRet = /\breturn\b/.test(executableCode);
|
||||
if (!hasRet) {
|
||||
if (!hasRet && !hasMvelFinalExpression(code)) {
|
||||
issues.push({
|
||||
level: "warning",
|
||||
message: "MVEL 代码中未发现 return 语句,合思代码节点通常需要 return 包装后的 Map 或结果对象",
|
||||
message: "MVEL 代码中未发现显式 return 或可确定的末尾结果表达式;请确认所需结果位于脚本末尾",
|
||||
rule: "missing-return",
|
||||
});
|
||||
}
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { executeJavaScriptSandbox, executeMvelSandbox } from "./sandbox.js";
|
||||
import { lintMvelCode } from "./lint-mvel.js";
|
||||
|
||||
describe("MVEL collection and completion subset", () => {
|
||||
test.each(["HashMap", "Map", "java.util.HashMap"])("returns the final Map expression constructed with %s", async kind => {
|
||||
const result = await executeMvelSandbox(`Map result = new ${kind}(); result.put("value", 7); result;`);
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.returnValue).toEqual({ value: 7 });
|
||||
});
|
||||
|
||||
test.each(["ArrayList", "List", "java.util.ArrayList"])("supports List constructor %s", async kind => {
|
||||
const result = await executeMvelSandbox(`List result = new ${kind}(); result.add(7); result;`);
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.returnValue).toEqual([7]);
|
||||
const direct = await executeMvelSandbox(`new ${kind}().size();`);
|
||||
expect(direct.success).toBe(true);
|
||||
expect(direct.returnValue).toBe(0);
|
||||
});
|
||||
|
||||
test("counts Map keys including length and prototype names, without double counting replacements", async () => {
|
||||
const result = await executeMvelSandbox(`Map m = new HashMap(); List sizes = new ArrayList();
|
||||
sizes.add(m.size()); m.put("length", 99); sizes.add(m.size());
|
||||
m.put("length", 100); sizes.add(m.size()); m.put("__proto__", 8); sizes.add(m.size());
|
||||
sizes.add(m.get("absent")); sizes;`);
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.returnValue).toEqual([0, 1, 1, 2, null]);
|
||||
});
|
||||
|
||||
test("supports nested receivers, nested arguments, indexed inputs and collection return values", async () => {
|
||||
const nested = await executeMvelSandbox(`Map m = new HashMap(); List a = new ArrayList();
|
||||
a.add(Math.max(2, 3)); m.put("items", a); m.get("items").add(m.get("items").size());
|
||||
data.get("rows")[0].put("x", 2); a.add((data.get("rows")[0]).size()); m.get("items");`, { data: { rows: [{}] } });
|
||||
expect(nested.success).toBe(true);
|
||||
expect(nested.returnValue).toEqual([3, 1, 1]);
|
||||
});
|
||||
|
||||
test("preserves literal contents while ignoring comments during conversion", async () => {
|
||||
const literal = 'String x = new java.util.HashMap(); .put("x", 1).size() / 2 ? a : b;';
|
||||
const result = await executeMvelSandbox(`/* new Unsafe(); return 8; */ // new ArrayList(2)
|
||||
${JSON.stringify(literal)}; // final comment`);
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.returnValue).toBe(literal);
|
||||
});
|
||||
|
||||
test.each(["result", "(result);", "result;;; // final comment", "result /* ; return 0; */"])("supports tail expression %s", async tail => {
|
||||
const result = await executeMvelSandbox(`var result = 7; ${tail}`);
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.returnValue).toBe(7);
|
||||
});
|
||||
|
||||
test("evaluates a terminal expression once and preserves put's previous-value return", async () => {
|
||||
const increment = await executeMvelSandbox("var count = 0; ++count;");
|
||||
expect(increment.success).toBe(true);
|
||||
expect(increment.returnValue).toBe(1);
|
||||
const put = await executeMvelSandbox('Map m = new HashMap(); m.put("x", 1); m.put("x", 2);');
|
||||
expect(put.success).toBe(true);
|
||||
expect(put.returnValue).toBe(1);
|
||||
});
|
||||
|
||||
test("preserves division, ternary, classic for and explicit return compatibility", async () => {
|
||||
const result = await executeMvelSandbox("int total = 0; for (int i = 0; i < 3; i++) { total += i; } if (total == 3) { total += 2; } else { total = 0; } return total > 0 ? total / 2 : 0;");
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.returnValue).toBe(2.5);
|
||||
const assignment = await executeMvelSandbox("var x = 0; x = 9;");
|
||||
expect(assignment.returnValue).toBe(9);
|
||||
});
|
||||
|
||||
test("does not reject existing JavaScript-compatible blocks before a terminal result", async () => {
|
||||
const result = await executeMvelSandbox('function value() { return 8; } var result = 0; try { throw "probe"; } catch (error) { result = value(); } finally { result += 1; } result;');
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.returnValue).toBe(9);
|
||||
});
|
||||
|
||||
test.each(["new java.util.Date();", "new HashMap(5);", "new java.util.ArrayList(2);", "Map<String, Object> m = new HashMap(); m;", "if (true) { 7; }", "var value = 7;", "for (item : items) { item; } item;"])("rejects unsupported syntax or completion: %s", async code => {
|
||||
const result = await executeMvelSandbox(code);
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.error?.name).toBe("UnsupportedMvelSyntax");
|
||||
});
|
||||
|
||||
test("fails explicitly for invalid receiver types and List bounds", async () => {
|
||||
for (const code of ['value.size();', 'value.get(1);']) {
|
||||
const result = await executeMvelSandbox(code, { value: code.includes("get") ? [] : 7 });
|
||||
expect(result.success).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
test("keeps the execution time budget and JavaScript completion behavior", async () => {
|
||||
const result = await executeMvelSandbox("while (true) {} 7;", {}, { timeoutMs: 10 });
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.error?.message).toContain("timed out");
|
||||
const js = await executeJavaScriptSandbox("7;");
|
||||
expect(js.success).toBe(true);
|
||||
expect(js.returnValue).toBeUndefined();
|
||||
});
|
||||
|
||||
test("lint accepts a final expression without changing explicit hasReturn meaning", () => {
|
||||
const result = lintMvelCode('Map result = new java.util.HashMap(); result.put("x", 7); result;');
|
||||
expect(result.hasReturn).toBe(false);
|
||||
expect(result.issues).toEqual([]);
|
||||
expect(lintMvelCode("var x = 1;").issues.map(issue => issue.rule)).toContain("missing-return");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,203 @@
|
||||
import { ValidationError } from "../../../../core/errors.js";
|
||||
|
||||
function unsupported(message: string): never {
|
||||
throw new ValidationError(`本地 MVEL 子集不支持 ${message};请使用真实 MVEL 运行时验证`);
|
||||
}
|
||||
|
||||
/** 字符串作为完整 token 保留;注释不参与语法转换。 */
|
||||
function tokenize(source: string): string[] {
|
||||
const tokens: string[] = [];
|
||||
const pattern = /\s+|\/\/[^\r\n]*|\/\*[\s\S]*?\*\/|"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|[A-Za-z_$][\w$]*|(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?|>>>=|===|!==|>>>|<<=|>>=|\*\*=|==|!=|<=|>=|&&|\|\||\+\+|--|\+=|-=|\*=|\/=|%=|<<|>>|\*\*|[{}()[\].,;:+*/%=&|^~!<>?-]/y;
|
||||
let offset = 0;
|
||||
while (offset < source.length) {
|
||||
pattern.lastIndex = offset;
|
||||
const match = pattern.exec(source);
|
||||
if (!match) unsupported(`字符 ${JSON.stringify(source[offset])}(偏移 ${offset})`);
|
||||
const token = match[0];
|
||||
offset = pattern.lastIndex;
|
||||
if (!/^\s|^\/\//.test(token) && !token.startsWith("/*")) tokens.push(token);
|
||||
}
|
||||
return tokens;
|
||||
}
|
||||
|
||||
function closing(tokens: string[], start: number): number {
|
||||
const stack: string[] = [];
|
||||
const pairs: Record<string, string> = { "(": ")", "[": "]", "{": "}" };
|
||||
for (let i = start; i < tokens.length; i++) {
|
||||
const token = tokens[i];
|
||||
if (pairs[token]) stack.push(pairs[token]);
|
||||
else if ([")", "]", "}"].includes(token)) {
|
||||
if (stack.pop() !== token) unsupported("不匹配的括号");
|
||||
if (!stack.length) return i;
|
||||
}
|
||||
}
|
||||
return unsupported("未闭合的括号");
|
||||
}
|
||||
|
||||
type Statement = { start: number; end: number; kind: "expression" | "return" | "declaration" | "compound" | "empty" };
|
||||
|
||||
/** 只识别语句边界,不模拟复合语句在 MVEL 中的完成值。 */
|
||||
function statementAt(tokens: string[], start: number): Statement {
|
||||
const token = tokens[start];
|
||||
const finish = (end: number, kind: Statement["kind"]): Statement => ({ start, end, kind });
|
||||
if (token === ";") return finish(start + 1, "empty");
|
||||
if (token === "{") return finish(closing(tokens, start) + 1, "compound");
|
||||
if (["if", "for", "while", "switch"].includes(token)) {
|
||||
if (tokens[start + 1] !== "(") unsupported(`${token} 语句`);
|
||||
const conditionEnd = closing(tokens, start + 1);
|
||||
if (token === "for") {
|
||||
// 三元表达式仍可使用冒号;没有分号的增强 for 不属于本地子集。
|
||||
const header = tokens.slice(start + 2, conditionEnd);
|
||||
if (!header.includes(";") && header.includes(":")) unsupported("增强 for 循环");
|
||||
}
|
||||
if (conditionEnd + 1 >= tokens.length) unsupported(`${token} 缺少语句体`);
|
||||
let end = statementAt(tokens, conditionEnd + 1).end;
|
||||
if (token === "if" && tokens[end] === "else") end = statementAt(tokens, end + 1).end;
|
||||
return finish(end, "compound");
|
||||
}
|
||||
if (token === "do") {
|
||||
const bodyEnd = statementAt(tokens, start + 1).end;
|
||||
if (tokens[bodyEnd] !== "while" || tokens[bodyEnd + 1] !== "(") unsupported("do/while 语句");
|
||||
const end = closing(tokens, bodyEnd + 1) + 1;
|
||||
return finish(tokens[end] === ";" ? end + 1 : end, "compound");
|
||||
}
|
||||
if (token === "try") {
|
||||
let end = statementAt(tokens, start + 1).end;
|
||||
if (tokens[end] === "catch") {
|
||||
end++;
|
||||
if (tokens[end] === "(") end = closing(tokens, end) + 1;
|
||||
end = statementAt(tokens, end).end;
|
||||
}
|
||||
if (tokens[end] === "finally") end = statementAt(tokens, end + 1).end;
|
||||
return finish(end, "compound");
|
||||
}
|
||||
if (token === "function" || token === "class") {
|
||||
let body = start + 1;
|
||||
while (body < tokens.length && tokens[body] !== "{") {
|
||||
if (tokens[body] === "(") body = closing(tokens, body);
|
||||
body++;
|
||||
}
|
||||
if (body >= tokens.length) unsupported(`${token} 缺少语句体`);
|
||||
return finish(closing(tokens, body) + 1, "declaration");
|
||||
}
|
||||
if (["catch", "finally", "import", "package"].includes(token)) unsupported(`${token} 语句`);
|
||||
let end = start;
|
||||
while (end < tokens.length && tokens[end] !== ";") {
|
||||
if (["(", "[", "{"].includes(tokens[end])) end = closing(tokens, end);
|
||||
else if ([")", "]", "}"].includes(tokens[end])) unsupported("不匹配的括号");
|
||||
end++;
|
||||
}
|
||||
if (tokens[end] === ";") end++;
|
||||
const kind = token === "return" || token === "throw" ? "return" : ["var", "let", "const"].includes(token) ? "declaration" : "expression";
|
||||
return finish(end, kind);
|
||||
}
|
||||
|
||||
function finalStatement(tokens: string[]): Statement | undefined {
|
||||
let last: Statement | undefined;
|
||||
for (let i = 0; i < tokens.length;) {
|
||||
const statement = statementAt(tokens, i);
|
||||
if (statement.kind !== "empty") last = statement;
|
||||
i = statement.end;
|
||||
}
|
||||
return last;
|
||||
}
|
||||
|
||||
const declarations = new Set(["String", "int", "Integer", "long", "Long", "double", "Double", "float", "Float", "boolean", "Boolean", "List", "Map", "HashMap", "ArrayList", "Object"]);
|
||||
|
||||
/** lint 保留 hasReturn 的显式 return 含义,同时识别可确定的末尾表达式。 */
|
||||
export function hasMvelFinalExpression(source: string): boolean {
|
||||
try {
|
||||
const tokens = tokenize(source);
|
||||
const tail = finalStatement(tokens);
|
||||
return tail?.kind === "expression" && !declarations.has(tokens[tail.start]);
|
||||
} catch {
|
||||
// 原生 MVEL 可能超出本地子集,静态 lint 不因此宣告其语法非法。
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function receiverStart(tokens: string[], end: number): number {
|
||||
let start = end;
|
||||
if (tokens[end] === ")" || tokens[end] === "]") {
|
||||
const opening = tokens[end] === ")" ? "(" : "[";
|
||||
let depth = 1;
|
||||
while (--start >= 0) {
|
||||
if (tokens[start] === tokens[end]) depth++;
|
||||
if (tokens[start] === opening && --depth === 0) break;
|
||||
}
|
||||
if (start < 0) unsupported("缺少方法接收对象");
|
||||
const previous = tokens[start - 1];
|
||||
const previousIsName = /^[A-Za-z_$][\w$]*$/.test(previous ?? "") && !["return", "throw", "if", "while", "for", "switch"].includes(previous);
|
||||
// 数组字面量不是索引表达式;不能把前面的 return/赋值运算符当作接收对象。
|
||||
if (previousIsName || (opening === "[" && [")", "]"].includes(previous))) start = receiverStart(tokens, start - 1);
|
||||
}
|
||||
if (tokens[start - 1] === ".") start = receiverStart(tokens, start - 2);
|
||||
if (start < 0) unsupported("缺少方法接收对象");
|
||||
return start;
|
||||
}
|
||||
|
||||
const arities: Record<string, number> = { put: 2, get: 1, size: 0, add: 1 };
|
||||
|
||||
function rewriteMethods(input: string[]): string[] {
|
||||
const tokens = [...input];
|
||||
for (let i = 1; i < tokens.length - 2; i++) {
|
||||
const method = tokens[i + 1];
|
||||
if (tokens[i] !== "." || tokens[i + 2] !== "(" || !Object.hasOwn(arities, method)) continue;
|
||||
const end = closing(tokens, i + 2);
|
||||
const args: string[][] = [];
|
||||
let from = i + 3;
|
||||
for (let j = from; j < end; j++) {
|
||||
if (["(", "[", "{"].includes(tokens[j])) j = closing(tokens, j);
|
||||
else if (tokens[j] === ",") { args.push(tokens.slice(from, j)); from = j + 1; }
|
||||
}
|
||||
if (from < end) args.push(tokens.slice(from, end));
|
||||
if (args.length !== arities[method] || args.some(arg => !arg.length)) unsupported(`${method} 的该参数数量`);
|
||||
const start = receiverStart(tokens, i - 1);
|
||||
const replacement = [`__hose_mvel_${method}`, "(", ...tokens.slice(start, i)];
|
||||
for (const arg of args) replacement.push(",", ...rewriteMethods(arg));
|
||||
replacement.push(")");
|
||||
tokens.splice(start, end - start + 1, ...replacement);
|
||||
i = start + replacement.length - 1;
|
||||
}
|
||||
return tokens;
|
||||
}
|
||||
|
||||
/** 必要的 MVEL 集合与末尾表达式子集;运算仍由隔离 QuickJS 执行。 */
|
||||
export function transpileMvelSubset(source: string): string {
|
||||
const tokens = tokenize(source);
|
||||
for (let i = 0; i < tokens.length; i++) {
|
||||
const token = tokens[i];
|
||||
if (/^__hose_mvel_/.test(token)) unsupported("保留的内部标识符");
|
||||
if (declarations.has(token) && tokens[i + 1] === "<") unsupported("泛型声明");
|
||||
// 1. 移除 Java 类型声明:如 String x =, int y =, List z =, Map m =, boolean b =, double d =, long l =
|
||||
if (declarations.has(token) && /^[A-Za-z_$][\w$]*$/.test(tokens[i + 1] ?? "") && ["=", ";"].includes(tokens[i + 2])) tokens[i] = "var";
|
||||
// 2. 转换 new HashMap() / new ArrayList(),仅精确扩展两个全限定名零参构造器。
|
||||
if (token === "new") {
|
||||
let end = i + 1;
|
||||
while (/^[A-Za-z_$][\w$]*$/.test(tokens[end] ?? "") && tokens[end + 1] === ".") end += 2;
|
||||
const kind = tokens.slice(i + 1, end + 1).join("");
|
||||
const map = ["HashMap", "Map", "java.util.HashMap"].includes(kind);
|
||||
if ((!map && !["ArrayList", "List", "java.util.ArrayList"].includes(kind)) || tokens[end + 1] !== "(" || tokens[end + 2] !== ")") unsupported("该构造器、泛型或构造参数");
|
||||
tokens.splice(i, end + 3 - i, ...(map ? ["__hose_mvel_map", "(", ")"] : ["[", "]"]));
|
||||
}
|
||||
}
|
||||
// 3. 常见 Map/List 方法调用模拟:
|
||||
// .put(k, v) -> [k] = v (包装为安全赋值辅助)
|
||||
// 注入轻量 helper;按 token 边界处理,避免直接正则冲突,并保留方法返回值。
|
||||
const rewritten = rewriteMethods(tokens);
|
||||
const tail = finalStatement(rewritten);
|
||||
if (!tail || !["return", "expression"].includes(tail.kind)) unsupported("末项复合语句或声明的完成值;请添加明确的末尾结果表达式");
|
||||
if (tail.kind === "expression") {
|
||||
const end = rewritten[tail.end - 1] === ";" ? tail.end - 1 : tail.end;
|
||||
rewritten.splice(tail.start, tail.end - tail.start, "return", "(", ...rewritten.slice(tail.start, end), ")", ";");
|
||||
}
|
||||
// 恢复并使用 helper,Map 使用自身属性,避免原型键影响集合语义。
|
||||
const preamble = `
|
||||
function __hose_mvel_map() { return Object.create(null); }
|
||||
function __hose_mvel_put(obj, key, val) { if (!obj || Array.isArray(obj) || typeof obj !== 'object') throw new TypeError('put requires Map'); if (typeof key !== 'string') throw new TypeError('MVEL subset supports string Map keys only'); const old = Object.hasOwn(obj, key) ? obj[key] : null; Object.defineProperty(obj, key, {value:val, writable:true, enumerable:true, configurable:true}); return old; }
|
||||
function __hose_mvel_get(obj, key) { if (!obj || typeof obj !== 'object') throw new TypeError('get requires Map/List'); if (Array.isArray(obj)) { if (!Number.isInteger(key) || key < 0 || key >= obj.length) throw new RangeError('List index out of bounds'); } else if (typeof key !== 'string') throw new TypeError('MVEL subset supports string Map keys only'); return Object.hasOwn(obj, key) ? obj[key] : null; }
|
||||
function __hose_mvel_size(obj) { if (!obj || typeof obj !== 'object') throw new TypeError('size requires Map/List'); return Array.isArray(obj) ? obj.length : Object.keys(obj).length; }
|
||||
function __hose_mvel_add(arr, item) { if (!Array.isArray(arr)) throw new TypeError('add requires List'); arr.push(item); return true; }
|
||||
`;
|
||||
return preamble + rewritten.join(" ");
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import variant from "@jitl/quickjs-singlefile-cjs-release-sync";
|
||||
import { newQuickJSWASMModuleFromVariant } from "quickjs-emscripten-core";
|
||||
import type { ScriptEvalResult, ScriptEvalLog } from "./types.js";
|
||||
import { transpileMvelSubset } from "./mvel-subset.js";
|
||||
|
||||
const MAX_MEMORY_BYTES = 32 * 1024 * 1024;
|
||||
const MAX_VALUE_BYTES = 1024 * 1024;
|
||||
@@ -127,38 +128,7 @@ export async function executeJavaScriptSandbox(
|
||||
* 转换 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}`;
|
||||
return transpileMvelSubset(mvelCode);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -169,7 +139,12 @@ export async function executeMvelSandbox(
|
||||
inputs: Record<string, unknown> = {},
|
||||
options: { timeoutMs?: number } = {}
|
||||
): Promise<ScriptEvalResult> {
|
||||
const transpiled = transpileMvelToJs(code);
|
||||
const result = await executeJavaScriptSandbox(transpiled, inputs, options);
|
||||
return result;
|
||||
const start = performance.now();
|
||||
try {
|
||||
const transpiled = transpileMvelToJs(code);
|
||||
return await executeJavaScriptSandbox(transpiled, inputs, options);
|
||||
} catch (error) {
|
||||
return { success: false, durationMs: Number((performance.now() - start).toFixed(2)), returnValue: undefined, logs: [],
|
||||
error: { name: "UnsupportedMvelSyntax", message: (error as Error).message }, inputs };
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user