001/**
002 * Copyright (c) 2025-2026, Michael Yang 杨福海 (fuhai999@gmail.com).
003 * <p>
004 * Licensed under the GNU Lesser General Public License (LGPL) ,Version 3.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 * <p>
008 * http://www.gnu.org/licenses/lgpl-3.0.txt
009 * <p>
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016package dev.tinyflow.core.code;
017
018import com.alibaba.qlexpress4.Express4Runner;
019import com.alibaba.qlexpress4.InitOptions;
020import com.alibaba.qlexpress4.QLOptions;
021import dev.tinyflow.core.chain.Chain;
022import dev.tinyflow.core.node.CodeNode;
023
024import java.util.HashMap;
025import java.util.Map;
026
027public class QLExpressRuntimeEngine implements CodeRuntimeEngine {
028    @Override
029    public Map<String, Object> execute(String code, CodeNode node, Chain chain) {
030        Express4Runner runner = new Express4Runner(InitOptions.DEFAULT_OPTIONS);
031        Map<String, Object> context = new HashMap<>();
032
033        Map<String, Object> parameterValues = chain.getState().resolveParameters(node);
034        if (parameterValues != null) context.putAll(parameterValues);
035
036        Map<String, Object> result = new HashMap<>();
037        context.put("_result", result);
038        context.put("_chain", chain);
039        context.put("_state", chain.getNodeState(node.getId()));
040
041        try {
042            runner.execute(code, context, QLOptions.DEFAULT_OPTIONS);
043        } catch (Exception e) {
044            throw new RuntimeException(e);
045        }
046        return result;
047    }
048}