<commit_before>'use strict';

var process = global.process;
var assert = require('assert');
var path = require('path');
var TermColor = require('term-color');

var serializeType = require('../../serialize.js');

var STRAIGHT_LINE = '-----------------------------------------' +
    '------------------------';

module.exports = {
    prettyPrintAllErrors: prettyPrintAllErrors,
    prettyPrintTraces: prettyPrintTraces
};

function prettyPrintAllErrors(checker) {
    var parts = [];
    parts.push('');

    for (var i = 0; i < checker.errors.length; i++) {
        var error = checker.errors[i];

        assert(error.fileName, 'error must have fileName');
        var relativePath = path.relative(process.cwd(), error.fileName);

        parts.push(TermColor.underline(relativePath));

        parts.push(prettyPrintError(checker, error, {
            prefix: ''
        }));
    }

    var word = checker.errors.length === 1 ? 'error' : 'errors';
    parts.push(TermColor.red('Found (' + checker.errors.length + ') ' + word));
    parts.push('');

    return parts.join('\n');
}

function prettyPrintError(checker, error, opts) {
    var parts = [];

    parts.push(opts.prefix + 'Found error: ' + TermColor.cyan(error.type));
    parts.push(opts.prefix + error.message);
    parts.push('');

    if (opts.showLoc !== false && error.loc) {
        var sourceLines;
        if (error.source) {
            sourceLines = error.source.split('\n');
        } else {
            var meta = checker.getOrCreateMeta(error.fileName);
            sourceLines = meta.sourceLines;
        }

        var failingLines = getFailingLines(sourceLines, error.loc);

        parts.push(opts.prefix + failingLines);
        parts.push('');
    } else if (opts.showLoc !== false &&
        (
            error.type === 'jsig.checker.could-not-parse-javascript' ||
            error.type === 'jsig.parser.cannot-parse-header-file'
        )
    ) {
        sourceLines = error.source.split('\n');
        var loc = {
            start: {
                column: 0,
                line: error.line
            },
            end: {
                line: error.line,
                column: sourceLines[error.line].length
            }
        };
        failingLines = getFailingLines(sourceLines, loc);

        parts.push(opts.prefix + failingLines);
        parts.push('');
    }

    if (error.expected && error.actual) {
        parts.push(opts.prefix +
            'Expected : ' + TermColor.green(error.expected));
        parts.push(opts.prefix +
            'Actual   : ' + TermColor.red(error.actual));
        parts.push('');
    }

    if (Array.isArray(error.originalErrors)) {
        var nestedPrefix = opts.prefix + '    ';
        parts.push(nestedPrefix + STRAIGHT_LINE);
        parts.push(nestedPrefix + 'Error caused by: ');
        parts.push('');

        for (var j = 0; j < error.originalErrors.length; j++) {
            var e = error.originalErrors[j];
            parts.push(
                nestedPrefix + 'Branch: ' + TermColor.green(e.branchType)
            );
            parts.push(prettyPrintError(checker, e, {
                prefix: nestedPrefix,
                showLoc: false
            }));
            parts.push('');
        }
    }

    return parts.join('\n');
}

function prettyPrintTraces(checker) {
    var traces = checker.traces;
    var parts = [];
    parts.push('');

    for (var i = 0; i < traces.length; i++) {
        var trace = traces[i];

        assert(trace.fileName, 'trace must have fileName');
        var relativePath = path.relative(process.cwd(), trace.fileName);

        parts.push(TermColor.underline(relativePath));
        parts.push(prettyPrintTrace(checker, trace));
    }

    return parts.join('\n');
}

function prettyPrintTrace(checker, trace) {
    var parts = [];

    parts.push('TRACE: ' + TermColor.cyan(trace.type));

    if (trace.node.loc) {
        var meta = checker.getOrCreateMeta(trace.fileName);
        var failingLines = getFailingLines(meta.sourceLines, trace.node.loc);

        parts.push(failingLines);
        parts.push('');
    }

    var expected = serializeType(trace.expected);
    var actual = serializeType(trace.actual);

    parts.push('Expected : ' + TermColor.green(expected));
    parts.push('Actual : ' + TermColor.red(actual));
    parts.push('');

    return parts.join('\n');
}

function getFailingLines(sourceLines, loc) {
    var startLine = loc.start.line - 1;
    var endLine = loc.end.line - 1;

    var prevLine = sourceLines[startLine - 1] || '';
    var nextLine = sourceLines[endLine + 1] || '';

    var segments = [
        String(startLine) + '. ' + TermColor.gray(prevLine)
    ];

    var failLine;
    var startColumn;
    var endColumn;
    if (startLine === endLine) {
        failLine = sourceLines[startLine];
        startColumn = loc.start.column;
        endColumn = loc.end.column;

        segments.push(
            String(startLine + 1) + '. ' +
            failLine.slice(0, startColumn) +
            TermColor.red(failLine.slice(startColumn, endColumn)) +
            failLine.slice(endColumn, failLine.length)
        );
    } else {
        failLine = sourceLines[startLine];
        startColumn = loc.start.column;
        endColumn = loc.end.column;

        segments.push(
            String(startLine + 1) + '. ' +
            failLine.slice(0, startColumn) +
            TermColor.red(failLine.slice(startColumn, failLine.length))
        );

        for (var i = startLine + 1; i < endLine; i++) {
            segments.push(
                String(i + 1) + '. ' + TermColor.red(sourceLines[i])
            );
        }

        failLine = sourceLines[endLine];

        segments.push(
            String(endLine + 1) + '. ' +
            TermColor.red(failLine.slice(0, endColumn)) +
            failLine.slice(endColumn, failLine.length)
        );
    }

    segments.push(
        String(endLine + 2) + '. ' + TermColor.gray(nextLine)
    );

    return segments.join('\n');
}
<commit_msg>improve red/green coloring code<commit_after>'use strict';

var process = global.process;
var assert = require('assert');
var path = require('path');
var TermColor = require('term-color');

var serializeType = require('../../serialize.js');

var STRAIGHT_LINE = '-----------------------------------------' +
    '------------------------';

module.exports = {
    prettyPrintAllErrors: prettyPrintAllErrors,
    prettyPrintTraces: prettyPrintTraces
};

function prettyPrintAllErrors(checker) {
    var parts = [];
    parts.push('');

    for (var i = 0; i < checker.errors.length; i++) {
        var error = checker.errors[i];

        assert(error.fileName, 'error must have fileName');
        var relativePath = path.relative(process.cwd(), error.fileName);

        parts.push(TermColor.underline(relativePath));

        parts.push(prettyPrintError(checker, error, {
            prefix: ''
        }));
    }

    var word = checker.errors.length === 1 ? 'error' : 'errors';
    parts.push(TermColor.red('Found (' + checker.errors.length + ') ' + word));
    parts.push('');

    return parts.join('\n');
}

function lineGreen(text) {
    if (text.indexOf('\n') === -1) {
        return TermColor.green(text);
    }

    var lines = text.split('\n');
    for (var i = 0; i < lines.length; i++) {
        lines[i] = TermColor.green(lines[i]);
    }

    return lines.join('\n');
}

function lineRed(text) {
    if (text.indexOf('\n') === -1) {
        return TermColor.red(text);
    }

    var lines = text.split('\n');
    for (var i = 0; i < lines.length; i++) {
        lines[i] = TermColor.red(lines[i]);
    }

    return lines.join('\n');
}

function prettyPrintError(checker, error, opts) {
    var parts = [];

    parts.push(opts.prefix + 'Found error: ' + TermColor.cyan(error.type));
    parts.push(opts.prefix + error.message);
    parts.push('');

    if (opts.showLoc !== false && error.loc) {
        var sourceLines;
        if (error.source) {
            sourceLines = error.source.split('\n');
        } else {
            var meta = checker.getOrCreateMeta(error.fileName);
            sourceLines = meta.sourceLines;
        }

        var failingLines = getFailingLines(sourceLines, error.loc);

        parts.push(opts.prefix + failingLines);
        parts.push('');
    } else if (opts.showLoc !== false &&
        (
            error.type === 'jsig.checker.could-not-parse-javascript' ||
            error.type === 'jsig.parser.cannot-parse-header-file'
        )
    ) {
        sourceLines = error.source.split('\n');
        var loc = {
            start: {
                column: 0,
                line: error.line
            },
            end: {
                line: error.line,
                column: sourceLines[error.line].length
            }
        };
        failingLines = getFailingLines(sourceLines, loc);

        parts.push(opts.prefix + failingLines);
        parts.push('');
    }

    if (error.expected && error.actual) {
        parts.push(opts.prefix +
            'Expected : ' + lineGreen(error.expected));
        parts.push(opts.prefix +
            'Actual   : ' + lineRed(error.actual));
        parts.push('');
    }

    if (Array.isArray(error.originalErrors)) {
        var nestedPrefix = opts.prefix + '    ';
        parts.push(nestedPrefix + STRAIGHT_LINE);
        parts.push(nestedPrefix + 'Error caused by: ');
        parts.push('');

        for (var j = 0; j < error.originalErrors.length; j++) {
            var e = error.originalErrors[j];
            parts.push(
                nestedPrefix + 'Branch: ' + TermColor.green(e.branchType)
            );
            parts.push(prettyPrintError(checker, e, {
                prefix: nestedPrefix,
                showLoc: false
            }));
            parts.push('');
        }
    }

    return parts.join('\n');
}

function prettyPrintTraces(checker) {
    var traces = checker.traces;
    var parts = [];
    parts.push('');

    for (var i = 0; i < traces.length; i++) {
        var trace = traces[i];

        assert(trace.fileName, 'trace must have fileName');
        var relativePath = path.relative(process.cwd(), trace.fileName);

        parts.push(TermColor.underline(relativePath));
        parts.push(prettyPrintTrace(checker, trace));
    }

    return parts.join('\n');
}

