All files Node.ts

94.65% Statements 124/131
97.05% Branches 33/34
78.94% Functions 15/19
95.04% Lines 115/121

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 3431x 1x 1x   1x                                                                                                                     30x             30x 30x   30x                       30x                                   1x 9x 9x 9x 9x       9x 9x 9x 9x   9x 17x   9x   9x           1x 7x 7x 7x 7x 7x 1x         6x 6x 12x 5x 5x   12x 12x 7x 7x 2x 2x 2x   2x 1x 1x   1x   1x 1x 1x 1x               1x 38x 38x 38x 68x 8x 8x 3x 1x 1x 1x                 2x   2x 2x 2x     56x 13x 7x 7x 7x 6x   9x                       9x 9x 9x 9x     32x   32x 32x 13x 13x   13x 40x 27x 1x   14x 30x   15x 13x 13x 13x           26x 13x 13x               1x 1x 1x                           26x   1x 1x 1x                           32x   32x                       34x 30x 30x 30x   30x   1x 1x 1x                   30x             2x 2x 2x 2x                      
import Edge, {execute as edgeExecute} from "./Edge";
import {parseScript} from 'meriyah';
import {generate} from "escodegen";
import Scheduler from "./Scheduler";
import {ConnectorEvent, Graph, newId, EdgeError, NodeTemplate,
    LinkedNode, LinkedGraph, NodeInterface, NodeSetEvent} from "./Shared";
/**
 *
 * Nodes are the building blocks of the graph.
 * Nodes represent a unit of code.
 * Units of code in Plastic-IO are _domain agnostic_.
 * That means the code in your nodes can execute in many different domains.
 * For example, your node can be called upon to work in a browser environment
 * or in the server environment.
 *
 * Your node addtionally can be called upon to supply a user interface to
 * simply display data, or to provide a complex control panel.
 *
 * Your node also contains tests, and is segmented from the graph in such a way
 * that it can be imported to other graphs where users can reuse to the
 * units of code that you create.
 *
 * This is made version safe through [Event Sourcing](https://martinfowler.com/eaaDev/EventSourcing.html) patterns.
 * Vecotrs, as well as {@link Graph}s are made to be shared.
 *
 * Although it's not difficult to construct Plastic-IO graphs by hand.
 * You can also use the [Plastic-IO Graph Editor](https://github.com/plastic-io/graph-editor).
 *
 */
