File size: 2,283 Bytes
05c5ed5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import { objectFlow, toAny } from "lib/utils";
import { OutputSchemaSourceKey } from "../workflow.interface";
import { graphStore } from "ts-edge";
import { DBEdge, DBNode } from "app-types/workflow";
import { ObjectJsonSchema7 } from "app-types/util";
import { defaultObjectJsonSchema } from "../shared.workflow";

export interface WorkflowRuntimeState {
  query: Record<string, unknown>;
  inputs: {
    [nodeId: string]: any;
  };
  nodes: DBNode[];
  edges: DBEdge[];
  outputs: {
    [nodeId: string]: any;
  };
  setInput(nodeId: string, value: any): void;
  getInput(nodeId: string): any;
  setOutput(key: OutputSchemaSourceKey, value: any): void;
  getOutput<T>(key: OutputSchemaSourceKey): undefined | T;
}

export const createGraphStore = (params: {
  nodes: DBNode[];
  edges: DBEdge[];
}) => {
  return graphStore<WorkflowRuntimeState>((set, get) => {
    return {
      query: {},
      outputs: {},
      inputs: {},
      nodes: params.nodes,
      edges: params.edges,
      setInput(nodeId, value) {
        set((prev) => {
          return { inputs: { ...prev.inputs, [nodeId]: value } };
        });
      },
      getInput(nodeId) {
        const { inputs } = get();
        return inputs[nodeId];
      },
      setOutput(key, value) {
        set((prev) => {
          const next = objectFlow(prev.outputs).setByPath(
            [key.nodeId, ...key.path],
            value,
          );
          return {
            outputs: next,
          };
        });
      },
      getOutput(key) {
        const { outputs, nodes } = get();
        const targetNode = nodes.find((n) => n.id == key.nodeId);
        const schema =
          (targetNode?.nodeConfig?.outputSchema as ObjectJsonSchema7) ??
          defaultObjectJsonSchema;
        const defaultValue = key.path.length
          ? key.path.reduce(
              (acc, cur, index) => {
                const isLast = index === key.path.length - 1;
                if (isLast) return acc?.[cur]?.default;
                return acc?.[cur]?.properties?.[cur];
              },
              (schema.properties ?? {}) as any,
            )
          : toAny(schema)?.default;

        return (
          objectFlow(outputs[key.nodeId]).getByPath(key.path) ?? defaultValue
        );
      },
    };
  });
};