function prettyPrintTrace(checker, trace) {
    var parts = [];

    parts.push('TRACE: ' + TermColor.cyan(trace.type));

    if (trace.node.loc) {
        var meta = checker.getOrCreateMeta(trace.fileName);
        var failingLines = getFailingLines(meta.sourceLines, trace.node.loc);

        parts.push(failingLines);
        parts.push('');
    }

    var expected = serializeType(trace.expected);
    var actual = serializeType(trace.actual);

    parts.push('Expected : ' + lineGreen(expected));
    parts.push('Actual : ' + lineRed(actual));
    parts.push('');

    return parts.join('\n');
}

function getFailingLines(sourceLines, loc) {
    var startLine = loc.start.line - 1;
    var endLine = loc.end.line - 1;

    var prevLine = sourceLines[startLine - 1] || '';
    var nextLine = sourceLines[endLine + 1] || '';

    var segments = [
        String(startLine) + '. ' + TermColor.gray(prevLine)
    ];

    var failLine;
    var startColumn;
    var endColumn;
    if (startLine === endLine) {
        failLine = sourceLines[startLine];
        startColumn = loc.start.column;
        endColumn = loc.end.column;

        segments.push(
            String(startLine + 1) + '. ' +
            failLine.slice(0, startColumn) +
            TermColor.red(failLine.slice(startColumn, endColumn)) +
            failLine.slice(endColumn, failLine.length)
        );
    } else {
        failLine = sourceLines[startLine];
        startColumn = loc.start.column;
        endColumn = loc.end.column;

        segments.push(
            String(startLine + 1) + '. ' +
            failLine.slice(0, startColumn) +
            TermColor.red(failLine.slice(startColumn, failLine.length))
        );

        for (var i = startLine + 1; i < endLine; i++) {
            segments.push(
                String(i + 1) + '. ' + TermColor.red(sourceLines[i])
            );
        }

        failLine = sourceLines[endLine];

        segments.push(
            String(endLine + 1) + '. ' +
            TermColor.red(failLine.slice(0, endColumn)) +
            failLine.slice(endColumn, failLine.length)
        );
    }

    segments.push(
        String(endLine + 2) + '. ' + TermColor.gray(nextLine)
    );

    return segments.join('\n');
}
<|endoftext|>


<commit_before>var util = require("../util"),
    rank = require("./rank"),
    acyclic = require("./acyclic"),
    CDigraph = require("graphlib").CDigraph,
    Digraph = require("graphlib").Digraph,
    Graph = require("graphlib").Graph,
    /* jshint -W079 */
    Set = require("graphlib").data.Set;

module.exports = function() {
  // External configuration
  var config = {
      // How much debug information to include?
      debugLevel: 0,
  };

  var timer = util.createTimer();

  // Phase functions
  var
      order = require("./order")(),
      position = require("./position")();

  // This layout object
  var self = {};

  self.orderIters = delegateProperty(order.iterations);

  self.nodeSep = delegateProperty(position.nodeSep);
  self.edgeSep = delegateProperty(position.edgeSep);
  self.universalSep = delegateProperty(position.universalSep);
  self.rankSep = delegateProperty(position.rankSep);
  self.rankDir = delegateProperty(position.rankDir);
  self.debugAlignment = delegateProperty(position.debugAlignment);

  self.debugLevel = util.propertyAccessor(self, config, "debugLevel", function(x) {
    timer.enabled(x);
    order.debugLevel(x);
    position.debugLevel(x);
  });

  self.run = timer.wrap("Total layout", run);

  self._normalize = normalize;

  return self;

  /*
   * Constructs an adjacency graph using the nodes and edges specified through
   * config. For each node and edge we add a property `dagre` that contains an
   * object that will hold intermediate and final layout information. Some of
   * the contents include:
   *
   *  1) A generated ID that uniquely identifies the object.
   *  2) Dimension information for nodes (copied from the source node).
   *  3) Optional dimension information for edges.
   *
   * After the adjacency graph is constructed the code no longer needs to use
   * the original nodes and edges passed in via config.
   */
  function buildAdjacencyGraph(inputGraph, constraintGraph) {
    var g = new CDigraph();

    inputGraph.eachNode(function(u, value) {
      if (value === undefined) value = {};
      g.addNode(u, {
        width: value.width,
        height: value.height
      });
    });

    // Set up subgraphs
    if (inputGraph.parent) {
      inputGraph.nodes().forEach(function(u) {
        g.parent(u, inputGraph.parent(u));
      });
    }

    inputGraph.eachEdge(function(e, u, v, value) {
      if (value === undefined) value = {};
      var newValue = {
        e: e,
        minLen: value.minLen || 1,
        width: value.width || 0,
        height: value.height || 0,
        points: []
      };

      g.addEdge(null, u, v, newValue);

      // If input graph is not directed, we create also add a reverse edge.
      // After we've run the acyclic algorithm we'll remove one of these edges.
      if (!inputGraph.isDirected()) {
        g.addEdge(null, v, u, newValue);
      }
    });

    g.graph({});

    if (constraintGraph) {
      g.graph().constraintGraph = constraintGraph;
    }

    return g;
  }

  function run(inputGraph, constraintGraph) {
    var rankSep = self.rankSep();
    var g;
    try {
      // Build internal graph
      g = buildAdjacencyGraph(inputGraph, constraintGraph);

      if (g.order() === 0) {
        return g;
      }

      // Make space for edge labels
      g.eachEdge(function(e, s, t, a) {
        a.minLen *= 2;
      });
      self.rankSep(rankSep / 2);

      // Reverse edges to get an acyclic graph, we keep the graph in an acyclic
      // state until the very end.
      acyclic(g, config.debugLevel);

      // Our intermediate graph is always directed. However, the input graph
      // may be undirected, so we create duplicate edges in opposite directions
      // in the buildAdjacencyGraph function. At this point one of each pair of
      // edges was reversed, so we remove the redundant edge.
      if (!inputGraph.isDirected()) {
        removeDupEdges(g);
      }

      // Determine the rank for each node. Nodes with a lower rank will appear
      // above nodes of higher rank.
      rank(g, config.debugLevel);

      // Normalize the graph by ensuring that every edge is proper (each edge has
      // a length of 1). We achieve this by adding dummy nodes to long edges,
      // thus shortening them.
      normalize(g);

      // Order the nodes so that edge crossings are minimized.
      order.run(g);

      // Find the x and y coordinates for every node in the graph.
      position.run(g);

      // De-normalize the graph by removing dummy nodes and augmenting the
      // original long edges with coordinate information.
      undoNormalize(g);

      // Reverses points for edges that are in a reversed state.
      fixupEdgePoints(g);

      // Reverse edges that were revered previously to get an acyclic graph.
      acyclic.undo(g);

      // Construct final result graph and return it
      return createFinalGraph(g, inputGraph.isDirected());
    } finally {
      self.rankSep(rankSep);
    }
  }

  function removeDupEdges(g) {
    var visited = new Set();
    g.eachEdge(function(e, u, v, value) {
      if (visited.has(value.e)) {
        g.delEdge(e);
      }
      visited.add(value.e);
    });
  }

  /*
   * This function is responsible for "normalizing" the graph. The process of
   * normalization ensures that no edge in the graph has spans more than one
   * rank. To do this it inserts dummy nodes as needed and links them by adding
   * dummy edges. This function keeps enough information in the dummy nodes and
   * edges to ensure that the original graph can be reconstructed later.
   *
   * This method assumes that the input graph is cycle free.
   */
  function normalize(g) {
    var dummyCount = 0;
    g.eachEdge(function(e, s, t, a) {
      var sourceRank = g.node(s).rank;
      var targetRank = g.node(t).rank;
      if (sourceRank + 1 < targetRank) {
        for (var u = s, rank = sourceRank + 1, i = 0; rank < targetRank; ++rank, ++i) {
          var v = "_D" + (++dummyCount);
          var node = {
            width: a.width,
            height: a.height,
            edge: { id: e, source: s, target: t, attrs: a },
            rank: rank,
            dummy: true
          };

          // If this node represents a bend then we will use it as a control
          // point. For edges with 2 segments this will be the center dummy
          // node. For edges with more than two segments, this will be the
          // first and last dummy node.
          if (i === 0) node.index = 0;
          else if (rank + 1 === targetRank) node.index = 1;

          g.addNode(v, node);
          g.addEdge(null, u, v, {});
          u = v;
        }
        g.addEdge(null, u, t, {});
        g.delEdge(e);
      }
    });
  }

  /*
   * Reconstructs the graph as it was before normalization. The positions of
   * dummy nodes are used to build an array of points for the original "long"
   * edge. Dummy nodes and edges are removed.
   */
  function undoNormalize(g) {
    g.eachNode(function(u, a) {
      if (a.dummy && "index" in a) {
        var edge = a.edge;
        if (!g.hasEdge(edge.id)) {
          g.addEdge(edge.id, edge.source, edge.target, edge.attrs);
        }
        var points = g.edge(edge.id).points;
        points[a.index] = { x: a.x, y: a.y, ul: a.ul, ur: a.ur, dl: a.dl, dr: a.dr };
        g.delNode(u);
      }
    });
  }

  /*
   * For each edge that was reversed during the `acyclic` step, reverse its
   * array of points.
   */
  function fixupEdgePoints(g) {
    g.eachEdge(function(e, s, t, a) { if (a.reversed) a.points.reverse(); });
  }

  function createFinalGraph(g, isDirected) {
    var out = isDirected ? new Digraph() : new Graph();
    out.graph(g.graph());
    g.eachNode(function(u, value) { out.addNode(u, value); });
    g.eachEdge(function(e, u, v, value) {
      out.addEdge("e" in value ? value.e : e, u, v, value);
      delete value.e;
    });
    return out;
  }

  /*
   * Given a function, a new function is returned that invokes the given
   * function. The return value from the function is always the `self` object.
   */
  function delegateProperty(f) {
    return function() {
      if (!arguments.length) return f();
      f.apply(null, arguments);
      return self;
    };
  }
};
<commit_msg>Include subgraph information in result graph<commit_after>var util = require("../util"),
    rank = require("./rank"),
    acyclic = require("./acyclic"),
    CDigraph = require("graphlib").CDigraph,
    Digraph = require("graphlib").Digraph,
    Graph = require("graphlib").Graph,
    /* jshint -W079 */
    Set = require("graphlib").data.Set;