export default interface Node {
    /** The unique UUID of this node */
    id: string;
    linkedGraph?: LinkedGraph;
    linkedNode?: LinkedNode;
    /** Output edges on the node */
    edges: Edge[];
    /** Used along with graphId to locate nodes in linked resources */
    version: number;
    /** Used along with version to locate nodes in linked resources */
    graphId: string;
    /** The URL to this node, combined with the node's graphId */
    url: string;
    /**
     * This property holds domain specific non-volitalie data associated
     * with this node instance
     */
    data: any; // eslint-disable-line
    /**
     * This property contains non-volitalie meta information about the node,
     * such as placement in the UI, executable code, and other meta properties
     * specific to the domain of the node
     */
    properties: any;
    /** Node template.  Defines UX and runtime code. */
    template: NodeTemplate;
    /**
     * Ephemeral value that should not be commited to a data store.
     * Used to store domain specific instance idenfitifer.
     */
    __contextId: any;
}
/** Utility to parse and run nodes.  Used internally to run the node's set function. */
async function parseAndRun(code: string, nodeInterface: NodeInterface): Promise<any> {
    const ast = parseScript(code, {
        loc: true,
        module: true,
        next: true,
        globalReturn: true,
    });
    // tslint:disable-next-line
    const AsyncFunction = Object.getPrototypeOf(async function(){}).constructor; // eslint-disable-line 
    const nodeFn = new AsyncFunction("scheduler", "graph", "cache", "node", "field",
        "state", "value", "edges", "data", "properties", "require", generate(ast));
    nodeInterface.scheduler.dispatchEvent("set", {
        id: newId(),
        nodeId: nodeInterface.node.id,
        graphId: nodeInterface.node.graphId,
        field: nodeInterface.field,
        time: Date.now(),
        nodeInterface,
        setContext(val: any) {
            nodeInterface.scheduler.logger.debug(`Node: setContext setting context of node.`);
            nodeInterface.context = val;
        },
    } as NodeSetEvent);
    return await nodeFn.call(
        nodeInterface.context,
        nodeInterface.scheduler,
        nodeInterface.graph,
        nodeInterface.cache,
        nodeInterface.node,
        nodeInterface.field,
        nodeInterface.state,
        nodeInterface.value,
        nodeInterface.edges,
        nodeInterface.data,
        nodeInterface.properties,
        (path: any) => {
            return eval("require")(path); // tslint:disable-line
        },
    );
}
/** Utility to connect linked nodes and the host graph's node.  Used internally. */
export function getLinkedInputs(vect: Node, field: string, scheduler: Scheduler): any {
    const log = scheduler.logger;
    const graph = vect.linkedGraph!.graph;// eslint-disable-line
    const outputs = vect.linkedGraph!.fields.outputs;// eslint-disable-line
    const inputs = vect.linkedGraph!.fields.inputs;// eslint-disable-line
    // ----- INPUTS
    // linked graph inputs (this part was easy)
    // replace field with internally mapped field
    log.debug(`Node: edge map inputs: ${Object.keys(inputs).join()}`);
    const mappedConnector = inputs[field];
    if (mappedConnector) {
        field = mappedConnector.field;
        // map to the internal node using the fieldMap
        vect = graph.nodes.find((v: Node) => {
            return v.id === mappedConnector.id;
        }) as Node;
        log.debug("Node: mapped node.id " + vect.id);
    }
    return {
        field,
        node: vect,
    };
}
/** Utility to connect linked nodes and the host graph's node.  Used internally. */
export function linkInnerNodeEdges(vect: Node, scheduler: Scheduler): void {
    const log = scheduler.logger;
    const graph = vect.linkedGraph!.graph;// eslint-disable-line
    const outputs = vect.linkedGraph!.fields.outputs;// eslint-disable-line
    const inputs = vect.linkedGraph!.fields.inputs;// eslint-disable-line
    if (!graph) {
        throw new Error("Critical Error: Linked graph not found on node.id: " + vect.id);
    }
    // ----- OUTPUTS
    // linked graph outputs (this part was hard)
    // connect output on this graph JIT using the field map
    log.debug(`Node: Linked graph: Attach output connectors from map. Embedded graph node count: ${graph.nodes.length}, node.id ${vect.id}`);
    graph.nodes.forEach((v: Node) => {
        if (vect.linkedGraph && Object.prototype.hasOwnProperty.call(vect.linkedGraph.data, v.id)) {
            log.debug(`Node: Linked graph set linked data.  Data type ${typeof vect.linkedGraph.data[v.id]}`);
            v.data = vect.linkedGraph.data[v.id];
        }
        v.properties = (vect.linkedGraph && Object.prototype.hasOwnProperty.call(vect.linkedGraph.properties, v.id)) ? vect.linkedGraph.properties[v.id] : v.properties;
        v.edges.forEach((edg: Edge) => {
            log.debug(`Node: edge map outputs: ${Object.keys(outputs).join()}`);
            Object.keys(outputs).forEach((outputField) => { // eslint-disable-line
                const output = vect.linkedGraph!.fields.outputs[outputField]; // eslint-disable-line
                const linkedEdge = vect.edges.find((edge) => {
                    return edge.field === output.field && output.id === v.id;
                });
                if (!linkedEdge) {
                    log.debug(`Node: No linked edges found for field: ${output.field} id: ${output.id}`);
                    return;
                }
                log.debug(`%cNode: Linked edges found for field: ${output.field} id: ${output.id} connectors ${linkedEdge.connectors.length}`
                    , "background: green; color: white; font-weight: bold;");
                const connectorIds = edg.connectors.map(c => c.id);
                linkedEdge.connectors.forEach((c) => {
                    if (connectorIds.indexOf(c.id) === -1) {
                        edg.connectors.push(c);
                    }
                });
            });
        });
    });
}
/** Run connector code in isolation, creates interface.  Used internally. */
export async function execute(scheduler: Scheduler, graph: Graph, node: Node, field: string, value: any): Promise<any> {
    const log = scheduler.logger;
    log.debug(`Node: Begin execute node.id ${node.id}, field ${field}`);
    let vect = node;
    if (node.linkedNode && !node.linkedNode.loaded) {
        log.debug(`Node: Load linkedNode.id ${node.linkedNode.id} for node.id: ${node.id}`);
        node.linkedNode.node = await scheduler.nodeLoader.load(scheduler.getNodePath(node.linkedNode.id, node.linkedNode.version));
        if (!node.linkedNode.node) {
            const err = new Error(`Node: Critical Error: Linked node not found on node.id: ${node.id}`);
            log.error(err.stack);
            scheduler.dispatchEvent("error", {
                id: newId(),
                time: Date.now(),
                err,
                message: err.toString(),
                nodeId: node.id,
                graphId: graph.id,
            } as EdgeError);
        } else {
            node.linkedNode.loaded = true;
            // use the linked node from here on out
            vect = node.linkedNode.node;
            vect.data = node.data;
            vect.properties = node.properties;
        }
    }
    if (vect.linkedGraph) {
        if (!vect.linkedGraph.loaded) {
            log.debug(`Node: Load linked graph for node.id ${node.id}`);
            vect.linkedGraph.graph = await scheduler.graphLoader.load(scheduler.getGraphPath(vect.linkedGraph.id, vect.linkedGraph.version));
            linkInnerNodeEdges(vect, scheduler);
            vect.linkedGraph.loaded = true;
        }
        Iif (node.linkedGraph && !node.linkedGraph.graph) {
            const err = new Error(`Node: Critical Error: Linked graph not found on node.id: ${node.id}`);
            log.error(err.stack);
            scheduler.dispatchEvent("error", {
                id: newId(),
                time: Date.now(),
                err,
                message: err.toString(),
                nodeId: node.id,
                graphId: graph.id,
            } as EdgeError);
        } else {
            graph = vect.linkedGraph!.graph;// eslint-disable-line
            const proxyInput = getLinkedInputs(vect, field, scheduler);
            field = proxyInput.field;
            vect = proxyInput.node;
        }
    }
    const edges = {};
    // create outputs for interface
    log.debug(`Node: node.edge.length ${vect.edges.length}`);
    vect.edges.forEach((edge: Edge) => {
        Object.defineProperty(edges, edge.field, {
            set: async (setterVal: any) => {
                async function setter(val: any): Promise<void> {
                    log.debug(`Node: Edge setter invoked. field ${edge.field}, edge.connectors.length ${edge.connectors.length}, node.id ${vect.id}, graph.id, ${graph.id}`);
                    for (const connector of edge.connectors) {
                        if (connector.graphId !== graph.id || connector.version !== graph.version) {
                            graph = await scheduler.graphLoader.load(scheduler.getGraphPath(connector.graphId, connector.version));
                        }
                        const nodeNext = graph.nodes.find((v: Node) => {
                            return connector.nodeId === v.id;
                        });
                        if (nodeNext) {
                            log.debug(`Node: Edge.execute nodeNext.id ${nodeNext.id} nodeNext.graphId ${nodeNext.graphId}`);
                            const start = Date.now();
                            scheduler.dispatchEvent("beginconnector", {
                                time: start,
                                id: newId(),
                                connector,
                                value: val,
                            } as ConnectorEvent);
                            await edgeExecute(scheduler, graph, nodeNext, connector.field, val);
                            const end = Date.now();
                            scheduler.dispatchEvent("endconnector", {
                                time: end,
                                duration: end - start,
                                id: newId(),
                                connector,
                                value: val,
                            } as ConnectorEvent);
                        } else {
                            const err = new Error(`Connector refers to a node edge that does not exist.  Connector.id: ${connector.id}`);
                            log.error(err.stack);
                            scheduler.dispatchEvent("error", {
                                id: newId(),
                                time: Date.now(),
                                err,
                                message: err.toString(),
                                edgeField: edge.field,
                                connectorId: connector.id,
                                nodeId: vect.id,
                                graphId: graph.id,
                            } as EdgeError);
                        }
                    }
                }
                try {
                    await setter(setterVal);
                } catch(err) {
                    const er = new Error(`Node: Edge setter error. field ${edge.field}, node.id ${vect.id}. Error: ${err}`);
                    log.error(er.stack);
                    scheduler.dispatchEvent("error", {
                        id: newId(),
                        time: Date.now(),
                        err: er,
                        message: er.toString(),
                        edgeField: edge.field,
                        nodeId: vect.id,
                        graphId: graph.id,
                    } as EdgeError);
                }
            }
        });
    });
    // ensure the node has a cache for private use
    scheduler.nodeCache[vect.id] = scheduler.nodeCache[vect.id] || {};
    // provide interface for invoking code
    const nodeInterface = {
        scheduler,
        edges,
        state: scheduler.state,
        field,
        value,
        node: vect,
        cache: scheduler.nodeCache[vect.id],
        graph,
        data: vect.data,
        properties: vect.properties,
    } as NodeInterface;
    if (vect.template.set) {
        let er;
        let setResult: any;
        log.debug(`Node: Parse and run template for node.id: ${node.id} template length ${vect.template.set.length}`);
        try {
            setResult = await parseAndRun(vect.template.set, nodeInterface);
        } catch (err: any) {
            er = err;
            scheduler.logger.error(`Node: set function caused an error: ${err.stack}`);
            scheduler.dispatchEvent("error", {
                id: newId(),
                time: Date.now(),
                err,
                message: err.toString(),
                nodeId: vect.id,
                graphId: graph.id,
                field,
            } as EdgeError);
        }
        scheduler.dispatchEvent("afterSet", {
            id: newId(),
            err: er,
            return: setResult,
            time: Date.now(),
            nodeInterface,
        } as NodeSetEvent);
    } else if (!vect.linkedGraph) {
        const err = new Error(`Node: No template for set found on node.id ${node.id}`);
        scheduler.logger.error(err.stack);
        scheduler.dispatchEvent("error", {
            id: newId(),
            time: Date.now(),
            err,
            message: err.toString(),
            nodeId: vect.id,
            graphId: graph.id,
            field,
        } as EdgeError);
    }
}