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.parser;
017
018import com.agentsflex.core.chain.Chain;
019import com.agentsflex.core.chain.ChainEdge;
020import com.agentsflex.core.chain.ChainNode;
021import com.agentsflex.core.chain.JsCodeCondition;
022import com.agentsflex.core.util.CollectionUtil;
023import com.agentsflex.core.util.StringUtil;
024import com.alibaba.fastjson.JSON;
025import com.alibaba.fastjson.JSONArray;
026import com.alibaba.fastjson.JSONObject;
027import dev.tinyflow.core.Tinyflow;
028import dev.tinyflow.core.parser.impl.*;
029
030import java.util.HashMap;
031import java.util.Map;
032
033public class ChainParser {
034
035    private Map<String, NodeParser> nodeParserMap = new HashMap<>();
036
037    public ChainParser() {
038
039        initDefaultParsers();
040    }
041
042    private void initDefaultParsers() {
043        nodeParserMap.put("startNode", new StartNodeParser());
044        nodeParserMap.put("codeNode", new CodeNodeParser());
045        nodeParserMap.put("confirmNode", new ConfirmNodeParser());
046
047        nodeParserMap.put("httpNode", new HttpNodeParser());
048        nodeParserMap.put("knowledgeNode", new KnowledgeNodeParser());
049        nodeParserMap.put("loopNode", new LoopNodeParser());
050        nodeParserMap.put("searchEngineNode", new SearchEngineNodeParser());
051        nodeParserMap.put("templateNode", new TemplateNodeParser());
052
053        nodeParserMap.put("endNode", new EndNodeParser());
054        nodeParserMap.put("llmNode", new LlmNodeParser());
055    }
056
057    public Map<String, NodeParser> getNodeParserMap() {
058        return nodeParserMap;
059    }
060
061    public void setNodeParserMap(Map<String, NodeParser> nodeParserMap) {
062        this.nodeParserMap = nodeParserMap;
063    }
064
065    public void addNodeParser(String type, NodeParser nodeParser) {
066        this.nodeParserMap.put(type, nodeParser);
067    }
068
069    public Chain parse(Tinyflow tinyflow) {
070        String jsonString = tinyflow.getData();
071        if (StringUtil.noText(jsonString)) {
072            return null;
073        }
074
075        JSONObject root = JSON.parseObject(jsonString);
076        JSONArray nodes = root.getJSONArray("nodes");
077        JSONArray edges = root.getJSONArray("edges");
078
079        return parse(tinyflow, nodes, edges, null);
080    }
081
082    public Chain parse(Tinyflow tinyflow, JSONArray nodes, JSONArray edges, JSONObject parentNode) {
083        if (CollectionUtil.noItems(nodes) || CollectionUtil.noItems(edges)) {
084            return null;
085        }
086
087        Chain chain = new Chain();
088        for (int i = 0; i < nodes.size(); i++) {
089            JSONObject nodeObject = nodes.getJSONObject(i);
090            if ((parentNode == null && StringUtil.noText(nodeObject.getString("parentId")))
091                    || (parentNode != null && parentNode.getString("id").equals(nodeObject.getString("parentId")))) {
092                ChainNode node = parseNode(tinyflow, nodeObject);
093                if (node != null) {
094                    chain.addNode(node);
095                }
096            }
097        }
098
099        for (int i = 0; i < edges.size(); i++) {
100            JSONObject edgeObject = edges.getJSONObject(i);
101            JSONObject edgeData = edgeObject.getJSONObject("data");
102
103            if ((parentNode == null && (edgeData == null || StringUtil.noText(edgeData.getString("parentNodeId"))))
104                    || (parentNode != null && edgeData != null && edgeData.getString("parentNodeId").equals(parentNode.getString("id"))
105                    //不添加子流程里的第一条 edge(也就是父节点连接子节点的第一条线)
106                    && !parentNode.getString("id").equals(edgeObject.getString("source")))) {
107                ChainEdge edge = parseEdge(edgeObject);
108                if (edge != null) {
109                    chain.addEdge(edge);
110                }
111            }
112        }
113
114        return chain;
115    }
116
117    private ChainNode parseNode(Tinyflow tinyflow, JSONObject nodeObject) {
118        String type = nodeObject.getString("type");
119        if (StringUtil.noText(type)) {
120            return null;
121        }
122
123        NodeParser nodeParser = nodeParserMap.get(type);
124        return nodeParser == null ? null : nodeParser.parse(nodeObject, tinyflow);
125    }
126
127
128    private ChainEdge parseEdge(JSONObject edgeObject) {
129        if (edgeObject == null) return null;
130        ChainEdge edge = new ChainEdge();
131        edge.setId(edgeObject.getString("id"));
132        edge.setSource(edgeObject.getString("source"));
133        edge.setTarget(edgeObject.getString("target"));
134
135        JSONObject data = edgeObject.getJSONObject("data");
136        if (data == null || data.isEmpty()) {
137            return edge;
138        }
139
140        String conditionString = data.getString("condition");
141        if (StringUtil.hasText(conditionString)) {
142            edge.setCondition(new JsCodeCondition(conditionString.trim()));
143        }
144        return edge;
145    }
146}