module.exports = function() {
  // External configuration
  var config = {
      // How much debug information to include?
      debugLevel: 0,
  };

  var timer = util.createTimer();

  // Phase functions
  var
      order = require("./order")(),
      position = require("./position")();

  // This layout object
  var self = {};

  self.orderIters = delegateProperty(order.iterations);

  self.nodeSep = delegateProperty(position.nodeSep);
  self.edgeSep = delegateProperty(position.edgeSep);
  self.universalSep = delegateProperty(position.universalSep);
  self.rankSep = delegateProperty(position.rankSep);
  self.rankDir = delegateProperty(position.rankDir);
  self.debugAlignment = delegateProperty(position.debugAlignment);

  self.debugLevel = util.propertyAccessor(self, config, "debugLevel", function(x) {
    timer.enabled(x);
    order.debugLevel(x);
    position.debugLevel(x);
  });

  self.run = timer.wrap("Total layout", run);

  self._normalize = normalize;

  return self;

  /*
   * Constructs an adjacency graph using the nodes and edges specified through
   * config. For each node and edge we add a property `dagre` that contains an
   * object that will hold intermediate and final layout information. Some of
   * the contents include:
   *
   *  1) A generated ID that uniquely identifies the object.
   *  2) Dimension information for nodes (copied from the source node).
   *  3) Optional dimension information for edges.
   *
   * After the adjacency graph is constructed the code no longer needs to use
   * the original nodes and edges passed in via config.
   */
  function buildAdjacencyGraph(inputGraph, constraintGraph) {
    var g = new CDigraph();

    inputGraph.eachNode(function(u, value) {
      if (value === undefined) value = {};
      g.addNode(u, {
        width: value.width,
        height: value.height
      });
    });

    // Set up subgraphs
    if (inputGraph.parent) {
      inputGraph.nodes().forEach(function(u) {
        g.parent(u, inputGraph.parent(u));
      });
    }

    inputGraph.eachEdge(function(e, u, v, value) {
      if (value === undefined) value = {};
      var newValue = {
        e: e,
        minLen: value.minLen || 1,
        width: value.width || 0,
        height: value.height || 0,
        points: []
      };

      g.addEdge(null, u, v, newValue);

      // If input graph is not directed, we create also add a reverse edge.
      // After we've run the acyclic algorithm we'll remove one of these edges.
      if (!inputGraph.isDirected()) {
        g.addEdge(null, v, u, newValue);
      }
    });

    g.graph({});

    if (constraintGraph) {
      g.graph().constraintGraph = constraintGraph;
    }

    return g;
  }

  function run(inputGraph, constraintGraph) {
    var rankSep = self.rankSep();
    var g;
    try {
      // Build internal graph
      g = buildAdjacencyGraph(inputGraph, constraintGraph);

      if (g.order() === 0) {
        return g;
      }

      // Make space for edge labels
      g.eachEdge(function(e, s, t, a) {
        a.minLen *= 2;
      });
      self.rankSep(rankSep / 2);

      // Reverse edges to get an acyclic graph, we keep the graph in an acyclic
      // state until the very end.
      acyclic(g, config.debugLevel);

      // Our intermediate graph is always directed. However, the input graph
      // may be undirected, so we create duplicate edges in opposite directions
      // in the buildAdjacencyGraph function. At this point one of each pair of
      // edges was reversed, so we remove the redundant edge.
      if (!inputGraph.isDirected()) {
        removeDupEdges(g);
      }

      // Determine the rank for each node. Nodes with a lower rank will appear
      // above nodes of higher rank.
      rank(g, config.debugLevel);

      // Normalize the graph by ensuring that every edge is proper (each edge has
      // a length of 1). We achieve this by adding dummy nodes to long edges,
      // thus shortening them.
      normalize(g);

      // Order the nodes so that edge crossings are minimized.
      order.run(g);

      // Find the x and y coordinates for every node in the graph.
      position.run(g);

      // De-normalize the graph by removing dummy nodes and augmenting the
      // original long edges with coordinate information.
      undoNormalize(g);

      // Reverses points for edges that are in a reversed state.
      fixupEdgePoints(g);

      // Reverse edges that were revered previously to get an acyclic graph.
      acyclic.undo(g);

      // Construct final result graph and return it
      return createFinalGraph(g, inputGraph.isDirected());
    } finally {
      self.rankSep(rankSep);
    }
  }

  function removeDupEdges(g) {
    var visited = new Set();
    g.eachEdge(function(e, u, v, value) {
      if (visited.has(value.e)) {
        g.delEdge(e);
      }
      visited.add(value.e);
    });
  }

  /*
   * This function is responsible for "normalizing" the graph. The process of
   * normalization ensures that no edge in the graph has spans more than one
   * rank. To do this it inserts dummy nodes as needed and links them by adding
   * dummy edges. This function keeps enough information in the dummy nodes and
   * edges to ensure that the original graph can be reconstructed later.
   *
   * This method assumes that the input graph is cycle free.
   */
  function normalize(g) {
    var dummyCount = 0;
    g.eachEdge(function(e, s, t, a) {
      var sourceRank = g.node(s).rank;
      var targetRank = g.node(t).rank;
      if (sourceRank + 1 < targetRank) {
        for (var u = s, rank = sourceRank + 1, i = 0; rank < targetRank; ++rank, ++i) {
          var v = "_D" + (++dummyCount);
          var node = {
            width: a.width,
            height: a.height,
            edge: { id: e, source: s, target: t, attrs: a },
            rank: rank,
            dummy: true
          };

          // If this node represents a bend then we will use it as a control
          // point. For edges with 2 segments this will be the center dummy
          // node. For edges with more than two segments, this will be the
          // first and last dummy node.
          if (i === 0) node.index = 0;
          else if (rank + 1 === targetRank) node.index = 1;

          g.addNode(v, node);
          g.addEdge(null, u, v, {});
          u = v;
        }
        g.addEdge(null, u, t, {});
        g.delEdge(e);
      }
    });
  }

  /*
   * Reconstructs the graph as it was before normalization. The positions of
   * dummy nodes are used to build an array of points for the original "long"
   * edge. Dummy nodes and edges are removed.
   */
  function undoNormalize(g) {
    g.eachNode(function(u, a) {
      if (a.dummy && "index" in a) {
        var edge = a.edge;
        if (!g.hasEdge(edge.id)) {
          g.addEdge(edge.id, edge.source, edge.target, edge.attrs);
        }
        var points = g.edge(edge.id).points;
        points[a.index] = { x: a.x, y: a.y, ul: a.ul, ur: a.ur, dl: a.dl, dr: a.dr };
        g.delNode(u);
      }
    });
  }

  /*
   * For each edge that was reversed during the `acyclic` step, reverse its
   * array of points.
   */
  function fixupEdgePoints(g) {
    g.eachEdge(function(e, s, t, a) { if (a.reversed) a.points.reverse(); });
  }

  function createFinalGraph(g, isDirected) {
    var out = isDirected ? new CDigraph() : new CGraph();
    out.graph(g.graph());
    g.eachNode(function(u, value) { out.addNode(u, value); });
    g.eachNode(function(u) { out.parent(u, g.parent(u)); });
    g.eachEdge(function(e, u, v, value) {
      out.addEdge("e" in value ? value.e : e, u, v, value);
      delete value.e;
    });
    return out;
  }

  /*
   * Given a function, a new function is returned that invokes the given
   * function. The return value from the function is always the `self` object.
   */
  function delegateProperty(f) {
    return function() {
      if (!arguments.length) return f();
      f.apply(null, arguments);
      return self;
    };
  }
};
<|endoftext|>


<commit_before>// open.js
//

'use strict';

var pkg   = require('../../package.json');
var utils = require('../utils');

var spawn = require('child_process').spawn;

module.exports = function () {

  utils.exists('./collider.json', function (err) {
    if (err) throw err;
    spawn('./node_modules/.bin/gulp', ['default'], { stdio: 'inherit' });
  });

};
<commit_msg>Update open handler<commit_after>// open.js
//

'use strict';

var matter = require('../matter');
var pkg    = require('../../package.json');
var utils  = require('../utils');

var spawn = require('child_process').spawn;

var Queue = require('queue');

module.exports = function (project) {

  // To do: Validate 'project'.
  project = project || {};

  var q = new Queue({ concurrency: 1 });

  var missingMatterLibs = [];

  // 1. Check for missing Matter lib. dependencies.
  q.push(function (cb) {
    var matterLibs = project.matterLibs;

    var numJobs          = matterLibs.length;
    var numJobsCompleted = 0;

    if (numJobs === 0) {
      cb(null);
    }

    matterLibs.forEach(function (lib) {
      var locale = matter.getLocale(lib);

      utils.exists(`./${locale}`, function (err) {
        if (err) {
          missingMatterLibs.push(lib);
        }

        numJobsCompleted++;
        if (numJobsCompleted === numJobs) {
          cb(null);
        }
      });
    });
  });

  // 2. Satisfy any missing Matter lib. dependencies.
  q.push(function (cb) {
    var numJobs          = missingMatterLibs.length;
    var numJobsCompleted = 0;

    if (numJobs === 0) {
      cb(null);
    }

    missingMatterLibs.forEach(function (lib) {

      matter.clone(lib, function (err) {
        if (err) cb(err);

        numJobsCompleted++;
        if (numJobsCompleted === numJobs) {
          cb(null);
        }
      });

    });
  });

  // Go.
  q.start(function (err) {
    if (err) throw err;
    spawn('./node_modules/.bin/gulp', ['default'], { stdio: 'inherit' });
  });

};
<|endoftext|>


