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.JavascriptStringCondition;
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
046        nodeParserMap.put("httpNode", new HttpNodeParser());
047        nodeParserMap.put("knowledgeNode", new KnowledgeNodeParser());
048        nodeParserMap.put("loopNode", new LoopNodeParser());
049        nodeParserMap.put("searchEngineNode", new SearchEngineNodeParser());
050        nodeParserMap.put("templateNode", new TemplateNodeParser());
051
052        nodeParserMap.put("endNode", new EndNodeParser());
053        nodeParserMap.put("llmNode", new LlmNodeParser());
054    }
055
056    public Map<String, NodeParser> getNodeParserMap() {
057        return nodeParserMap;
058    }
059
060    public void setNodeParserMap(Map<String, NodeParser> nodeParserMap) {
061        this.nodeParserMap = nodeParserMap;
062    }
063
064    public void addNodeParser(String type, NodeParser nodeParser) {
065        this.nodeParserMap.put(type, nodeParser);
066    }
067
068    public Chain parse(Tinyflow tinyflow) {
069        String jsonString = tinyflow.getData();
070        if (StringUtil.noText(jsonString)) {
071            return null;
072        }
073
074        JSONObject root = JSON.parseObject(jsonString);
075        JSONArray nodes = root.getJSONArray("nodes");
076        JSONArray edges = root.getJSONArray("edges");
077
078        return parse(tinyflow, nodes, edges, null);
079    }
080
081    public Chain parse(Tinyflow tinyflow, JSONArray nodes, JSONArray edges, JSONObject parentNode) {
082        if (CollectionUtil.noItems(nodes) || CollectionUtil.noItems(edges)) {
083            return null;
084        }
085
086        Chain chain = new Chain();
087        for (int i = 0; i < nodes.size(); i++) {
088            JSONObject nodeObject = nodes.getJSONObject(i);
089            if ((parentNode == null && StringUtil.noText(nodeObject.getString("parentId")))
090                    || (parentNode != null && parentNode.getString("id").equals(nodeObject.getString("parentId")))) {
091                ChainNode node = parseNode(tinyflow, nodeObject);
092                if (node != null) {
093                    node.setId(nodeObject.getString("id"));
094                    node.setName(nodeObject.getString("label"));
095                    node.setDescription(nodeObject.getString("description"));
096
097                    String conditionString = nodeObject.getString("condition");
098                    if (StringUtil.hasText(conditionString)) {
099                        node.setCondition(new JavascriptStringCondition(conditionString.trim()));
100                    }
101
102                    chain.addNode(node);
103                }
104            }
105        }
106
107        for (int i = 0; i < edges.size(); i++) {
108            JSONObject edgeObject = edges.getJSONObject(i);
109            JSONObject edgeData = edgeObject.getJSONObject("data");
110
111            if ((parentNode == null && (edgeData == null || StringUtil.noText(edgeData.getString("parentNodeId"))))
112                    || (parentNode != null && edgeData != null && edgeData.getString("parentNodeId").equals(parentNode.getString("id"))
113                    //不添加子流程里的第一条 edge(也就是父节点连接子节点的第一条线)
114                    && !parentNode.getString("id").equals(edgeObject.getString("source")))) {
115                ChainEdge edge = parseEdge(edgeObject);
116                if (edge != null) {
117                    chain.addEdge(edge);
118                }
119            }
120        }
121
122        return chain;
123    }
124
125    private ChainNode parseNode(Tinyflow tinyflow, JSONObject nodeObject) {
126        String type = nodeObject.getString("type");
127        if (StringUtil.noText(type)) {
128            return null;
129        }
130
131        NodeParser nodeParser = nodeParserMap.get(type);
132        return nodeParser == null ? null : nodeParser.parse(nodeObject, tinyflow);
133    }
134
135
136    private ChainEdge parseEdge(JSONObject edgeObject) {
137        if (edgeObject == null) return null;
138        ChainEdge edge = new ChainEdge();
139        edge.setId(edgeObject.getString("id"));
140        edge.setSource(edgeObject.getString("source"));
141        edge.setTarget(edgeObject.getString("target"));
142
143        JSONObject data = edgeObject.getJSONObject("data");
144        if (data == null || data.isEmpty()) {
145            return edge;
146        }
147
148        String conditionString = data.getString("condition");
149        if (StringUtil.hasText(conditionString)) {
150            edge.setCondition(new JavascriptStringCondition(conditionString.trim()));
151        }
152        return edge;
153    }
154}