<commit_before>var utils = require('../utils'),
    packages = require('../packages'),
    logger = require('../logger'),
    couchdb = require('../couchdb'),
    kansorc = require('../kansorc'),
    argParse = require('../args').parse,
    exec = require('child_process').exec,
    path = require('path'),
    fs = require('fs'),
    pathExists = fs.exists || path.exists,
    url = require('url'),
    urlParse = url.parse,
    urlFormat = url.format;

exports.summary = 'Load a project and push to a CouchDB database';

exports.usage = '' +
'kanso push [PATH] [DB]\n' +
'\n' +
'Parameters:\n' +
'  PATH    Path to project directory to push (defaults to ".")\n' +
'  DB      The CouchDB database to upload the app to, will use "default"\n' +
'          env set in .kansorc if none provided and .kansorc exists\n' +
'\n' +
'Options:\n' +
'  --minify    Compress CommonJS modules attachment using UglifyJS\n' +
'  --open      Open the app URL in the browser after pushing\n' +
'  --baseURL   Add a custom baseURL property to the kanso.json values\n' +
'  --id        Specify a custom document id for the generated app,\n' +
'              defaults to "_design/<name>" where <name> is from kanso.json';

/**
 * Main command called when typing "kanso push ..." on the command line
 */

exports.run = function (settings, args) {
    var a = argParse(args, {
        'minify': {match: '--minify'},
        'open': {match: '--open'},
        'baseURL': {match: '--baseURL', value: true},
        'id': {match: '--id', value: true}
    });
    var url;
    var dir = a.positional[0] || '.';
    pathExists(dir, function (exists) {
        if (!exists) {
            dir = process.cwd();
            url = a.positional[0];
        }
        dir = utils.abspath(dir);
        kansorc.extend(settings, dir + '/.kansorc', function (err, settings) {
            if (err) {
                return logger.error(err);
            }
            if (a.positional.length > 1) {
                url = a.positional[1];
            }
            else if (a.positional.length && !exists) {
                url = a.positional[0];
            }

            var env = utils.argToEnv(settings, url);
            url = env.db;
            if (env.baseURL) {
                a.options.baseURL = env.baseURL;
            }
            if (env.minify) {
                a.options.minify = env.minify;
            }
            if (env.id) {
                a.options.id = env.id;
            }

            // these options will override values in kanso.json
            // the 'id' and 'open' options are not relevant to that data
            var opt = env.overrides || {};
            opt.minify = a.options.minify;
            opt.baseURL = a.options.baseURL;

            exports.loadApp(dir, url, opt, settings,
                function (err, url, cfg, doc) {
                    if (err) {
                        logger.error(err);
                        if (settings.callback) settings.callback(err);
                        return;
                    }
                    var app_url = exports.getAppURL(url, cfg, doc);
                    var noauth_url = utils.noAuthURL(app_url);

                    if (a.options.open) {
                        exports.openInBrowser(app_url, function (err) {
                            if (err) {
                                return logger.error(err);
                            }
                            logger.end(noauth_url);
                            if (settings.callback) settings.callback();
                        });
                    }
                    else {
                        logger.end(noauth_url);
                        if (settings.callback) settings.callback();
                    }
                }
            );
        });
    });
};

/**
 * Builds the app prior to pushing
 */

exports.loadApp = function (dir, url, options, settings, callback) {
    var paths = settings.package_paths || [];
    var parent_dir = path.dirname(dir);
    if (path.basename(parent_dir) === 'packages') {
        paths.push(parent_dir);
    }
    var build_start = new Date().getTime();
    // make the url available to the modules
    options._url = url;
    options._utils = utils;
    packages.load(dir, paths, null, options, function (err, doc, cfg) {
        if (err) {
            if (callback) {
                return callback(err);
            }
            else {
                return logger.error(err);
            }
        }
        var build_end = new Date().getTime();
        console.log('Build complete: ' + (build_end - build_start) + 'ms');
        utils.completeAuth(url, false, function (err, url) {
            if (err) {
                return callback(err);
            }
            utils.catchAuthError(
                exports.push, url, [dir, options, cfg, doc], callback
            );
        });
    });
};

/**
 * Upload the app to the DB, catch auth errors and prompt for password
 */

exports.push = function (url, dir, options, cfg, doc, callback) {
    var db = couchdb(url);
    var root = couchdb(url);
    root.instance.pathname = '';
    root.session(function (err, info, resp) {
        if (err) {
            return callback(err);
        }
        var server_time = utils.ISODateString(new Date(resp.headers.date));
        if (!doc.kanso) {
            doc.kanso = {};
        }
        doc.kanso.push_time = server_time;
        doc.kanso.pushed_by = info.userCtx.name;

        // delete private/build time only properties
        delete doc.kanso.config._url;
        delete doc.kanso.config._utils;

        db.ensureDB(function (err) {
            if (err) {
                return callback(err);
            }
            var id = options.id || '_design/' + cfg.name;
            logger.info('Uploading...');

            db.save(id, doc, {force: true}, function (err) {
                callback(err, url, cfg, doc);
            });
        });
    });
};

/**
 * Tries to determine the right URL to report on the command-line after a
 * successful push
 *
 * OK: <url>
 */

exports.getAppURL = function (url, cfg, doc) {
    var newurl= urlParse(url);
    delete newurl.auth;
    delete newurl.host;
    var ddoc_url = urlFormat(newurl) + '/' + doc._id;

    if (!/^_design\//.test(doc._id)) {
        // not pushed as a design doc, report doc url instead of app url
        return ddoc_url;
    }

    var app_url = ddoc_url;
    if (cfg.index) {
        // if there's an index property in kanso.json
        app_url = ddoc_url + cfg.index;
    }
    if (cfg.baseURL !== undefined) {
        // if there is a custom baseURL defined
        newurl.pathname = cfg.baseURL + '/';
        app_url = urlFormat(newurl);
    }
    else if (doc.rewrites && doc.rewrites.length) {
        app_url = ddoc_url + '/_rewrite/';
    }
    else if (doc._attachments && doc._attachments['index.html']) {
        app_url = ddoc_url + '/index.html';
    }
    else if (doc._attachments && doc._attachments['index.htm']) {
        app_url = ddoc_url + '/index.htm';
    }
    return app_url;
};

/**
 * Opens the app URL in the browser when the --open option is used
 */

exports.openInBrowser = function (url, callback) {
    if (process.platform === 'linux') {
        cmd = 'xdg-open';
    }
    else {
        // OSX
        cmd = 'open';
    }
    console.log('Opening URL in browser...');
    exec(cmd + ' ' + url, callback);
};
<commit_msg>Fix kanso push --id= option<commit_after>var utils = require('../utils'),
    packages = require('../packages'),
    logger = require('../logger'),
    couchdb = require('../couchdb'),
    kansorc = require('../kansorc'),
    argParse = require('../args').parse,
    exec = require('child_process').exec,
    path = require('path'),
    fs = require('fs'),
    pathExists = fs.exists || path.exists,
    url = require('url'),
    urlParse = url.parse,
    urlFormat = url.format;

exports.summary = 'Load a project and push to a CouchDB database';

exports.usage = '' +
'kanso push [PATH] [DB]\n' +
'\n' +
'Parameters:\n' +
'  PATH    Path to project directory to push (defaults to ".")\n' +
'  DB      The CouchDB database to upload the app to, will use "default"\n' +
'          env set in .kansorc if none provided and .kansorc exists\n' +
'\n' +
'Options:\n' +
'  --minify    Compress CommonJS modules attachment using UglifyJS\n' +
'  --open      Open the app URL in the browser after pushing\n' +
'  --baseURL   Add a custom baseURL property to the kanso.json values\n' +
'  --id        Specify a custom document id for the generated app,\n' +
'              defaults to "_design/<name>" where <name> is from kanso.json';

/**
 * Main command called when typing "kanso push ..." on the command line
 */

exports.run = function (settings, args) {
    var a = argParse(args, {
        'minify': {match: '--minify'},
        'open': {match: '--open'},
        'baseURL': {match: '--baseURL', value: true},
        'id': {match: '--id', value: true}
    });
    var url;
    var dir = a.positional[0] || '.';
    pathExists(dir, function (exists) {
        if (!exists) {
            dir = process.cwd();
            url = a.positional[0];
        }
        dir = utils.abspath(dir);
        kansorc.extend(settings, dir + '/.kansorc', function (err, settings) {
            if (err) {
                return logger.error(err);
            }
            if (a.positional.length > 1) {
                url = a.positional[1];
            }
            else if (a.positional.length && !exists) {
                url = a.positional[0];
            }

            var env = utils.argToEnv(settings, url);
            url = env.db;
            if (env.baseURL) {
                a.options.baseURL = env.baseURL;
            }
            if (env.minify) {
                a.options.minify = env.minify;
            }
            if (env.id) {
                a.options.id = env.id;
            }

            // these options will override values in kanso.json
            // the 'open' option is not relevant to that data
            var opt = env.overrides || {};
            opt.minify = a.options.minify;
            opt.baseURL = a.options.baseURL;
            opt.id = a.options.id;

            exports.loadApp(dir, url, opt, settings,
                function (err, url, cfg, doc) {
                    if (err) {
                        logger.error(err);
                        if (settings.callback) settings.callback(err);
                        return;
                    }
                    var app_url = exports.getAppURL(url, cfg, doc);
                    var noauth_url = utils.noAuthURL(app_url);

                    if (a.options.open) {
                        exports.openInBrowser(app_url, function (err) {
                            if (err) {
                                return logger.error(err);
                            }
                            logger.end(noauth_url);
                            if (settings.callback) settings.callback();
                        });
                    }
                    else {
                        logger.end(noauth_url);
                        if (settings.callback) settings.callback();
                    }
                }
            );
        });
    });
};

/**
 * Builds the app prior to pushing
 */

exports.loadApp = function (dir, url, options, settings, callback) {
    var paths = settings.package_paths || [];
    var parent_dir = path.dirname(dir);
    if (path.basename(parent_dir) === 'packages') {
        paths.push(parent_dir);
    }
    var build_start = new Date().getTime();
    // make the url available to the modules
    options._url = url;
    options._utils = utils;
    packages.load(dir, paths, null, options, function (err, doc, cfg) {
        if (err) {
            if (callback) {
                return callback(err);
            }
            else {
                return logger.error(err);
            }
        }
        var build_end = new Date().getTime();
        console.log('Build complete: ' + (build_end - build_start) + 'ms');
        utils.completeAuth(url, false, function (err, url) {
            if (err) {
                return callback(err);
            }
            utils.catchAuthError(
                exports.push, url, [dir, options, cfg, doc], callback
            );
        });
    });
};

/**
 * Upload the app to the DB, catch auth errors and prompt for password
 */

exports.push = function (url, dir, options, cfg, doc, callback) {
    var db = couchdb(url);
    var root = couchdb(url);
    root.instance.pathname = '';
    root.session(function (err, info, resp) {
        if (err) {
            return callback(err);
        }
        var server_time = utils.ISODateString(new Date(resp.headers.date));
        if (!doc.kanso) {
            doc.kanso = {};
        }
        doc.kanso.push_time = server_time;
        doc.kanso.pushed_by = info.userCtx.name;

        // delete private/build time only properties
        delete doc.kanso.config._url;
        delete doc.kanso.config._utils;

        db.ensureDB(function (err) {
            if (err) {
                return callback(err);
            }
            var id = options.id || '_design/' + cfg.name;
            logger.info('Uploading...');

            db.save(id, doc, {force: true}, function (err) {
                callback(err, url, cfg, doc);
            });
        });
    });
};

/**
 * Tries to determine the right URL to report on the command-line after a
 * successful push
 *
 * OK: <url>
 */

exports.getAppURL = function (url, cfg, doc) {
    var newurl= urlParse(url);
    delete newurl.auth;
    delete newurl.host;
    var ddoc_url = urlFormat(newurl) + '/' + doc._id;

    if (!/^_design\//.test(doc._id)) {
        // not pushed as a design doc, report doc url instead of app url
        return ddoc_url;
    }

    var app_url = ddoc_url;
    if (cfg.index) {
        // if there's an index property in kanso.json
        app_url = ddoc_url + cfg.index;
    }
    if (cfg.baseURL !== undefined) {
        // if there is a custom baseURL defined
        newurl.pathname = cfg.baseURL + '/';
        app_url = urlFormat(newurl);
    }
    else if (doc.rewrites && doc.rewrites.length) {
        app_url = ddoc_url + '/_rewrite/';
    }
    else if (doc._attachments && doc._attachments['index.html']) {
        app_url = ddoc_url + '/index.html';
    }
    else if (doc._attachments && doc._attachments['index.htm']) {
        app_url = ddoc_url + '/index.htm';
    }
    return app_url;
};

/**
 * Opens the app URL in the browser when the --open option is used
 */

exports.openInBrowser = function (url, callback) {
    if (process.platform === 'linux') {
        cmd = 'xdg-open';
    }
    else {
        // OSX
        cmd = 'open';
    }
    console.log('Opening URL in browser...');
    exec(cmd + ' ' + url, callback);
};
<|endoftext|>


<commit_before>export const hashbang = rule => url => {
	const origin = document.location.origin,
		hashUrl = new URL(new URL(url, origin).hash.replace(/^#!?/iu, ''), origin),
		result = hashUrl.pathname.match(rule);
	return result && {
		result,
		url: hashUrl
	};
};

export const href = rule => url => {
	const result = url.match(rule);
	return result && { result };
};

export const match = (routes, url) => {
	for (const route of routes) {
		const match = route.rule instanceof RegExp
			? href(route.rule)(url)
			: route.rule(url);
		if (match) {
			return {
				...route,
				match,
				url
			};
		}
	}
};
<commit_msg>fix: handles encoded `#` in hash (#85)<commit_after>export const hashbang = rule => url => {
	const origin = document.location.origin,
		/* Chrome on iOS bug encodes second `#` in url as `%23`
		 * https://github.com/Neovici/cosmoz-frontend/issues/1524
		 * https://github.com/angular/angular.js/issues/7699
		*/
		hash = new URL(url, origin).hash.replace(/^#!?/iu, '').replace('%23', '#'),
		hashUrl = new URL(hash, origin),
		result = hashUrl.pathname.match(rule);
	return result && {
		result,
		url: hashUrl
	};
};

export const href = rule => url => {
	const result = url.match(rule);
	return result && { result };
};

export const match = (routes, url) => {
	for (const route of routes) {
		const match = route.rule instanceof RegExp
			? href(route.rule)(url)
			: route.rule(url);
		if (match) {
			return {
				...route,
				match,
				url
			};
		}
	}
};
<|endoftext|>


<commit_before>/**********************************************************\
|                                                          |
|                          hprose                          |
|                                                          |
| Official WebSite: http://www.hprose.com/                 |
|                   http://www.hprose.org/                 |
|                                                          |
\**********************************************************/

/**********************************************************\
 *                                                        *
 * hprose/common/Future.js                                *
 *                                                        *
 * Hprose Future for Node.js.                             *
 *                                                        *
 * LastModified: Jul 19, 2015                             *
 * Author: Ma Bingyao <andot@hprose.com>                  *
 *                                                        *
\**********************************************************/

/*jshint node:true, eqeqeq:true */
'use strict';

var TimeoutError = require('./TimeoutError');

var PENDING = 0;
var FULFILLED = 1;
var REJECTED = 2;

var setImmediate = global.setImmediate;
var setTimeout = global.setTimeout;
var clearTimeout = global.clearTimeout;
var foreach = Function.prototype.call.bind(Array.prototype.forEach);
var slice = Function.prototype.call.bind(Array.prototype.slice);

function syncCall(callback, next, x) {
    try {
        var r = callback(x);
        next.resolve(r);
    }
    catch(e) {
        next.reject(e);
    }
}

function asyncCall(callback, next, x) {
    setImmediate(function() {
        try {
            var r = callback(x);
            next.resolve(r);
        }
        catch(e) {
            next.reject(e);
        }
    });
}

function Future(computation) {
    var sync = !!computation;
    Object.defineProperties(this, {
        _subscribers: { value: [] },
        _sync: { value: sync },
        _call: { value: sync ? syncCall : asyncCall },
        resolve: { value: this.resolve.bind(this) },
        reject: { value: this.reject.bind(this) },
    });
    if (typeof computation === 'function') {
        setImmediate(function() {
            try {
                this.resolve(computation());
            }
            catch(e) {
                this.reject(e);
            }
        });
    }
}

function isFuture(obj) {
    return obj instanceof Future;
}

function isPromise(obj) {
    return isFuture(obj) || ((global.Promise) && (obj instanceof global.Promise) && (typeof (obj.then === 'function')));
}

function delayed(duration, value) {
    var computation = (typeof value === 'function') ?
                      value :
                      function() { return value; };
    var future = new Future();
    setTimeout(function() {
        try {
            future.resolve(computation());
        }
        catch(e) {
            future.reject(e);
        }
    }, duration);
    return future;
}

function error(e) {
    var future = new Future();
    future.reject(e);
    return future;
}

function sync(computation) {
    var future = new Future(true);
    try {
        future.resolve(computation());
    }
    catch(e) {
        future.reject(e);
    }
    return future;
}

function value(v) {
    var future = new Future(true);
    future.resolve(v);
    return future;
}

function promise(executor) {
    var future = new Future();
    executor(future.resolve, future.reject);
    return future;
}

function arraysize(array) {
    var size = 0;
    foreach(array, function() { ++size; });
    return size;
}

function all(array) {
    array = isPromise(array) ? array : value(array);
    return array.then(function(array) {
        var n = array.length;
        var count = arraysize(array);
        var result = new Array(n);
        if (count === 0) return value(result);
        var future = new Future();
        foreach(array, function(element, index) {
            var f = (isPromise(element) ? element : value(element));
            f.then(function(value) {
                result[index] = value;
                if (--count === 0) {
                    future.resolve(result);
                }
            },
            future.reject);
        });
        return future;
    });
}

function join() {
    return all(arguments);
}

function race(array) {
    array = isPromise(array) ? array : value(array);
    return array.then(function(array) {
        var future = new Future();
        foreach(array, function(element) {
            var f = (isPromise(element) ? element : value(element));
            f.then(future.resolve, future.reject);
        });
        return future;
    });
}

function any(array) {
    array = isPromise(array) ? array : value(array);
    return array.then(function(array) {
        var n = array.length;
        var count = arraysize(array);
        if (count === 0) {
            throw new RangeError('any(): array must not be empty');
        }
        var reasons = new Array(n);
        var future = new Future();
        foreach(array, function(element, index) {
            var f = (isPromise(element) ? element : value(element));
            f.then(future.resolve, function(e) {
                reasons[index] = e;
                if (--count === 0) {
                    future.reject(reasons);
                }
            });
        });
        return future;
    });
}

function settle(array) {
    array = isPromise(array) ? array : value(array);
    return array.then(function(array) {
        var n = array.length;
        var count = arraysize(array);
        var result = new Array(n);
        if (count === 0) return value(result);
        var future = new Future();
        foreach(array, function(element, index) {
            var f = (isPromise(element) ? element : value(element));
            f.whenComplete(function() {
                result[index] = f.inspect();
                if (--count === 0) {
                    future.resolve(result);
                }
            });
        });
        return future;
    });
}

function run(handler, thisArg /*, args */) {
    var args = slice(arguments, 2);
    return all(args).then(function(args) {
        return handler.apply(thisArg, args);
    });
}

function wrap(handler, thisArg) {
    return function() {
        return all(arguments).then(function(args) {
            return handler.apply(thisArg, args);
        });
    };
}

function forEach(array, callback, thisArg) {
    return all(array).then(function(array) {
        return array.forEach(callback, thisArg);
    });
}

function every(array, callback, thisArg) {
    return all(array).then(function(array) {
        return array.every(callback, thisArg);
    });
}

function some(array, callback, thisArg) {
    return all(array).then(function(array) {
        return array.some(callback, thisArg);
    });
}

function filter(array, callback, thisArg) {
    return all(array).then(function(array) {
        return array.filter(callback, thisArg);
    });
}

function map(array, callback, thisArg) {
    return all(array).then(function(array) {
        return array.map(callback, thisArg);
    });
}

function reduce(array, callback, initialValue) {
    return all(array).then(function(array) {
        return array.reduce(callback, initialValue);
    });
}

function reduceRight(array, callback, initialValue) {
    return all(array).then(function(array) {
        return array.reduceRight(callback, initialValue);
    });
}

Object.defineProperties(Future, {
    // port from Dart
    delayed: { value: delayed },
    error: { value: error },
    sync: { value : sync },
    value: { value : value },
    // Promise compatible
    all: { value : all },
    race: { value : race },
    resolve: { value : value },
    reject: { value : error },
    // extended methods
    promise: { value: promise },
    isFuture: { value: isFuture },
    isPromise: { value: isPromise },
    join: { value: join },
    any: { value: any },
    settle: { value: settle },
    run: {value: run },
    wrap: { value: wrap },
    // for array
    forEach: { value: forEach },
    every: { value: every },
    some: { value: some },
    filter: { value: filter },
    map: { value: map },
    reduce: { value: reduce },
    reduceRight: { value: reduceRight }
});

Object.defineProperties(Future.prototype, {
    _value: { writable: true },
    _reason: { writable: true },
    _state: { value: PENDING, writable: true },
    _resolve: { value: function(onfulfill, onreject, next, x) {
        if (isPromise(x)) {
            if (x === this) {
                throw new TypeError('Self resolution');
            }
            x.then(onfulfill, onreject)
             .then(next.resolve, next.reject);
            return;
        }
        if ((typeof x === 'object') || (typeof x === 'function')) {
            var then;
            try {
                then = x.then;
            }
            catch (e) {
                if (onreject) {
                    this._call(onreject, next, e);
                }
                else {
                    next.reject(e);
                }
                return;
            }
            if (typeof then === 'function') {
                try {
                    var f = then.call(x, onfulfill, onreject);
                    f.then(next.resolve, next.reject);
                }
                catch (e) {
                    next.reject(e);
                }
                return;
            }
        }
        if (onfulfill) {
            this._call(onfulfill, next, x);
        }
        else {
            next.resolve(x);
        }
    } },
    // Calling complete must not be done more than once.
    resolve: { value: function(value) {
        if (this._state === PENDING) {
            this._state = FULFILLED;
            this._value = value;
            var subscribers = this._subscribers;
            while (subscribers.length > 0) {
                var subscriber = subscribers.shift();
                this._resolve(subscriber.onfulfill,
                              subscriber.onreject,
                              subscriber.next,
                              value);
            }
        }
    } },
    // Calling complete must not be done more than once.
    reject: { value: function(reason) {
        if (this._state === PENDING) {
            this._state = REJECTED;
            this._reason = reason;
            var subscribers = this._subscribers;
            while (subscribers.length > 0) {
                var subscriber = subscribers.shift();
                if (subscriber.onreject) {
                    this._call(subscriber.onreject,
                               subscriber.next,
                               reason);
                }
                else {
                    subscriber.next.reject(reason);
                }
            }
        }
    } },
    then: { value: function(onfulfill, onreject) {
        if (typeof onfulfill !== 'function') onfulfill = null;
        if (typeof onreject !== 'function') onreject = null;
        if (onfulfill || onreject) {
            var next = new Future(this._sync);
            if (this._state === FULFILLED) {
                if (onfulfill) {
                    this._resolve(onfulfill, onreject, next, this._value);
                }
                else {
                    next.resolve(this._value);
                }
            }
            else if (this._state === REJECTED) {
                if (onreject) {
                    this._call(onreject, next, this._reason);
                }
                else {
                    next.reject(this._reason);
                }
            }
            else {
                this._subscribers.push({
                    onfulfill: onfulfill,
                    onreject: onreject,
                    next: next
                });
            }
            return next;
        }
        return this;
    } },
    inspect: { value: function() {
        switch (this._state) {
            case PENDING: return { state: 'pending' };
            case FULFILLED: return { state: 'fulfilled', value: this._value };
            case REJECTED: return { state: 'rejected', reason: this._reason };
        }
    } },
    catchError: { value: function(onreject, test) {
        if (typeof test === 'function') {
            var self = this;
            return this['catch'](function(e) {
                return (test(e) ? self['catch'](onreject) : self);
            });
        }
        return this['catch'](onreject);
    } },
    'catch': { value: function(onreject) {
        return this.then(null, onreject);
    } },
    whenComplete: { value: function(action) {
        return this.then(
            function(v) {
                var f = action();
                if (f === undefined) return v;
                f = isPromise(f) ? f : value(f);
                return f.then(function() { return v; });
            },
            function(e) {
                var f = action();
                if (f === undefined) throw e;
                f = isPromise(f) ? f : value(f);
                return f.then(function() { throw e; });
            }
        );
    } },
    timeout: { value: function(duration, reason) {
        var future = new Future();
        var timeoutId = setTimeout(function() {
            future.reject(reason || new TimeoutError('timeout'));
        }, duration);
        this.whenComplete(function() { clearTimeout(timeoutId); })
            .then(future.resolve, future.reject);
        return future;
    } },
    delay: { value: function(duration) {
        var future = new Future();
        this.then(function(result) {
            setTimeout(function() {
                future.resolve(result);
            }, duration);
        },
        future.reject);
        return future;
    } },
    tap: { value: function(onfulfilledSideEffect, thisArg) {
        return this.then(function(result) {
            onfulfilledSideEffect.call(thisArg, result);
            return result;
        });
    } },
    spread: { value: function(onfulfilledArray, thisArg) {
        return this.then(function(array) {
            return onfulfilledArray.apply(thisArg, array);
        });
    } },
    get: { value: function(key) {
        return this.then(function(result) {
            return result[key];
        });
    } },
    set: { value: function(key, value) {
        return this.then(function(result) {
            result[key] = value;
            return result;
        });
    } },
    apply: { value: function(method, args) {
        args = args || [];
        return this.then(function(result) {
            return all(args).then(function(args) {
                return result[method].apply(result, args);
            });
        });
    } },
    call: { value: function(method) {
        var args = slice(arguments, 1);
        return this.then(function(result) {
            return all(args).then(function(args) {
                return result[method].apply(result, args);
            });
        });
    } },
    bind: { value: function(method) {
        var bindargs = slice(arguments);
        if (Array.isArray(method)) {
            for (var i = 0, n = method.length; i < n; ++i) {
                bindargs[0] = method[i];
                this.bind.apply(this, bindargs);
            }
        }
        bindargs.shift();
        var self = this;
        Object.defineProperty(this, method, { value: function() {
            var args = slice(arguments);
            return self.then(function(result) {
                return all(bindargs.concat(args)).then(function(args) {
                    return result[method].apply(result, args);
                });
            });
        } });
        return this;
    } },
    forEach: { value: function(callback, thisArg) {
        return forEach(this, callback, thisArg);
    } },
    every: { value: function(callback, thisArg) {
        return every(this, callback, thisArg);
    } },
    some: { value: function(callback, thisArg) {
        return some(this, callback, thisArg);
    } },
    filter: { value: function(callback, thisArg) {
        return filter(this, callback, thisArg);
    } },
    map: { value: function(callback, thisArg) {
        return map(this, callback, thisArg);
    } },
    reduce: { value: function(callback, initialValue) {
        return reduce(this, callback, initialValue);
    } },
    reduceRight: { value: function(callback, initialValue) {
        return reduceRight(this, callback, initialValue);
    } }
});

global.hprose.Future = Future;

function Completer(sync) {
    var future = new Future(sync);
    Object.defineProperties(this, {
        future: { value: future },
        // Calling complete must not be done more than once.
        complete: { value: future.resolve },
        // Calling complete must not be done more than once.
        completeError: { value: future.reject },
        isCompleted: { get: function() {
            return ( future._state !== PENDING );
        } }
    });
}

Object.defineProperties(Completer, {
    sync: { value : function() { return new Completer(true); } }
});

global.hprose.Completer = Completer;
<commit_msg>Added attempt for Future<commit_after>/**********************************************************\
|                                                          |
|                          hprose                          |
|                                                          |
| Official WebSite: http://www.hprose.com/                 |
|                   http://www.hprose.org/                 |
|                                                          |
\**********************************************************/

/**********************************************************\
 *                                                        *
 * hprose/common/Future.js                                *
 *                                                        *
 * Hprose Future for Node.js.                             *
 *                                                        *
 * LastModified: Jul 19, 2015                             *
 * Author: Ma Bingyao <andot@hprose.com>                  *
 *                                                        *
\**********************************************************/

/*jshint node:true, eqeqeq:true */
'use strict';

var TimeoutError = require('./TimeoutError');

var PENDING = 0;
var FULFILLED = 1;
var REJECTED = 2;

var setImmediate = global.setImmediate;
var setTimeout = global.setTimeout;
var clearTimeout = global.clearTimeout;
var foreach = Function.prototype.call.bind(Array.prototype.forEach);
var slice = Function.prototype.call.bind(Array.prototype.slice);

function syncCall(callback, next, x) {
    try {
        var r = callback(x);
        next.resolve(r);
    }
    catch(e) {
        next.reject(e);
    }
}

function asyncCall(callback, next, x) {
    setImmediate(function() {
        try {
            var r = callback(x);
            next.resolve(r);
        }
        catch(e) {
            next.reject(e);
        }
    });
}

function Future(computation) {
    var sync = !!computation;
    Object.defineProperties(this, {
        _subscribers: { value: [] },
        _sync: { value: sync },
        _call: { value: sync ? syncCall : asyncCall },
        resolve: { value: this.resolve.bind(this) },
        reject: { value: this.reject.bind(this) },
    });
    if (typeof computation === 'function') {
        setImmediate(function() {
            try {
                this.resolve(computation());
            }
            catch(e) {
                this.reject(e);
            }
        });
    }
}

function isFuture(obj) {
    return obj instanceof Future;
}

function isPromise(obj) {
    return isFuture(obj) || ((global.Promise) && (obj instanceof global.Promise) && (typeof (obj.then === 'function')));
}

function delayed(duration, value) {
    var computation = (typeof value === 'function') ?
                      value :
                      function() { return value; };
    var future = new Future();
    setTimeout(function() {
        try {
            future.resolve(computation());
        }
        catch(e) {
            future.reject(e);
        }
    }, duration);
    return future;
}

function error(e) {
    var future = new Future();
    future.reject(e);
    return future;
}

function sync(computation) {
    var future = new Future(true);
    try {
        future.resolve(computation());
    }
    catch(e) {
        future.reject(e);
    }
    return future;
}

function value(v) {
    var future = new Future(true);
    future.resolve(v);
    return future;
}

function promise(executor) {
    var future = new Future();
    executor(future.resolve, future.reject);
    return future;
}

function arraysize(array) {
    var size = 0;
    foreach(array, function() { ++size; });
    return size;
}

function all(array) {
    array = isPromise(array) ? array : value(array);
    return array.then(function(array) {
        var n = array.length;
        var count = arraysize(array);
        var result = new Array(n);
        if (count === 0) return value(result);
        var future = new Future();
        foreach(array, function(element, index) {
            var f = (isPromise(element) ? element : value(element));
            f.then(function(value) {
                result[index] = value;
                if (--count === 0) {
                    future.resolve(result);
                }
            },
            future.reject);
        });
        return future;
    });
}

function join() {
    return all(arguments);
}

function race(array) {
    array = isPromise(array) ? array : value(array);
    return array.then(function(array) {
        var future = new Future();
        foreach(array, function(element) {
            var f = (isPromise(element) ? element : value(element));
            f.then(future.resolve, future.reject);
        });
        return future;
    });
}

function any(array) {
    array = isPromise(array) ? array : value(array);
    return array.then(function(array) {
        var n = array.length;
        var count = arraysize(array);
        if (count === 0) {
            throw new RangeError('any(): array must not be empty');
        }
        var reasons = new Array(n);
        var future = new Future();
        foreach(array, function(element, index) {
            var f = (isPromise(element) ? element : value(element));
            f.then(future.resolve, function(e) {
                reasons[index] = e;
                if (--count === 0) {
                    future.reject(reasons);
                }
            });
        });
        return future;
    });
}

function settle(array) {
    array = isPromise(array) ? array : value(array);
    return array.then(function(array) {
        var n = array.length;
        var count = arraysize(array);
        var result = new Array(n);
        if (count === 0) return value(result);
        var future = new Future();
        foreach(array, function(element, index) {
            var f = (isPromise(element) ? element : value(element));
            f.whenComplete(function() {
                result[index] = f.inspect();
                if (--count === 0) {
                    future.resolve(result);
                }
            });
        });
        return future;
    });
}

function attempt(handler/*, arg1, arg2, ... */) {
    var args = slice(arguments, 1);
    return all(args).then(function(args) {
        return handler.apply(undefined, args);
    });
}

function run(handler, thisArg/*, arg1, arg2, ... */) {
    var args = slice(arguments, 2);
    return all(args).then(function(args) {
        return handler.apply(thisArg, args);
    });
}

function wrap(handler, thisArg) {
    return function() {
        return all(arguments).then(function(args) {
            return handler.apply(thisArg, args);
        });
    };
}

function forEach(array, callback, thisArg) {
    return all(array).then(function(array) {
        return array.forEach(callback, thisArg);
    });
}

function every(array, callback, thisArg) {
    return all(array).then(function(array) {
        return array.every(callback, thisArg);
    });
}

function some(array, callback, thisArg) {
    return all(array).then(function(array) {
        return array.some(callback, thisArg);
    });
}

function filter(array, callback, thisArg) {
    return all(array).then(function(array) {
        return array.filter(callback, thisArg);
    });
}

function map(array, callback, thisArg) {
    return all(array).then(function(array) {
        return array.map(callback, thisArg);
    });
}

function reduce(array, callback, initialValue) {
    return all(array).then(function(array) {
        return array.reduce(callback, initialValue);
    });
}

function reduceRight(array, callback, initialValue) {
    return all(array).then(function(array) {
        return array.reduceRight(callback, initialValue);
    });
}

Object.defineProperties(Future, {
    // port from Dart
    delayed: { value: delayed },
    error: { value: error },
    sync: { value: sync },
    value: { value: value },
    // Promise compatible
    all: { value: all },
    race: { value: race },
    resolve: { value: value },
    reject: { value: error },
    // extended methods
    promise: { value: promise },
    isFuture: { value: isFuture },
    isPromise: { value: isPromise },
    join: { value: join },
    any: { value: any },
    settle: { value: settle },
    attempt: { value: attempt },
    run: { value: run },
    wrap: { value: wrap },
    // for array
    forEach: { value: forEach },
    every: { value: every },
    some: { value: some },
    filter: { value: filter },
    map: { value: map },
    reduce: { value: reduce },
    reduceRight: { value: reduceRight }
});

Object.defineProperties(Future.prototype, {
    _value: { writable: true },
    _reason: { writable: true },
    _state: { value: PENDING, writable: true },
    _resolve: { value: function(onfulfill, onreject, next, x) {
        if (isPromise(x)) {
            if (x === this) {
                throw new TypeError('Self resolution');
            }
            x.then(onfulfill, onreject)
             .then(next.resolve, next.reject);
            return;
        }
        if ((typeof x === 'object') || (typeof x === 'function')) {
            var then;
            try {
                then = x.then;
            }
            catch (e) {
                if (onreject) {
                    this._call(onreject, next, e);
                }
                else {
                    next.reject(e);
                }
                return;
            }
            if (typeof then === 'function') {
                try {
                    var f = then.call(x, onfulfill, onreject);
                    f.then(next.resolve, next.reject);
                }
                catch (e) {
                    next.reject(e);
                }
                return;
            }
        }
        if (onfulfill) {
            this._call(onfulfill, next, x);
        }
        else {
            next.resolve(x);
        }
    } },
    // Calling complete must not be done more than once.
    resolve: { value: function(value) {
        if (this._state === PENDING) {
            this._state = FULFILLED;
            this._value = value;
            var subscribers = this._subscribers;
            while (subscribers.length > 0) {
                var subscriber = subscribers.shift();
                this._resolve(subscriber.onfulfill,
                              subscriber.onreject,
                              subscriber.next,
                              value);
            }
        }
    } },
    // Calling complete must not be done more than once.
    reject: { value: function(reason) {
        if (this._state === PENDING) {
            this._state = REJECTED;
            this._reason = reason;
            var subscribers = this._subscribers;
            while (subscribers.length > 0) {
                var subscriber = subscribers.shift();
                if (subscriber.onreject) {
                    this._call(subscriber.onreject,
                               subscriber.next,
                               reason);
                }
                else {
                    subscriber.next.reject(reason);
                }
            }
        }
    } },
    then: { value: function(onfulfill, onreject) {
        if (typeof onfulfill !== 'function') onfulfill = null;
        if (typeof onreject !== 'function') onreject = null;
        if (onfulfill || onreject) {
            var next = new Future(this._sync);
            if (this._state === FULFILLED) {
                if (onfulfill) {
                    this._resolve(onfulfill, onreject, next, this._value);
                }
                else {
                    next.resolve(this._value);
                }
            }
            else if (this._state === REJECTED) {
                if (onreject) {
                    this._call(onreject, next, this._reason);
                }
                else {
                    next.reject(this._reason);
                }
            }
            else {
                this._subscribers.push({
                    onfulfill: onfulfill,
                    onreject: onreject,
                    next: next
                });
            }
            return next;
        }
        return this;
    } },
    inspect: { value: function() {
        switch (this._state) {
            case PENDING: return { state: 'pending' };
            case FULFILLED: return { state: 'fulfilled', value: this._value };
            case REJECTED: return { state: 'rejected', reason: this._reason };
        }
    } },
    catchError: { value: function(onreject, test) {
        if (typeof test === 'function') {
            var self = this;
            return this['catch'](function(e) {
                return (test(e) ? self['catch'](onreject) : self);
            });
        }
        return this['catch'](onreject);
    } },
    'catch': { value: function(onreject) {
        return this.then(null, onreject);
    } },
    whenComplete: { value: function(action) {
        return this.then(
            function(v) {
                var f = action();
                if (f === undefined) return v;
                f = isPromise(f) ? f : value(f);
                return f.then(function() { return v; });
            },
            function(e) {
                var f = action();
                if (f === undefined) throw e;
                f = isPromise(f) ? f : value(f);
                return f.then(function() { throw e; });
            }
        );
    } },
    timeout: { value: function(duration, reason) {
        var future = new Future();
        var timeoutId = setTimeout(function() {
            future.reject(reason || new TimeoutError('timeout'));
        }, duration);
        this.whenComplete(function() { clearTimeout(timeoutId); })
            .then(future.resolve, future.reject);
        return future;
    } },
    delay: { value: function(duration) {
        var future = new Future();
        this.then(function(result) {
            setTimeout(function() {
                future.resolve(result);
            }, duration);
        },
        future.reject);
        return future;
    } },
    tap: { value: function(onfulfilledSideEffect, thisArg) {
        return this.then(function(result) {
            onfulfilledSideEffect.call(thisArg, result);
            return result;
        });
    } },
    spread: { value: function(onfulfilledArray, thisArg) {
        return this.then(function(array) {
            return onfulfilledArray.apply(thisArg, array);
        });
    } },
    get: { value: function(key) {
        return this.then(function(result) {
            return result[key];
        });
    } },
    set: { value: function(key, value) {
        return this.then(function(result) {
            result[key] = value;
            return result;
        });
    } },
    apply: { value: function(method, args) {
        args = args || [];
        return this.then(function(result) {
            return all(args).then(function(args) {
                return result[method].apply(result, args);
            });
        });
    } },
    call: { value: function(method) {
        var args = slice(arguments, 1);
        return this.then(function(result) {
            return all(args).then(function(args) {
                return result[method].apply(result, args);
            });
        });
    } },
    bind: { value: function(method) {
        var bindargs = slice(arguments);
        if (Array.isArray(method)) {
            for (var i = 0, n = method.length; i < n; ++i) {
                bindargs[0] = method[i];
                this.bind.apply(this, bindargs);
            }
        }
        bindargs.shift();
        var self = this;
        Object.defineProperty(this, method, { value: function() {
            var args = slice(arguments);
            return self.then(function(result) {
                return all(bindargs.concat(args)).then(function(args) {
                    return result[method].apply(result, args);
                });
            });
        } });
        return this;
    } },
    forEach: { value: function(callback, thisArg) {
        return forEach(this, callback, thisArg);
    } },
    every: { value: function(callback, thisArg) {
        return every(this, callback, thisArg);
    } },
    some: { value: function(callback, thisArg) {
        return some(this, callback, thisArg);
    } },
    filter: { value: function(callback, thisArg) {
        return filter(this, callback, thisArg);
    } },
    map: { value: function(callback, thisArg) {
        return map(this, callback, thisArg);
    } },
    reduce: { value: function(callback, initialValue) {
        return reduce(this, callback, initialValue);
    } },
    reduceRight: { value: function(callback, initialValue) {
        return reduceRight(this, callback, initialValue);
    } }
});

global.hprose.Future = Future;

function Completer(sync) {
    var future = new Future(sync);
    Object.defineProperties(this, {
        future: { value: future },
        // Calling complete must not be done more than once.
        complete: { value: future.resolve },
        // Calling complete must not be done more than once.
        completeError: { value: future.reject },
        isCompleted: { get: function() {
            return ( future._state !== PENDING );
        } }
    });
}

Object.defineProperties(Completer, {
    sync: { value : function() { return new Completer(true); } }
});

global.hprose.Completer = Completer;
<|endoftext|>


<commit_before>
/**
 * Module dependencies.
 */

var debug = require('debug')('wpcom:media');

/**
 * Media methods
 *
 * @param {String} id
 * @param {String} sid site id
 * @param {WPCOM} wpcom
 * @api public
 */

function Media(id, sid, wpcom){
  if (!(this instanceof Media)) return new Media(id, sid, wpcom);

  this.wpcom = wpcom;
  this._sid = sid;
  this._id = id;

  if (!this._id) {
    debug('WARN: media id is not defined');
  }
}

/**
 * Get media
 *
 * @param {Object} [query]
 * @param {Function} fn
 * @api public
 */

Media.prototype.get = function(query, fn){
  var path = '/sites/' + this._sid + '/media/' + this._id;
  this.wpcom.sendRequest(path, query, null, fn);
};

/**
 * Add media
 *
 * @param {Object} body
 * @param {Function} fn
 * @api public
 */

Media.prototype.add = function(body, fn){
  var path = '/sites/' + this._sid + '/media/new';
  this.wpcom.sendRequest({ path: path, method: 'post' }, null, body, fn);
};

/**
 * Add media file
 *
 * @param {String|Array} files
 * @param {Function} fn
 */

Media.prototype.addFile = function(files, fn){
  var path = '/sites/' + this._sid + '/media/new';
  var params = { path: path, method: 'post', formData: [] };

  // process formData
  files = Array.isArray(files) ? files : [ files ];
  for (var i = 0; i < files.length; i++) {
    params.formData.push(['media', files[i]]);
  }

  this.wpcom.sendRequest(params, null, null, fn);
};

/**
 * Edit media
 *
 * @param {Object} body
 * @param {Function} fn
 * @api public
 */

Media.prototype.update = function(body, fn){
  var path = '/sites/' + this._sid + '/media/' + this._id;
  this.wpcom.sendRequest({ path: path, method: 'post' }, null, body, fn);
};

/**
 * Delete media
 *
 * @param {Function} fn
 * @api public
 */

Media.prototype['delete'] =
Media.prototype.del = function(fn){
  var path = '/sites/' + this._sid + '/media/' + this._id + '/delete';
  this.wpcom.sendRequest({ path: path, method: 'post' }, null, body, fn);
};

/**
 * Expose `Media` module
 */

module.exports = Media;
<commit_msg>media: remove unchecked methods<commit_after>
/**
 * Module dependencies.
 */

var debug = require('debug')('wpcom:media');

/**
 * Media methods
 *
 * @param {String} id
 * @param {String} sid site id
 * @param {WPCOM} wpcom
 * @api public
 */

function Media(id, sid, wpcom){
  if (!(this instanceof Media)) return new Media(id, sid, wpcom);

  this.wpcom = wpcom;
  this._sid = sid;
  this._id = id;

  if (!this._id) {
    debug('WARN: media id is not defined');
  }
}

/**
 * Get media
 *
 * @param {Object} [query]
 * @param {Function} fn
 * @api public
 */

Media.prototype.get = function(query, fn){
  var path = '/sites/' + this._sid + '/media/' + this._id;
  this.wpcom.sendRequest(path, query, null, fn);
};

/**
 * Add media file
 *
 * @param {String|Array} files
 * @param {Function} fn
 */

Media.prototype.addFile = function(files, fn){
  var path = '/sites/' + this._sid + '/media/new';
  var params = { path: path, method: 'post', formData: [] };

  // process formData
  files = Array.isArray(files) ? files : [ files ];
  for (var i = 0; i < files.length; i++) {
    params.formData.push(['media', files[i]]);
  }

  this.wpcom.sendRequest(params, null, null, fn);
};

/**
 * Delete media
 *
 * @param {Function} fn
 * @api public
 */

Media.prototype['delete'] =
Media.prototype.del = function(fn){
  var path = '/sites/' + this._sid + '/media/' + this._id + '/delete';
  this.wpcom.sendRequest({ path: path, method: 'post' }, null, body, fn);
};

/**
 * Expose `Media` module
 */

module.exports = Media;
<|endoftext|>


<commit_before>'use strict';

const fs = require('fs');
const Promise = require('bluebird');
const path = require('path');
const parseUrl = require('url').parse;
const formatUrl = require('url').format;
const child_process = require('child_process');
const yaml = require('js-yaml');
const _ = require('lodash');
const filename = process.env.SF_EVENTMESH_SETTINGS_PATH;

const ENV = process.env.NODE_ENV || 'development';
process.env.NODE_ENV = _
  .chain(ENV)
  .split(/[_-]/)
  .first()
  .value();
const buffer = fs.readFileSync(filename, 'utf8');
const context = {
  require: require,
  __filename: filename,
  __dirname: path.dirname(filename),
  base64_template: function (filePath) {
    const template = path.join(this.__dirname, filePath);
    return fs.readFileSync(template).toString('base64');
  },
  certificate: function (name) {
    const filename = path.join(this.__dirname, 'certs', name);
    return JSON.stringify(fs.readFileSync(filename).toString('ascii'));
  }
};
const config = yaml.safeLoad(_.template(buffer)(context))[ENV];

module.exports = config;<commit_msg>Removing unused funcitons<commit_after>'use strict';

const fs = require('fs');
const Promise = require('bluebird');
const path = require('path');
const parseUrl = require('url').parse;
const formatUrl = require('url').format;
const child_process = require('child_process');
const yaml = require('js-yaml');
const _ = require('lodash');
const filename = process.env.SF_EVENTMESH_SETTINGS_PATH;

const ENV = process.env.NODE_ENV || 'development';
process.env.NODE_ENV = _
  .chain(ENV)
  .split(/[_-]/)
  .first()
  .value();
const buffer = fs.readFileSync(filename, 'utf8');
const context = {
  require: require,
  __filename: filename,
  __dirname: path.dirname(filename),
};
const config = yaml.safeLoad(_.template(buffer)(context))[ENV];

module.exports = config;<|endoftext|>