<commit_before>var packet = require('dns-packet')
var dgram = require('dgram')
var thunky = require('thunky')
var events = require('events')
var os = require('os')

var noop = function () {}

module.exports = function (opts) {
  if (!opts) opts = {}

  var that = new events.EventEmitter()
  var port = typeof opts.port === 'number' ? opts.port : 5353
  var type = opts.type || 'udp4'
  var ip = opts.ip || opts.host || (type === 'udp4' ? '224.0.0.251' : null)
  var me = {address: ip, port: port}
  var memberships = {}
  var destroyed = false
  var interval = null

  if (type === 'udp6' && (!ip || !opts.interface)) {
    throw new Error('For IPv6 multicast you must specify `ip` and `interface`')
  }

  var socket = opts.socket || dgram.createSocket({
    type: type,
    reuseAddr: opts.reuseAddr !== false,
    toString: function () {
      return type
    }
  })

  socket.on('error', function (err) {
    if (err.code === 'EACCES' || err.code === 'EADDRINUSE') that.emit('error', err)
    else that.emit('warning', err)
  })

  socket.on('message', function (message, rinfo) {
    try {
      message = packet.decode(message)
    } catch (err) {
      that.emit('warning', err)
      return
    }

    that.emit('packet', message, rinfo)

    if (message.type === 'query') that.emit('query', message, rinfo)
    if (message.type === 'response') that.emit('response', message, rinfo)
  })

  socket.on('listening', function () {
    if (!port) port = me.port = socket.address().port
    if (opts.multicast !== false) {
      that.update()
      interval = setInterval(that.update, 5000)
      socket.setMulticastTTL(opts.ttl || 255)
      socket.setMulticastLoopback(opts.loopback !== false)
    }
  })

  var bind = thunky(function (cb) {
    if (!port) return cb(null)
    socket.once('error', cb)
    socket.bind(port, opts.interface, function () {
      socket.removeListener('error', cb)
      cb(null)
    })
  })

  bind(function (err) {
    if (err) return that.emit('error', err)
    that.emit('ready')
  })

  that.send = function (value, rinfo, cb) {
    if (typeof rinfo === 'function') return that.send(value, null, rinfo)
    if (!cb) cb = noop
    if (!rinfo) rinfo = me

    bind(onbind)

    function onbind (err) {
      if (destroyed) return cb()
      if (err) return cb(err)
      var message = packet.encode(value)
      socket.send(message, 0, message.length, rinfo.port, rinfo.address || rinfo.host, cb)
    }
  }

  that.response =
  that.respond = function (res, rinfo, cb) {
    if (Array.isArray(res)) res = {answers: res}

    res.type = 'response'
    that.send(res, rinfo, cb)
  }

  that.query = function (q, type, rinfo, cb) {
    if (typeof type === 'function') return that.query(q, null, null, type)
    if (typeof type === 'object' && type && type.port) return that.query(q, null, type, rinfo)
    if (typeof rinfo === 'function') return that.query(q, type, null, rinfo)
    if (!cb) cb = noop

    if (typeof q === 'string') q = [{name: q, type: type || 'ANY'}]
    if (Array.isArray(q)) q = {type: 'query', questions: q}

    q.type = 'query'
    that.send(q, rinfo, cb)
  }

  that.destroy = function (cb) {
    if (!cb) cb = noop
    if (destroyed) return process.nextTick(cb)
    destroyed = true
    clearInterval(interval)
    socket.once('close', cb)
    socket.close()
  }

  that.update = function () {
    var ifaces = opts.interface ? [].concat(opts.interface) : allInterfaces()
    var updated = false

    for (var i = 0; i < ifaces.length; i++) {
      var addr = ifaces[i]

      if (memberships[addr]) continue
      memberships[addr] = true
      updated = true

      try {
        socket.addMembership(ip, addr)
      } catch (err) {
        that.emit('error', err)
      }
    }

    if (!updated || !socket.setMulticastInterface) return
    socket.setMulticastInterface(opts.interface || defaultInterface())
  }

  return that
}

function defaultInterface () {
  var networks = os.networkInterfaces()
  var names = Object.keys(networks)

  for (var i = 0; i < names.length; i++) {
    var net = networks[names[i]]
    for (var j = 0; j < net.length; j++) {
      var iface = net[j]
      if (iface.family === 'IPv4' && !iface.internal) return iface.address
    }
  }

  return '127.0.0.1'
}

function allInterfaces () {
  var networks = os.networkInterfaces()
  var names = Object.keys(networks)
  var res = []

  for (var i = 0; i < names.length; i++) {
    var net = networks[names[i]]
    for (var j = 0; j < net.length; j++) {
      var iface = net[j]
      if (iface.family === 'IPv4') {
        res.push(iface.address)
        // could only addMembership once per interface (https://nodejs.org/api/dgram.html#dgram_socket_addmembership_multicastaddress_multicastinterface)
        break
      }
    }
  }

  return res
}
<commit_msg>bad membership should be a warning<commit_after>var packet = require('dns-packet')
var dgram = require('dgram')
var thunky = require('thunky')
var events = require('events')
var os = require('os')

var noop = function () {}

module.exports = function (opts) {
  if (!opts) opts = {}

  var that = new events.EventEmitter()
  var port = typeof opts.port === 'number' ? opts.port : 5353
  var type = opts.type || 'udp4'
  var ip = opts.ip || opts.host || (type === 'udp4' ? '224.0.0.251' : null)
  var me = {address: ip, port: port}
  var memberships = {}
  var destroyed = false
  var interval = null

  if (type === 'udp6' && (!ip || !opts.interface)) {
    throw new Error('For IPv6 multicast you must specify `ip` and `interface`')
  }

  var socket = opts.socket || dgram.createSocket({
    type: type,
    reuseAddr: opts.reuseAddr !== false,
    toString: function () {
      return type
    }
  })

  socket.on('error', function (err) {
    if (err.code === 'EACCES' || err.code === 'EADDRINUSE') that.emit('error', err)
    else that.emit('warning', err)
  })

  socket.on('message', function (message, rinfo) {
    try {
      message = packet.decode(message)
    } catch (err) {
      that.emit('warning', err)
      return
    }

    that.emit('packet', message, rinfo)

    if (message.type === 'query') that.emit('query', message, rinfo)
    if (message.type === 'response') that.emit('response', message, rinfo)
  })

  socket.on('listening', function () {
    if (!port) port = me.port = socket.address().port
    if (opts.multicast !== false) {
      that.update()
      interval = setInterval(that.update, 5000)
      socket.setMulticastTTL(opts.ttl || 255)
      socket.setMulticastLoopback(opts.loopback !== false)
    }
  })

  var bind = thunky(function (cb) {
    if (!port) return cb(null)
    socket.once('error', cb)
    socket.bind(port, opts.interface, function () {
      socket.removeListener('error', cb)
      cb(null)
    })
  })

  bind(function (err) {
    if (err) return that.emit('error', err)
    that.emit('ready')
  })

  that.send = function (value, rinfo, cb) {
    if (typeof rinfo === 'function') return that.send(value, null, rinfo)
    if (!cb) cb = noop
    if (!rinfo) rinfo = me

    bind(onbind)

    function onbind (err) {
      if (destroyed) return cb()
      if (err) return cb(err)
      var message = packet.encode(value)
      socket.send(message, 0, message.length, rinfo.port, rinfo.address || rinfo.host, cb)
    }
  }

  that.response =
  that.respond = function (res, rinfo, cb) {
    if (Array.isArray(res)) res = {answers: res}

    res.type = 'response'
    that.send(res, rinfo, cb)
  }

  that.query = function (q, type, rinfo, cb) {
    if (typeof type === 'function') return that.query(q, null, null, type)
    if (typeof type === 'object' && type && type.port) return that.query(q, null, type, rinfo)
    if (typeof rinfo === 'function') return that.query(q, type, null, rinfo)
    if (!cb) cb = noop

    if (typeof q === 'string') q = [{name: q, type: type || 'ANY'}]
    if (Array.isArray(q)) q = {type: 'query', questions: q}

    q.type = 'query'
    that.send(q, rinfo, cb)
  }

  that.destroy = function (cb) {
    if (!cb) cb = noop
    if (destroyed) return process.nextTick(cb)
    destroyed = true
    clearInterval(interval)
    socket.once('close', cb)
    socket.close()
  }

  that.update = function () {
    var ifaces = opts.interface ? [].concat(opts.interface) : allInterfaces()
    var updated = false

    for (var i = 0; i < ifaces.length; i++) {
      var addr = ifaces[i]

      if (memberships[addr]) continue
      memberships[addr] = true
      updated = true

      try {
        socket.addMembership(ip, addr)
      } catch (err) {
        that.emit('warning', err)
      }
    }

    if (!updated || !socket.setMulticastInterface) return
    socket.setMulticastInterface(opts.interface || defaultInterface())
  }

  return that
}

function defaultInterface () {
  var networks = os.networkInterfaces()
  var names = Object.keys(networks)

  for (var i = 0; i < names.length; i++) {
    var net = networks[names[i]]
    for (var j = 0; j < net.length; j++) {
      var iface = net[j]
      if (iface.family === 'IPv4' && !iface.internal) return iface.address
    }
  }

  return '127.0.0.1'
}

function allInterfaces () {
  var networks = os.networkInterfaces()
  var names = Object.keys(networks)
  var res = []

  for (var i = 0; i < names.length; i++) {
    var net = networks[names[i]]
    for (var j = 0; j < net.length; j++) {
      var iface = net[j]
      if (iface.family === 'IPv4') {
        res.push(iface.address)
        // could only addMembership once per interface (https://nodejs.org/api/dgram.html#dgram_socket_addmembership_multicastaddress_multicastinterface)
        break
      }
    }
  }

  return res
}
<|endoftext|>


<commit_before>var fs = require('fs');
var path = require('path');
var spawn = require('child_process').spawn;

var browserResolve = require('browser-resolve');
var nodeResolve = require('resolve');
var detective = require('detective');
var through = require('through2');
var concat = require('concat-stream');
var parents = require('parents');
var combine = require('stream-combiner');
var duplexer = require('duplexer2');
var copy = require('shallow-copy');

var inherits = require('inherits');
var Transform = require('readable-stream').Transform;

module.exports = Deps;
inherits(Deps, Transform);

function Deps (opts) {
    var self = this;
    if (!(this instanceof Deps)) return new Deps(opts);
    Transform.call(this, { objectMode: true });

    if (!opts) opts = {};

    this.basedir = opts.basedir || process.cwd();
    this.cache = opts.cache;
    this.pkgCache = opts.packageCache || {};
    this.pkgFileCache = {};
    this.pkgFileCachePending = {};
    this.visited = {};
    this.walking = {};
    this.entries = [];

    this.paths = opts.paths || process.env.NODE_PATH;
    if (typeof this.paths === 'string') {
        this.paths = process.env.NODE_PATH.split(':');
    }
    if (!this.paths) this.paths = [];

    this.transforms = [].concat(opts.transform).filter(Boolean);
    this.resolver = opts.resolve || browserResolve;
    this.options = opts;
    this.pending = 0;

    var topfile = path.join(this.basedir, '__fake.js');
    this.top = { id: topfile, filename: topfile, paths: this.paths };
}

Deps.prototype._transform = function (row, enc, next) {
    var self = this;
    self.pending ++;
    if (typeof row === 'string') {
        row = { file: row };
    }
    if (row.entry !== false) self.entries.push(row.file);

    self.lookupPackage(row.file, function (err, pkg) {
        if (err) return self.emit('error', err)
        self.pending --;
        start(pkg)
    });
    next();

    function start (pkg) {
        if (!pkg) pkg = {};
        if (!pkg.__dirname) pkg.__dirname = path.dirname(row.file);
        self.walk(row, self.top);
    }
};

Deps.prototype._flush = function () {
    if (this.pending === 0) this.push(null);
    this._ended = true;
};

Deps.prototype.resolve = function (id, parent, cb) {
    var self = this;
    var opts = self.options;

    if (xhas(self.cache, parent.id, 'deps', id)
    && self.cache[parent.id].deps) {
        var file = self.cache[parent.id].deps[id];
        var pkg = self.pkgCache[file];
        if (pkg) return cb(null, file, pkg);
        return self.lookupPackage(file, function (err, pkg) {
            cb(null, file, pkg);
        });
    }

    var pkgdir;
    parent.packageFilter = function (p, x) {
        pkgdir = x;
        if (opts.packageFilter) return opts.packageFilter(p, x);
        else return p;
    };

    if (opts.extensions) parent.extensions = opts.extensions;
    if (opts.modules) parent.modules = opts.modules;

    self.resolver(id, parent, function onresolve (err, file, pkg) {
        if (err) return cb(err);
        if (!file) return cb(new Error(
            'module not found: "' + id + '" from file '
            + parent.filename
        ));

        if (pkg && pkgdir) pkg.__dirname = pkgdir;
        if (!pkg || !pkg.__dirname) {
            self.lookupPackage(file, function (err, p) {
                if (err) return cb(err);
                if (!p) p = {};
                if (!p.__dirname) p.__dirname = path.dirname(file);
                self.pkgCache[file] = p;
                onresolve(err, file, opts.packageFilter
                    ? opts.packageFilter(p, p.__dirname) : p
                );
            });
        }
        else cb(err, file, pkg);
    });
};

Deps.prototype.readFile = function (file, pkg) {
    var tr = through();
    if (this.cache && this.cache[file]) {
        tr.push(this.cache[file].source);
        tr.push(null);
        return tr;
    }
    var rs = fs.createReadStream(file);
    rs.on('error', function (err) { tr.emit('error', err) });
    this.emit('file', file);
    return rs.pipe(this.getTransforms(file, pkg));
};

Deps.prototype.getTransforms = function (file, pkg) {
    var self = this;
    var isTopLevel = this.entries.some(function (main) {
        var m = path.relative(path.dirname(main), file);
        return m.split(/[\\\/]/).indexOf('node_modules') < 0;
    });

    var transforms = [].concat(isTopLevel ? this.transforms : [])
        .concat(getTransforms(pkg, this.options))
    ;
    if (transforms.length === 0) return through();

    var pending = transforms.length;
    var streams = [];
    var input = through();
    var output = through();
    var dup = duplexer(input, output);

    for (var i = 0; i < transforms.length; i++) (function (i) {
        makeTransform(transforms[i], function (err, trs) {
            if (err) return self.emit('error', err)
            streams[i] = trs;
            if (-- pending === 0) done();
        });
    })(i);
    return dup;

    function done () {
        var middle = combine.apply(null, streams);
        middle.on('error', function (err) {
            self.emit('error', err);
        });
        input.pipe(middle).pipe(output);
    }

    function makeTransform (tr, cb) {
        var trOpts = {};
        if (Array.isArray(tr)) {
            trOpts = tr[1];
            tr = tr[0];
        }
        if (typeof tr === 'function') {
            var t = tr(file, trOpts);
            self.emit('transform', t, file);
            nextTick(cb, null, wrapTransform(t));
        }
        else {
            loadTransform(tr, trOpts, function (err, trs) {
                if (err) return cb(err);
                cb(null, wrapTransform(trs));
            });
        }
    }

    function loadTransform (id, trOpts, cb) {
        var params = { basedir: path.dirname(file) };
        nodeResolve(id, params, function nr (err, res, again) {
            if (err && again) return cb(err);

            if (err) {
                params.basedir = pkg.__dirname;
                return nodeResolve(id, params, function (e, r) {
                    nr(e, r, true)
                });
            }

            if (!res) return cb(new Error(
                'cannot find transform module ' + tr
                + ' while transforming ' + file
            ));

            var r = require(res);
            if (typeof r !== 'function') {
                return cb(new Error('transform not a function'));
            }

            var trs = r(file, trOpts);
            self.emit('transform', trs, file);
            cb(null, trs);
        });
    }
};

Deps.prototype.walk = function (id, parent, cb) {
    var self = this;
    var opts = self.options;
    this.pending ++;

    var rec = {};
    if (typeof id === 'object') {
        rec = copy(id);
        if (rec.entry === false) delete rec.entry;
        id = rec.file;
    }

    self.resolve(id, parent, function (err, file, pkg) {
        if (err) return self.emit('error', err);
        if (self.visited[file]) {
            if (-- self.pending === 0) self.push(null);
            return cb && cb(null, file);
        }
        self.visited[file] = true;

        if (rec.source) return fromSource(rec.source);

        var c = self.cache && self.cache[file];
        if (c) return fromDeps(file, c.source, c.package, Object.keys(c.deps));

        self.readFile(file, pkg).pipe(concat(function (body) {
            fromSource(body.toString('utf8'));
        }));

        function fromSource (src) {
            var deps = self.parseDeps(file, src);
            if (deps) fromDeps(file, src, pkg, deps);
        }
    });

    function fromDeps (file, src, pkg, deps) {
        var p = deps.length;
        var current = {
            id: file,
            filename: file,
            paths: self.paths,
            package: pkg
        };
        var resolved = {};

        deps.forEach(function (id) {
            if (opts.filter && !opts.filter(id)) {
                resolved[id] = false;
                if (--p === 0) done();
                return;
            }
            self.walk(id, current, function (err, r) {
                resolved[id] = r;
                if (--p === 0) done();
            });
        });
        if (deps.length === 0) done();

        function done () {
            if (!rec.id) rec.id = file;
            if (!rec.source) rec.source = src;
            if (!rec.deps) rec.deps = resolved;
            if (!rec.file) rec.file = file;

            if (self.entries.indexOf(file) >= 0) {
                rec.entry = true;
            }
            self.push(rec);

            if (cb) cb(null, file);
            if (-- self.pending === 0 && self._ended) self.push(null);
        }
    }
};

Deps.prototype.parseDeps = function (file, src, cb) {
    if (this.options.noParse === true) return [];
    if (/\.json$/.test(file)) return [];

    if (Array.isArray(this.options.noParse)
    && this.options.noParse.indexOf(file) >= 0) {
        return [];
    }

    try { var deps = detective(src) }
    catch (ex) {
        var message = ex && ex.message ? ex.message : ex;
        this.emit('error', new Error(
            'Parsing file ' + file + ': ' + message
        ));
        return;
    }
    return deps;
};

Deps.prototype.lookupPackage = function (file, cb) {
    var self = this;

    var cached = this.pkgCache[file];
    if (cached) return nextTick(cb, null, cached);
    if (cached === false) return nextTick(cb, null, undefined);

    var dirs = parents(path.dirname(file));

    (function next () {
        if (dirs.length === 0) {
            self.pkgCache[file] = false;
            return cb(null, undefined);
        }
        var dir = dirs.shift();
        if (dir.split(/[\\\/]/).slice(-1)[0] === 'node_modules') {
            return cb(null, undefined);
        }

        var pkgfile = path.join(dir, 'package.json');

        var cached = self.pkgCache[pkgfile];
        if (cached) return nextTick(cb, null, cached);
        else if (cached === false) return next();

        var pcached = self.pkgFileCachePending[pkgfile];
        if (pcached) return pcached.push(onpkg);
        pcached = self.pkgFileCachePending[pkgfile] = [];

        fs.readFile(pkgfile, function (err, src) {
            if (err) return onpkg();
            try { var pkg = JSON.parse(src) }
            catch (err) {
                return onpkg(new Error([
                    err + ' while parsing json file ' + pkgfile
                ].join('')))
            }
            pkg.__dirname = dir;

            self.pkgCache[pkgfile] = pkg;
            self.pkgCache[file] = pkg;
            onpkg(null, pkg);
        });

        function onpkg (err, pkg) {
            if (self.pkgFileCachePending[pkgfile]) {
                var fns = self.pkgFileCachePending[pkgfile];
                delete self.pkgFileCachePending[pkgfile];
                fns.forEach(function (f) { f(err, pkg) });
            }
            if (err) cb(err)
            else if (pkg) cb(null, pkg)
            else {
                self.pkgCache[pkgfile] = false;
                next();
            }
        }
    })();
};

function getTransforms (pkg, opts) {
    var trx = [];
    if (opts.transformKey) {
        var n = pkg;
        var keys = opts.transformKey;
        for (var i = 0; i < keys.length; i++) {
            if (n && typeof n === 'object') n = n[keys[i]];
            else break;
        }
        if (i === keys.length) {
            trx = [].concat(n).filter(Boolean);
        }
    }
    return trx.concat(opts.globalTransform || []);
}

function nextTick (cb) {
    var args = [].slice.call(arguments, 1);
    process.nextTick(function () { cb.apply(null, args) });
}

function xhas (obj) {
    if (!obj) return false;
    for (var i = 1; i < arguments.length; i++) {
        var key = arguments[i];
        if (!has(obj, key)) return false;
        obj = obj[key];
    }
    return true;
}

function has (obj, key) {
    return Object.prototype.hasOwnProperty.call(obj, key);
}

function wrapTransform (tr) {
    if (typeof tr.read === 'function') return tr;
    var input = through(), output = through();
    input.pipe(tr).pipe(output);
    var wrapper = duplexer(input, output);
    tr.on('error', function (err) { wrapper.emit('error', err) });
    return wrapper;
}
<commit_msg>expose .globalTransforms<commit_after>var fs = require('fs');
var path = require('path');
var spawn = require('child_process').spawn;

var browserResolve = require('browser-resolve');
var nodeResolve = require('resolve');
var detective = require('detective');
var through = require('through2');
var concat = require('concat-stream');
var parents = require('parents');
var combine = require('stream-combiner');
var duplexer = require('duplexer2');
var copy = require('shallow-copy');

var inherits = require('inherits');
var Transform = require('readable-stream').Transform;

module.exports = Deps;
inherits(Deps, Transform);

function Deps (opts) {
    var self = this;
    if (!(this instanceof Deps)) return new Deps(opts);
    Transform.call(this, { objectMode: true });

    if (!opts) opts = {};

    this.basedir = opts.basedir || process.cwd();
    this.cache = opts.cache;
    this.pkgCache = opts.packageCache || {};
    this.pkgFileCache = {};
    this.pkgFileCachePending = {};
    this.visited = {};
    this.walking = {};
    this.entries = [];

    this.paths = opts.paths || process.env.NODE_PATH;
    if (typeof this.paths === 'string') {
        this.paths = process.env.NODE_PATH.split(':');
    }
    if (!this.paths) this.paths = [];

    this.transforms = [].concat(opts.transform).filter(Boolean);
    this.globalTransforms = [].concat(opts.globalTransform).filter(Boolean);
    this.resolver = opts.resolve || browserResolve;
    this.options = opts;
    this.pending = 0;

    var topfile = path.join(this.basedir, '__fake.js');
    this.top = { id: topfile, filename: topfile, paths: this.paths };
}

Deps.prototype._transform = function (row, enc, next) {
    var self = this;
    self.pending ++;
    if (typeof row === 'string') {
        row = { file: row };
    }
    if (row.entry !== false) self.entries.push(row.file);

    self.lookupPackage(row.file, function (err, pkg) {
        if (err) return self.emit('error', err)
        self.pending --;
        start(pkg)
    });
    next();

    function start (pkg) {
        if (!pkg) pkg = {};
        if (!pkg.__dirname) pkg.__dirname = path.dirname(row.file);
        self.walk(row, self.top);
    }
};

Deps.prototype._flush = function () {
    if (this.pending === 0) this.push(null);
    this._ended = true;
};

Deps.prototype.resolve = function (id, parent, cb) {
    var self = this;
    var opts = self.options;

    if (xhas(self.cache, parent.id, 'deps', id)
    && self.cache[parent.id].deps) {
        var file = self.cache[parent.id].deps[id];
        var pkg = self.pkgCache[file];
        if (pkg) return cb(null, file, pkg);
        return self.lookupPackage(file, function (err, pkg) {
            cb(null, file, pkg);
        });
    }

    var pkgdir;
    parent.packageFilter = function (p, x) {
        pkgdir = x;
        if (opts.packageFilter) return opts.packageFilter(p, x);
        else return p;
    };

    if (opts.extensions) parent.extensions = opts.extensions;
    if (opts.modules) parent.modules = opts.modules;

    self.resolver(id, parent, function onresolve (err, file, pkg) {
        if (err) return cb(err);
        if (!file) return cb(new Error(
            'module not found: "' + id + '" from file '
            + parent.filename
        ));

        if (pkg && pkgdir) pkg.__dirname = pkgdir;
        if (!pkg || !pkg.__dirname) {
            self.lookupPackage(file, function (err, p) {
                if (err) return cb(err);
                if (!p) p = {};
                if (!p.__dirname) p.__dirname = path.dirname(file);
                self.pkgCache[file] = p;
                onresolve(err, file, opts.packageFilter
                    ? opts.packageFilter(p, p.__dirname) : p
                );
            });
        }
        else cb(err, file, pkg);
    });
};

Deps.prototype.readFile = function (file, pkg) {
    var tr = through();
    if (this.cache && this.cache[file]) {
        tr.push(this.cache[file].source);
        tr.push(null);
        return tr;
    }
    var rs = fs.createReadStream(file);
    rs.on('error', function (err) { tr.emit('error', err) });
    this.emit('file', file);
    return rs.pipe(this.getTransforms(file, pkg));
};

Deps.prototype.getTransforms = function (file, pkg) {
    var self = this;
    var isTopLevel = this.entries.some(function (main) {
        var m = path.relative(path.dirname(main), file);
        return m.split(/[\\\/]/).indexOf('node_modules') < 0;
    });

    var transforms = [].concat(isTopLevel ? this.transforms : [])
        .concat(getTransforms(pkg, {
            globalTransform: this.globalTransforms,
            transformKey: this.options.transformKey
        }))
    ;
    if (transforms.length === 0) return through();

    var pending = transforms.length;
    var streams = [];
    var input = through();
    var output = through();
    var dup = duplexer(input, output);

    for (var i = 0; i < transforms.length; i++) (function (i) {
        makeTransform(transforms[i], function (err, trs) {
            if (err) return self.emit('error', err)
            streams[i] = trs;
            if (-- pending === 0) done();
        });
    })(i);
    return dup;

    function done () {
        var middle = combine.apply(null, streams);
        middle.on('error', function (err) {
            self.emit('error', err);
        });
        input.pipe(middle).pipe(output);
    }

    function makeTransform (tr, cb) {
        var trOpts = {};
        if (Array.isArray(tr)) {
            trOpts = tr[1];
            tr = tr[0];
        }
        if (typeof tr === 'function') {
            var t = tr(file, trOpts);
            self.emit('transform', t, file);
            nextTick(cb, null, wrapTransform(t));
        }
        else {
            loadTransform(tr, trOpts, function (err, trs) {
                if (err) return cb(err);
                cb(null, wrapTransform(trs));
            });
        }
    }

    function loadTransform (id, trOpts, cb) {
        var params = { basedir: path.dirname(file) };
        nodeResolve(id, params, function nr (err, res, again) {
            if (err && again) return cb(err);

            if (err) {
                params.basedir = pkg.__dirname;
                return nodeResolve(id, params, function (e, r) {
                    nr(e, r, true)
                });
            }

            if (!res) return cb(new Error(
                'cannot find transform module ' + tr
                + ' while transforming ' + file
            ));

            var r = require(res);
            if (typeof r !== 'function') {
                return cb(new Error('transform not a function'));
            }

            var trs = r(file, trOpts);
            self.emit('transform', trs, file);
            cb(null, trs);
        });
    }
};

Deps.prototype.walk = function (id, parent, cb) {
    var self = this;
    var opts = self.options;
    this.pending ++;

    var rec = {};
    if (typeof id === 'object') {
        rec = copy(id);
        if (rec.entry === false) delete rec.entry;
        id = rec.file;
    }

    self.resolve(id, parent, function (err, file, pkg) {
        if (err) return self.emit('error', err);
        if (self.visited[file]) {
            if (-- self.pending === 0) self.push(null);
            return cb && cb(null, file);
        }
        self.visited[file] = true;

        if (rec.source) return fromSource(rec.source);

        var c = self.cache && self.cache[file];
        if (c) return fromDeps(file, c.source, c.package, Object.keys(c.deps));

        self.readFile(file, pkg).pipe(concat(function (body) {
            fromSource(body.toString('utf8'));
        }));

        function fromSource (src) {
            var deps = self.parseDeps(file, src);
            if (deps) fromDeps(file, src, pkg, deps);
        }
    });

    function fromDeps (file, src, pkg, deps) {
        var p = deps.length;
        var current = {
            id: file,
            filename: file,
            paths: self.paths,
            package: pkg
        };
        var resolved = {};

        deps.forEach(function (id) {
            if (opts.filter && !opts.filter(id)) {
                resolved[id] = false;
                if (--p === 0) done();
                return;
            }
            self.walk(id, current, function (err, r) {
                resolved[id] = r;
                if (--p === 0) done();
            });
        });
        if (deps.length === 0) done();

        function done () {
            if (!rec.id) rec.id = file;
            if (!rec.source) rec.source = src;
            if (!rec.deps) rec.deps = resolved;
            if (!rec.file) rec.file = file;

            if (self.entries.indexOf(file) >= 0) {
                rec.entry = true;
            }
            self.push(rec);

            if (cb) cb(null, file);
            if (-- self.pending === 0 && self._ended) self.push(null);
        }
    }
};

Deps.prototype.parseDeps = function (file, src, cb) {
    if (this.options.noParse === true) return [];
    if (/\.json$/.test(file)) return [];

    if (Array.isArray(this.options.noParse)
    && this.options.noParse.indexOf(file) >= 0) {
        return [];
    }

    try { var deps = detective(src) }
    catch (ex) {
        var message = ex && ex.message ? ex.message : ex;
        this.emit('error', new Error(
            'Parsing file ' + file + ': ' + message
        ));
        return;
    }
    return deps;
};

Deps.prototype.lookupPackage = function (file, cb) {
    var self = this;

    var cached = this.pkgCache[file];
    if (cached) return nextTick(cb, null, cached);
    if (cached === false) return nextTick(cb, null, undefined);

    var dirs = parents(path.dirname(file));

    (function next () {
        if (dirs.length === 0) {
            self.pkgCache[file] = false;
            return cb(null, undefined);
        }
        var dir = dirs.shift();
        if (dir.split(/[\\\/]/).slice(-1)[0] === 'node_modules') {
            return cb(null, undefined);
        }

        var pkgfile = path.join(dir, 'package.json');

        var cached = self.pkgCache[pkgfile];
        if (cached) return nextTick(cb, null, cached);
        else if (cached === false) return next();

        var pcached = self.pkgFileCachePending[pkgfile];
        if (pcached) return pcached.push(onpkg);
        pcached = self.pkgFileCachePending[pkgfile] = [];

        fs.readFile(pkgfile, function (err, src) {
            if (err) return onpkg();
            try { var pkg = JSON.parse(src) }
            catch (err) {
                return onpkg(new Error([
                    err + ' while parsing json file ' + pkgfile
                ].join('')))
            }
            pkg.__dirname = dir;

            self.pkgCache[pkgfile] = pkg;
            self.pkgCache[file] = pkg;
            onpkg(null, pkg);
        });

        function onpkg (err, pkg) {
            if (self.pkgFileCachePending[pkgfile]) {
                var fns = self.pkgFileCachePending[pkgfile];
                delete self.pkgFileCachePending[pkgfile];
                fns.forEach(function (f) { f(err, pkg) });
            }
            if (err) cb(err)
            else if (pkg) cb(null, pkg)
            else {
                self.pkgCache[pkgfile] = false;
                next();
            }
        }
    })();
};

function getTransforms (pkg, opts) {
    var trx = [];
    if (opts.transformKey) {
        var n = pkg;
        var keys = opts.transformKey;
        for (var i = 0; i < keys.length; i++) {
            if (n && typeof n === 'object') n = n[keys[i]];
            else break;
        }
        if (i === keys.length) {
            trx = [].concat(n).filter(Boolean);
        }
    }
    return trx.concat(opts.globalTransform || []);
}

function nextTick (cb) {
    var args = [].slice.call(arguments, 1);
    process.nextTick(function () { cb.apply(null, args) });
}

function xhas (obj) {
    if (!obj) return false;
    for (var i = 1; i < arguments.length; i++) {
        var key = arguments[i];
        if (!has(obj, key)) return false;
        obj = obj[key];
    }
    return true;
}

function has (obj, key) {
    return Object.prototype.hasOwnProperty.call(obj, key);
}

function wrapTransform (tr) {
    if (typeof tr.read === 'function') return tr;
    var input = through(), output = through();
    input.pipe(tr).pipe(output);
    var wrapper = duplexer(input, output);
    tr.on('error', function (err) { wrapper.emit('error', err) });
    return wrapper;
}
<|endoftext|>


<commit_before>'use strict'

const isBlank = require('is-blank')
const nUrl    = require('normalize-url')
const psi     = require('psi')
const a11y    = require('a11y')
const html    = require('html-validator')
const styles  = require('stylestats')
const seo     = require('seo-checker')
const req     = require('request')
const request = require('request-promise-native')
const dom     = require('dom-stats')

module.exports = (url) => {
  if (isBlank(url) || typeof url !== 'string') {
    throw new TypeError('staats expected a url as a string')
  };

  url  = nUrl(url);

  html({url: url})
    .then(data => {
      console.log('-------------------')
      console.log('HTML validation')
      console.log('-------------------')

      let results = JSON.parse(data);

      for (let result in results.messages) {
        let test = new Object(result);
          test.status = (result.type == "error");
          test.name   = result.message;
          if (!result.firstLine) {
            test.firstLine = result.lastLine;
          }
          test.value  = `From line ${result.firstLine}, column ${result.firstColumn}; to line ${result.lastLine}, column ${result.lastColumn}`;

        console.log(test.status + ' // ' + test.name + ' // ' + test.value)
      }
    })
    .catch((error) => {console.error(error)});

  /*seo.load(url, function(data) {
    console.log('-------------------')
    console.log('SEO')
    console.log('-------------------')

    if (!data) {
      console.error('SEO checker failed :/')
    } else {
      let results = seo.meta(data);

      for (let result in results) {
        let test = new Object(result);
          test.status = isBlank(results[result]);
          test.name   = result;
          test.value  = results[result];

        console.log(test.status + ' // ' + test.name + ' // ' + test.value)
      }
    }
  });

  const css = new styles(url, {
    "uniqueFontSizes": false,
    "uniqueFontFamilies": false,
    "uniqueColors": false,
    "uniqueBackgroundImages": false
  });
  css.parse()
    .then(data => {
      console.log('-------------------')
      console.log('CSS stats')
      console.log('-------------------')

      let results = JSON.parse(JSON.stringify(data));

      for (let result in results) {
        // if result is propertiesCount, we'll have to do better :)
        let test = new Object(result);
          // 100 is arbitrary value, need a way to define a budget!
          test.status = (parseInt(results[result]) >= 100);
          test.name   = result;
          test.value  = results[result];

        console.log(test.status + ' // ' + test.name + ' // ' + test.value)
      }
    })
    .catch((error) => console.error(error));

  request(url)
    .then(data => {
      console.log('-------------------')
      console.log('DOM')
      console.log('-------------------')

      let results = dom(data);

      for (let result in results) {
        // if result is tagCounts, we'll have to do better :)
        let test = new Object(result);
          // 100 is arbitrary value, need a way to define a budget!
          test.status = (parseInt(results[result]) >= 100);
          test.name   = result;
          test.value  = results[result];

        console.log(test.status + ' // ' + test.name + ' // ' + test.value)
      }
    })
    .catch((error) => console.error(error));

  psi(url, {nokey: 'true', strategy: 'mobile'})
    .then(data => {
      console.log('-------------------')
      console.log('Page Speed Insights Scores')
      console.log('-------------------')

      let scores = data.ruleGroups;

      for (let result in scores) {
        let test = new Object(result);
          // 90 is arbitrary value, need a way to define a budget!
          test.status = (scores[result].score >= 90);
          test.name   = result;
          test.value  = scores[result].score;

        console.log(test.status + ' // ' + test.name + ' // ' + test.value)
      }

      console.log('-------------------')
      console.log('Page Speed Insights Stats')
      console.log('-------------------')

      let results = data.pageStats;

      for (let result in results) {
        let test = new Object(result);
          // 100 is arbitrary value, need a way to define a budget!
          test.status = (parseInt(results[result]) >= 100);
          test.name   = result;
          test.value  = results[result];

        console.log(test.status + ' // ' + test.name + ' // ' + test.value)
      }

      console.log('-------------------')
      console.log('Page Speed Insights Tests')
      console.log('-------------------')

      let formattedResults = data.formattedResults.ruleResults;

      for (let result in formattedResults) {
        let test = new Object(result);
          // 100 is arbitrary value, need a way to define a budget!
          test.status = (formattedResults[result].ruleImpact > 0);
          test.name   = formattedResults[result].localizedRuleName;
          test.value  = formattedResults[result].groups;
          if (formattedResults[result].summary) {
            test.value  = formattedResults[result].summary.format;
          }

        console.log(test.status + ' // ' + test.name + ' // ' + test.value)
      }
    })
    .catch((error) => console.error(error));

  a11y(url, function (error, data) {
    console.log('-------------------')
    console.log('Accessibility')
    console.log('-------------------')

    if (error) {
      console.error(error.message)
    }

    data.audit.forEach(function (result) {
      let test = new Object(result);
        test.status = (result.result == "FAIL");
        test.name   = result.heading;
        test.value  = result.elements.replace(/(\r\n\t|\n|\r\t)/gm, ', ');

      console.log(test.status + ' // ' + test.name + ' // ' + test.value)
    });
  });*/
}
<commit_msg>feat: normalize each checker's results as object<commit_after>'use strict'

const isBlank = require('is-blank')
const nUrl    = require('normalize-url')
const psi     = require('psi')
const a11y    = require('a11y')
const html    = require('html-validator')
const styles  = require('stylestats')
const seo     = require('seo-checker')
const req     = require('request')
const request = require('request-promise-native')
const dom     = require('dom-stats')

module.exports = (url) => {
  if (isBlank(url) || typeof url !== 'string') {
    throw new TypeError('staats expected a url as a string')
  };

  url  = nUrl(url);

  html({url: url})
    .then(data => {
      console.log('-------------------')
      console.log('HTML validation')
      console.log('-------------------')

      let messages = JSON.parse(data);
      let results  = messages.messages.reduce((results, value, key) => { results[key] = value; return results; }, {});

      for (let result in results) {
        let test = new Object(results[result]);
          test.status = (results[result].type == "error");
          test.name   = results[result].message;
          if (!results[result].firstLine) {
            test.firstLine = results[result].lastLine;
          }
          test.value  = `From line ${results[result].firstLine}, column ${results[result].firstColumn}; to line ${results[result].lastLine}, column ${results[result].lastColumn}`;

        console.log(test.status + ' // ' + test.name + ' // ' + test.value)
      }
    })
    .catch((error) => {console.error(error)});

  seo.load(url, function(data) {
    console.log('-------------------')
    console.log('SEO')
    console.log('-------------------')

    if (!data) {
      console.error('SEO checker failed :/')
    } else {
      let results = seo.meta(data);

      for (let result in results) {
        let test = new Object(result);
          test.status = isBlank(results[result]);
          test.name   = result;
          test.value  = results[result];

        console.log(test.status + ' // ' + test.name + ' // ' + test.value)
      }
    }
  });

  const css = new styles(url, {
    "uniqueFontSizes": false,
    "uniqueFontFamilies": false,
    "uniqueColors": false,
    "uniqueBackgroundImages": false
  });
  css.parse()
    .then(data => {
      console.log('-------------------')
      console.log('CSS stats')
      console.log('-------------------')

      let results = JSON.parse(JSON.stringify(data));

      for (let result in results) {
        // if result is propertiesCount, we'll have to do better :)
        let test = new Object(result);
          // 100 is arbitrary value, need a way to define a budget!
          test.status = (parseInt(results[result]) >= 100);
          test.name   = result;
          test.value  = results[result];

        console.log(test.status + ' // ' + test.name + ' // ' + test.value)
      }
    })
    .catch((error) => console.error(error));

  request(url)
    .then(data => {
      console.log('-------------------')
      console.log('DOM')
      console.log('-------------------')

      let results = dom(data);

      for (let result in results) {
        // if result is tagCounts, we'll have to do better :)
        let test = new Object(result);
          // 100 is arbitrary value, need a way to define a budget!
          test.status = (parseInt(results[result]) >= 100);
          test.name   = result;
          test.value  = results[result];

        console.log(test.status + ' // ' + test.name + ' // ' + test.value)
      }
    })
    .catch((error) => console.error(error));

  psi(url, {nokey: 'true', strategy: 'mobile'})
    .then(data => {
      console.log('-------------------')
      console.log('Page Speed Insights Scores')
      console.log('-------------------')

      let scores = data.ruleGroups;

      for (let result in scores) {
        let test = new Object(result);
          // 90 is arbitrary value, need a way to define a budget!
          test.status = (scores[result].score >= 90);
          test.name   = result;
          test.value  = scores[result].score;

        console.log(test.status + ' // ' + test.name + ' // ' + test.value)
      }

      console.log('-------------------')
      console.log('Page Speed Insights Stats')
      console.log('-------------------')

      let results = data.pageStats;

      for (let result in results) {
        let test = new Object(result);
          // 100 is arbitrary value, need a way to define a budget!
          test.status = (parseInt(results[result]) >= 100);
          test.name   = result;
          test.value  = results[result];

        console.log(test.status + ' // ' + test.name + ' // ' + test.value)
      }

      console.log('-------------------')
      console.log('Page Speed Insights Tests')
      console.log('-------------------')

      let formattedResults = data.formattedResults.ruleResults;

      for (let result in formattedResults) {
        let test = new Object(result);
          // 100 is arbitrary value, need a way to define a budget!
          test.status = (formattedResults[result].ruleImpact > 0);
          test.name   = formattedResults[result].localizedRuleName;
          test.value  = formattedResults[result].groups;
          if (formattedResults[result].summary) {
            test.value  = formattedResults[result].summary.format;
          }

        console.log(test.status + ' // ' + test.name + ' // ' + test.value)
      }
    })
    .catch((error) => console.error(error));

  a11y(url, function (error, data) {
    console.log('-------------------')
    console.log('Accessibility')
    console.log('-------------------')

    if (error) {
      console.error(error.message)
    }

    let results = data.audit.reduce((results, value, key) => { results[key] = value; return results; }, {});

    for (let result in results) {
      let test = new Object(results[result]);
        test.status = (results[result].result == "FAIL");
        test.name   = results[result].heading;
        test.value  = results[result].elements.replace(/(\r\n\t|\n|\r\t)/gm, ', ');

      console.log(test.status + ' // ' + test.name + ' // ' + test.value)
    }
  });
}
<|endoftext|>


<commit_before>var vm = require('vm');
var fs = require('fs');
var path = require('path');

var tsc = path.join(path.dirname(require.resolve("typescript")),"tsc.js");
var tscScript = vm.createScript(fs.readFileSync(tsc, "utf8"), tsc);
var libPath = path.join(path.dirname(require.resolve("typescript")), "lib.d.ts")

var options = {
  nodeLib: false,
  targetES5: true,
  moduleKind: 'commonjs',
  exitOnError: true
};

module.exports = function(opts) {
  options = merge(options, opts);
};

require.extensions['.ts'] = function(module) {
  var jsname = compileTS(module);
  runJS(jsname, module);
};

function isModified(tsname, jsname) {
  var tsMTime = fs.statSync(tsname).mtime;

  try {
    var jsMTime = fs.statSync(jsname).mtime;
  } catch (e) { //catch if file does not exists
    jsMTime = 0;
  }

  return tsMTime > jsMTime;
}

/**
 * Compiles TypeScript file, returns js file path
 * @return {string} js file path
 */
function compileTS (module) {
  var exitCode = 0;
  var tmpDir = path.join(process.cwd(), "tmp", "tsreq");
  var jsname = path.join(tmpDir, path.basename(module.filename, ".ts") + ".js");

  if (!isModified(module.filename, jsname)) {
    return jsname;
  }

  var argv = [
    "node",
    "tsc.js",
    "--nolib",
    "--target",
    options.targetES5 ? "ES5" : "ES3", !! options.moduleKind ? "--module" : "", !! options.moduleKind ? options.moduleKind : "",
    "--outDir",
    tmpDir,
    libPath,
    options.nodeLib ? path.resolve(__dirname, "typings/node.d.ts") : null,
    module.filename
  ];

  var proc = merge(merge({}, process), {
    argv: compact(argv),
    exit: function(code) {
      if (code !== 0 && options.exitOnError) {
        console.error('Fatal Error. Unable to compile TypeScript file. Exiting.');
        process.exit(code);
      }
      exitCode = code;
    }
  });

  var sandbox = {
    process: proc,
    require: require,
    module: module,
    Buffer: Buffer,
    setTimeout: setTimeout
  };

  tscScript.runInNewContext(sandbox);
  if (exitCode != 0) {
    throw new Error('Unable to compile TypeScript file.');
  }

  return jsname;
}

function runJS (jsname, module) {
  var content = fs.readFileSync(jsname, 'utf8');

  var sandbox = {};
  for (var k in global) {
    sandbox[k] = global[k];
  }
  sandbox.require = module.require.bind(module);
  sandbox.exports = module.exports;
  sandbox.__filename = jsname;
  sandbox.__dirname = path.dirname(module.filename);
  sandbox.module = module;
  sandbox.global = sandbox;
  sandbox.root = root;

  return vm.runInNewContext(content, sandbox, { filename: jsname });
}

function merge(a, b) {
  if (a && b) {
    for (var key in b) {
      a[key] = b[key];
    }
  }
  return a;
};

function compact(arr) {
  var narr = [];
  arr.forEach(function(data) {
    if (data) narr.push(data);
  });
  return narr;
}
<commit_msg>Skip merging properties whose getters throw<commit_after>var vm = require('vm');
var fs = require('fs');
var path = require('path');

var tsc = path.join(path.dirname(require.resolve("typescript")),"tsc.js");
var tscScript = vm.createScript(fs.readFileSync(tsc, "utf8"), tsc);
var libPath = path.join(path.dirname(require.resolve("typescript")), "lib.d.ts")

var options = {
  nodeLib: false,
  targetES5: true,
  moduleKind: 'commonjs',
  exitOnError: true
};

module.exports = function(opts) {
  options = merge(options, opts);
};

require.extensions['.ts'] = function(module) {
  var jsname = compileTS(module);
  runJS(jsname, module);
};

function isModified(tsname, jsname) {
  var tsMTime = fs.statSync(tsname).mtime;

  try {
    var jsMTime = fs.statSync(jsname).mtime;
  } catch (e) { //catch if file does not exists
    jsMTime = 0;
  }

  return tsMTime > jsMTime;
}

/**
 * Compiles TypeScript file, returns js file path
 * @return {string} js file path
 */
function compileTS (module) {
  var exitCode = 0;
  var tmpDir = path.join(process.cwd(), "tmp", "tsreq");
  var jsname = path.join(tmpDir, path.basename(module.filename, ".ts") + ".js");

  if (!isModified(module.filename, jsname)) {
    return jsname;
  }

  var argv = [
    "node",
    "tsc.js",
    "--nolib",
    "--target",
    options.targetES5 ? "ES5" : "ES3", !! options.moduleKind ? "--module" : "", !! options.moduleKind ? options.moduleKind : "",
    "--outDir",
    tmpDir,
    libPath,
    options.nodeLib ? path.resolve(__dirname, "typings/node.d.ts") : null,
    module.filename
  ];

  var proc = merge(merge({}, process), {
    argv: compact(argv),
    exit: function(code) {
      if (code !== 0 && options.exitOnError) {
        console.error('Fatal Error. Unable to compile TypeScript file. Exiting.');
        process.exit(code);
      }
      exitCode = code;
    }
  });

  var sandbox = {
    process: proc,
    require: require,
    module: module,
    Buffer: Buffer,
    setTimeout: setTimeout
  };

  tscScript.runInNewContext(sandbox);
  if (exitCode != 0) {
    throw new Error('Unable to compile TypeScript file.');
  }

  return jsname;
}

function runJS (jsname, module) {
  var content = fs.readFileSync(jsname, 'utf8');

  var sandbox = {};
  for (var k in global) {
    sandbox[k] = global[k];
  }
  sandbox.require = module.require.bind(module);
  sandbox.exports = module.exports;
  sandbox.__filename = jsname;
  sandbox.__dirname = path.dirname(module.filename);
  sandbox.module = module;
  sandbox.global = sandbox;
  sandbox.root = root;

  return vm.runInNewContext(content, sandbox, { filename: jsname });
}

function merge(a, b) {
  if (a && b) {
    for (var key in b) {
      try {
        a[key] = b[key];
      } catch(e) {}
    }
  }
  return a;
};

function compact(arr) {
  var narr = [];
  arr.forEach(function(data) {
    if (data) narr.push(data);
  });
  return narr;
}
<|endoftext|>


<commit_before>// Generated by CoffeeScript 1.9.0
console.log('ok');
<commit_msg>remove js file<commit_after><|endoftext|>


<commit_before>module.exports = {
    plugins: [
        'vue'
    ],
    extends: [
        'vast',
        'plugin:vue/recommended'
    ]
};
<commit_msg>Add common errors and best practices rules<commit_after>module.exports = {
    plugins: [
        'vue'
    ],
    extends: [
        'vast',
        'plugin:vue/recommended'
    ],
    rules: {
        // Possible errors:
        // this rule only covers case when used in code like: Vue.component...
        'vue/no-shared-component-data': 2,
        'vue/require-valid-default-prop': 2,

        // Best practices:
        'vue/html-end-tags': 2,
        'vue/no-async-in-computed-properties': 2,
        'vue/no-duplicate-attributes': 2,
        'vue/no-side-effects-in-computed-properties': 2,
        // this could be part of the Stylistic Issues
        'vue/order-in-components': 1

        // Stylistic Issues:
    }
};
<|endoftext|>


<commit_before>'use strict';
var _ = require('lodash');

module.exports = function (inputObj, opts) {
  // Ensure that `opts` is always an object.
  opts = (opts && typeof opts === 'object') ? opts : {};

  var width = (opts.width && typeof opts.width === 'number') ? opts.width : require('window-size').width;
  var barChar = opts.ascii ? '=' : require('figures').square;

  var maxBarWidth = width - (width > 20 ? 20 : 1);

  var totalSum = 0.0;
  var percentage = [];
  var barWidths = [];

  var values = _.values(inputObj);
  var keys = _.keys(inputObj);

  var printValues = opts.values;

  totalSum = _.sum(values);
  percentage = _.map(values, (elem) => elem / totalSum * 100);
  var maxPercentage = _.max(percentage);

  var fixedLabels = [];

  var labelsTrue = opts.labels || false;

  var maxLabelLength = 0;

  if (labelsTrue) {
    maxLabelLength = _.max(_.map(keys, e => e.toString().length));
    fixedLabels = _.map(inputObj, (value, key) => {
      var padLength = maxLabelLength - key.toString().length + 1;
      return padLength > 0 ? (key + new Array(padLength).join(' ')) : '';
    });
  }

  maxBarWidth = labelsTrue ? (maxBarWidth - maxLabelLength) : maxBarWidth;

  barWidths = _.map(percentage, elem => {
    var potentialWidth = Math.ceil(elem / maxPercentage * maxBarWidth);
    return (potentialWidth <= 1 ? 0 : potentialWidth);
  });

  percentage.forEach(function (element, index, array) {
    var elementLine = (labelsTrue ? fixedLabels[index] : '');
    elementLine += ' : ';
    elementLine += new Array(barWidths[index]).join(barChar);
    elementLine += '  ';
    elementLine += (printValues ? (values[index].toFixed(2)) : (element.toFixed(2) + '%'));
    console.log(elementLine);
  });

  if (_.filter(values, 0).length > 0 && opts.warnings) {
    var message = "This terminal's width is too less!";

    if (labelsTrue) {
      message += ' You can remove labels, and try again!';
    }

    console.log(message);
  }
};
<commit_msg>filter barWidths properly<commit_after>'use strict';
var _ = require('lodash');

module.exports = function (inputObj, opts) {
  // Ensure that `opts` is always an object.
  opts = (opts && typeof opts === 'object') ? opts : {};

  var width = (opts.width && typeof opts.width === 'number') ? opts.width : require('window-size').width;
  var barChar = opts.ascii ? '=' : require('figures').square;

  var maxBarWidth = width - (width > 20 ? 20 : 1);

  var totalSum = 0.0;
  var percentage = [];
  var barWidths = [];

  var values = _.values(inputObj);
  var keys = _.keys(inputObj);

  var printValues = opts.values;

  totalSum = _.sum(values);
  percentage = _.map(values, (elem) => elem / totalSum * 100);
  var maxPercentage = _.max(percentage);

  var fixedLabels = [];

  var labelsTrue = opts.labels || false;

  var maxLabelLength = 0;

  if (labelsTrue) {
    maxLabelLength = _.max(_.map(keys, e => e.toString().length));
    fixedLabels = _.map(inputObj, (value, key) => {
      var padLength = maxLabelLength - key.toString().length + 1;
      return padLength > 0 ? (key + new Array(padLength).join(' ')) : '';
    });
  }

  maxBarWidth = labelsTrue ? (maxBarWidth - maxLabelLength) : maxBarWidth;

  barWidths = _.map(percentage, elem => {
    var potentialWidth = Math.ceil(elem / maxPercentage * maxBarWidth);
    return (potentialWidth <= 1 ? 0 : potentialWidth);
  });

  percentage.forEach(function (element, index, array) {
    var elementLine = (labelsTrue ? fixedLabels[index] : '');
    elementLine += ' : ';
    elementLine += new Array(barWidths[index]).join(barChar);
    elementLine += '  ';
    elementLine += (printValues ? (values[index].toFixed(2)) : (element.toFixed(2) + '%'));
    console.log(elementLine);
  });

  if (_.filter(barWidths, x => x == 0).length > 0 && opts.warnings) {
    var message = "This terminal's width is too less!";

    if (labelsTrue) {
      message += ' You can remove labels, and try again!';
    }

    console.log(message);
  }
};
<|endoftext|>


<commit_before>/*!
 * template-helper-apidocs <https://github.com/jonschlinkert/template-helper-apidocs>
 *
 * Copyright (c) 2014-2015, Jon Schlinkert.
 * Licensed under the MIT License.
 */

'use strict';

/**
 * Module dependencies
 */

var fs = require('fs');
var glob = require('globby');
var bindHelpers = require('template-bind-helpers');
var comments = require('js-comments');
var relative = require('relative');
var isGlob = require('is-glob');
var clone = require('clone-deep');
var merge = require('mixin-deep');

/**
 * Generate API docs from code comments for any JavaScript
 * files that match the given `patterns`. Note that **only code
 * comments with `@api public` will be rendered.**
 *
 * **Example**
 *
 * ```js
 * apidocs("index.js");
 * ```
 *
 * @param  {String} `patterns` Glob patterns for files with code comments to render.
 * @param  {Object} `options` Options to pass to [js-comments].
 * @return {String} Markdown-formatted API documentation
 * @api public
 */

module.exports = function apidocs(patterns, opts) {
  opts = merge({}, this && this.options, opts);
  opts.file = opts.file || {};
  opts.dest = opts.dest || 'README.md';

  var delims = opts.escapeDelims;
  var files = isGlob ? glob.sync(patterns, opts) : [patterns];
  var len = files.length, i = 0;
  var res = '';

  if (this && this.app) {
    opts = bindHelpers(this.app, opts, false);
  }

  while (len--) {
    var fp = files[i++];
    var str = fs.readFileSync(fp, 'utf8');
    var arr = comments.parse(str, opts);
    var checked, n = 0;

    arr = filter(arr, opts, checked, n);

    var ctx = clone(opts);
    ctx.file.path = ctx.file.path || fp;
    if (ctx.file.path.indexOf('//') === -1) {
      ctx.file.path = relative(opts.dest, ctx.file.path);
    }
    res += comments.render(arr, ctx);
  }

  res = comments.format(res);
  if (this && this.app) {
    res = res.split(delims[0] || '<%%=').join('__DELIM__');
    res = this.app.render(res, opts);
    res = res.split('__DELIM__').join(delims[1] || '<%=');
  }
  return res;
};

function filter(arr, opts, checked, n) {
  return arr.filter(function (ele, i) {
    n = n || 0;
    if (!checked && /Copyright/.test(ele.description) && i === 0) {
      checked = true;
      n++;
    }
    if (opts.skipFirst && i === n) return false;
    return true;
  });
}
<commit_msg>ensure that `cwd` is defined<commit_after>/*!
 * template-helper-apidocs <https://github.com/jonschlinkert/template-helper-apidocs>
 *
 * Copyright (c) 2014-2015, Jon Schlinkert.
 * Licensed under the MIT License.
 */

'use strict';

/**
 * Module dependencies
 */

var fs = require('fs');
var glob = require('globby');
var bindHelpers = require('template-bind-helpers');
var comments = require('js-comments');
var relative = require('relative');
var isGlob = require('is-glob');
var clone = require('clone-deep');
var merge = require('mixin-deep');

/**
 * Generate API docs from code comments for any JavaScript
 * files that match the given `patterns`. Note that **only code
 * comments with `@api public` will be rendered.**
 *
 * **Example**
 *
 * ```js
 * apidocs("index.js");
 * ```
 *
 * @param  {String} `patterns` Glob patterns for files with code comments to render.
 * @param  {Object} `options` Options to pass to [js-comments].
 * @return {String} Markdown-formatted API documentation
 * @api public
 */

module.exports = function apidocs(patterns, opts) {
  opts = merge({}, this && this.options, opts);
  opts.file = opts.file || {};
  opts.dest = opts.dest || 'README.md';
  opts.cwd = opts.cwd || process.cwd();

  var delims = opts.escapeDelims;
  var files = isGlob ? glob.sync(patterns, opts) : [patterns];
  var len = files.length, i = 0;
  var res = '';

  if (this && this.app) {
    opts = bindHelpers(this.app, opts, false);
  }

  while (len--) {
    var fp = files[i++];
    var str = fs.readFileSync(fp, 'utf8');
    var arr = comments.parse(str, opts);
    var checked, n = 0;

    arr = filter(arr, opts, checked, n);

    var ctx = clone(opts);
    ctx.file.path = ctx.file.path || fp;
    if (ctx.file.path.indexOf('//') === -1) {
      ctx.file.path = relative(opts.dest, ctx.file.path);
    }
    res += comments.render(arr, ctx);
  }

  res = comments.format(res);
  if (this && this.app) {
    res = res.split(delims[0] || '<%%=').join('__DELIM__');
    res = this.app.render(res, opts);
    res = res.split('__DELIM__').join(delims[1] || '<%=');
  }
  return res;
};

function filter(arr, opts, checked, n) {
  return arr.filter(function (ele, i) {
    n = n || 0;
    if (!checked && /Copyright/.test(ele.description) && i === 0) {
      checked = true;
      n++;
    }
    if (opts.skipFirst && i === n) return false;
    return true;
  });
}
<|endoftext|>


<commit_before>'use strict'

const EventEmitter = require('events').EventEmitter
const Parser = require('node-expat').Parser

class XMLStream extends EventEmitter {
  constructor (stream, options) {
    super()
    options = options || {}
    this.encoding = options.encoding || 'UTF-8'
    this.stream = stream
    this.parser = new Parser(this.encoding)
    this.stream.pipe(this.parser)
    this.explicitText = options.explicitText
    this.explicitArrays = options.explicitArrays
    this._attachEvents()
    this._root = {}
    this._elementTree = [{
      isRoot: true,
      element: this._root,
      children: null
    }]
  }

  _attachEvents () {
    const stream = this.stream
    const parser = this.parser
    stream.on('error', this._handleError.bind(this))
    parser.on('error', this._handleError.bind(this))
    parser.on('close', this._handleClose.bind(this))
    parser.on('startElement', this._handleStartElement.bind(this))
    parser.on('endElement', this._handleEndElement.bind(this))
    parser.on('text', this._handleText.bind(this))
    parser.on('end', this._handleEnd.bind(this))
  }

  _handleEnd () {
    this.emit('end', this._root)
  }

  _handleClose () {
    this.emit('close')
  }

  _handleError (err) {
    // We are only emitting one error.
    if (this._errored) return
    this._errored = true
    this.emit('error', err)
    this.parser.destroy()
  }

  _getLastElementFromTree () {
    const tree = this._elementTree
    return tree[tree.length - 1]
  }

  _handleStartElement (name, attrs) {
    const newElement = {
      $: attrs
    }

    this._elementTree.push({
      isRoot: false,
      element: newElement,
      children: [],
      parent: this._getLastElementFromTree(),
      name: name
    })

    if (this._currentElement) { // this._currentElement === lastEl.parent.element
      let lastEl = this._getLastElementFromTree()
      if (!this._currentElement[name]) {
        this._currentElement[name] = []
        lastEl.parent.children.push(name)
      }
      let newLen = this._currentElement[name].push(newElement)
      lastEl.childIndex = newLen - 1
    } else {
      this._root[name] = newElement
    }
    this._currentElement = newElement
  }

  _handleEndElement (endName) {
    const oldElement = this._elementTree.pop()
    const name = oldElement.name
    const children = oldElement.children
    const parent = oldElement.parent
    const childIndex = oldElement.childIndex
    let el = oldElement.element

    if (name !== endName) {
      return this._handleError(new Error(`parser ended element '${endName}', which is not the element we are building ('${name}')`))
    }
    this._currentElement = parent

    if (!this.explicitArrays) {
      for (let i = 0; i < children.length; i++) {
        let child = children[i]
        if (el[child].length === 1) {
          el[child] = el[child][0]
        }
      }
    }

    if (!this.explicitText) {
      let hasProps = false
      for (let a in el.$) {
        if (el.$.hasOwnProperty(a)) {
          hasProps = true
          break
        }
      }
      if (!hasProps && !children.length) {
        el = el._
        // We also need to set this child on the parent.
        parent.element[name][childIndex] = el
      }
    }

    this.emit('element', el, name)
    this.emit('element: ' + name, el, name)
  }

  _handleText (text) {
    const curel = this._currentElement
    curel._ = curel._ || ''
    curel._ += text
  }

  pause () {
    this.stream.pause()
  }

  resume () {
    this.stream.resume()
  }
}

module.exports = XMLStream
<commit_msg>reference fixes<commit_after>'use strict'

const EventEmitter = require('events').EventEmitter
const Parser = require('node-expat').Parser

class XMLStream extends EventEmitter {
  constructor (stream, options) {
    super()
    options = options || {}
    this.encoding = options.encoding || 'UTF-8'
    this.stream = stream
    this.parser = new Parser(this.encoding)
    this.stream.pipe(this.parser)
    this.explicitText = options.explicitText
    this.explicitArrays = options.explicitArrays
    this._attachEvents()
    this._root = {}
    this._elementTree = [{
      isRoot: true,
      element: this._root,
      children: null
    }]
  }

  _attachEvents () {
    const stream = this.stream
    const parser = this.parser
    stream.on('error', this._handleError.bind(this))
    parser.on('error', this._handleError.bind(this))
    parser.on('close', this._handleClose.bind(this))
    parser.on('startElement', this._handleStartElement.bind(this))
    parser.on('endElement', this._handleEndElement.bind(this))
    parser.on('text', this._handleText.bind(this))
    parser.on('end', this._handleEnd.bind(this))
  }

  _handleEnd () {
    this.emit('end', this._root)
  }

  _handleClose () {
    this.emit('close')
  }

  _handleError (err) {
    // We are only emitting one error.
    if (this._errored) return
    this._errored = true
    this.emit('error', err)
    this.parser.destroy()
  }

  _getLastElementFromTree () {
    const tree = this._elementTree
    return tree[tree.length - 1]
  }

  _handleStartElement (name, attrs) {
    const newElement = {
      $: attrs
    }

    const parent = this._getLastElementFromTree()

    this._elementTree.push({
      isRoot: false,
      element: newElement,
      children: [],
      parent: parent,
      name: name
    })

    const current = this._getLastElementFromTree()

    if (!parent.isRoot) {
      if (!parent.element[name]) {
        parent.element[name] = []
        parent.children.push(name)
      }
      let newLen = parent.element[name].push(newElement)
      current.childIndex = newLen - 1
    } else {
      this._root[name] = newElement
    }
  }

  _handleEndElement (endName) {
    const oldElement = this._elementTree.pop()
    const name = oldElement.name
    const children = oldElement.children
    const parent = oldElement.parent
    const childIndex = oldElement.childIndex
    let el = oldElement.element

    if (name !== endName) {
      return this._handleError(new Error(`parser ended element '${endName}', which is not the element we are building ('${name}')`))
    }

    if (!this.explicitArrays) {
      for (let i = 0; i < children.length; i++) {
        let child = children[i]
        if (el[child].length === 1) {
          el[child] = el[child][0]
        }
      }
    }

    if (!this.explicitText) {
      let hasProps = false
      for (let a in el.$) {
        if (el.$.hasOwnProperty(a)) {
          hasProps = true
          break
        }
      }
      if (!hasProps && !children.length) {
        el = el._
        // We also need to set this child on the parent.
        if (!parent.isRoot) {
          parent.element[name][childIndex] = el
        }
      }
    }

    this.emit('element', el, name)
    this.emit('element: ' + name, el, name)
  }

  _handleText (text) {
    const curel = this._getLastElementFromTree().element
    curel._ = curel._ || ''
    curel._ += text
  }

  pause () {
    this.stream.pause()
  }

  resume () {
    this.stream.resume()
  }
}

module.exports = XMLStream
<|endoftext|>


<commit_before>class SyntaxErrorReporter {
  key: string;
  parent: Function;
  child: Function;

  get parentNotation() {
    return `${this.parent.constructor.name}#${this.key}`;
  }

  get childNotation() {
    return `${this.child.constructor.name}#${this.key}`;
  }

  constructor(propertyKey, parentKlass, childClass) {
    this.key = propertyKey;
    this.parent = parentKlass;
    this.child = childClass;
  }

  error(msg) {
    msg = msg
      .replace('{parent}', this.parentNotation)
      .replace('{child}', this.childNotation);

    throw new SyntaxError(msg);
  }
}

function getDescriptorType(descriptor) {
  if (descriptor.hasOwnProperty('value')) {
    return 'data';
  }

  if (descriptor.hasOwnProperty('get') || descriptor.hasOwnProperty('set')) {
    return 'accessor';
  }

  // If none of them exist, browsers treat it as
  // a data descriptor with a value of `undefined`
  return 'data';
}

function checkDataDescriptors(parent, child, reportor) {
  const parentValueType = typeof parent.value;
  const childValueType = typeof child.value;

  if (parentValueType !== childValueType) {
    reportor.error(`Descriptor value types do not match. {parent} is "${parentValueType}", {child} is "${childValueType}"`);
  }
}

function checkAccessorDescriptors(parent, child, reportor) {

}

function checkDescriptors(parent, child, reportor) {
  if (parent === undefined) {
    reportor.error(`{child} marked as @override but {parent} was not defined (perhaps misspelled?)`);
  }

  const parentType = getDescriptorType(parent);
  const childType = getDescriptorType(child);

  if (parentType !== childType) {
    reportor.error(`Descriptor types do not match. {parent} is "${parentType}", {child} is "${childType}"`);
  }

  switch (childType) {
    case 'data':
      checkDataDescriptors(parent, child, reportor);
      break;

    case 'accessor':
      checkAccessorDescriptors(parent, child, reportor);
      break;
  }
}

function override(klass, key, descriptor) {
  const superKlass = Object.getPrototypeOf(klass);
  const superDescriptor = Object.getOwnPropertyDescriptor(superKlass, key);
  const reportor = new SyntaxErrorReporter(key, superKlass, klass);

  checkDescriptors(superDescriptor, descriptor, reportor);

  return descriptor;
}<commit_msg>export @override<commit_after>class SyntaxErrorReporter {
  key: string;
  parent: Function;
  child: Function;

  get parentNotation() {
    return `${this.parent.constructor.name}#${this.key}`;
  }

  get childNotation() {
    return `${this.child.constructor.name}#${this.key}`;
  }

  constructor(propertyKey, parentKlass, childClass) {
    this.key = propertyKey;
    this.parent = parentKlass;
    this.child = childClass;
  }

  error(msg) {
    msg = msg
      .replace('{parent}', this.parentNotation)
      .replace('{child}', this.childNotation);

    throw new SyntaxError(msg);
  }
}

function getDescriptorType(descriptor) {
  if (descriptor.hasOwnProperty('value')) {
    return 'data';
  }

  if (descriptor.hasOwnProperty('get') || descriptor.hasOwnProperty('set')) {
    return 'accessor';
  }

  // If none of them exist, browsers treat it as
  // a data descriptor with a value of `undefined`
  return 'data';
}

function checkDataDescriptors(parent, child, reportor) {
  const parentValueType = typeof parent.value;
  const childValueType = typeof child.value;

  if (parentValueType !== childValueType) {
    reportor.error(`Descriptor value types do not match. {parent} is "${parentValueType}", {child} is "${childValueType}"`);
  }
}

function checkAccessorDescriptors(parent, child, reportor) {

}

function checkDescriptors(parent, child, reportor) {
  if (parent === undefined) {
    reportor.error(`{child} marked as @override but {parent} was not defined (perhaps misspelled?)`);
  }

  const parentType = getDescriptorType(parent);
  const childType = getDescriptorType(child);

  if (parentType !== childType) {
    reportor.error(`Descriptor types do not match. {parent} is "${parentType}", {child} is "${childType}"`);
  }

  switch (childType) {
    case 'data':
      checkDataDescriptors(parent, child, reportor);
      break;

    case 'accessor':
      checkAccessorDescriptors(parent, child, reportor);
      break;
  }
}

export function override(klass, key, descriptor) {
  const superKlass = Object.getPrototypeOf(klass);
  const superDescriptor = Object.getOwnPropertyDescriptor(superKlass, key);
  const reportor = new SyntaxErrorReporter(key, superKlass, klass);

  checkDescriptors(superDescriptor, descriptor, reportor);

  return descriptor;
}<|endoftext|>


<commit_before>// Dependencies
//const modules = require('./lib/modules');
//const instances = require('./lib/instances');
//const events = require('./lib/events');
const cayley = require('cayley');
const Adapter = require('./lib/cayley_adapter');
const VIS = require('./lib/cayley_vis');
const GET = require('./lib/cayley_get');
const POST = require('./lib/cayley_post');
const DELETE = require('./lib/cayley_delete');
const utils = require('./lib/utils');

function connect (state, db) {
    state.client = cayley(db);
    state.g = state.client.graph;
}

function getHandler (Methods, fn, params) {

    if (typeof Methods[fn] !== 'function') {
        throw new Error('Flow-api.cayley: Method "' + fn + '" doesn\' exists.');
    }

    return (scope, state, args, data, next) => {

        // create db client for state
        if (!state.client) {
            connect(state, scope.env.db);
        }

        let query_args = [state.g];
        for (let i = 0, l = params.length; i < l; ++i) {

            if (typeof data[params[i]] === 'undefined') {
                return next(new Error('Flow-api.get.' + fn  + ': Missing parameter "' + params[i]  + '".'));
            }

            query_args.push(data[params[i]]);
        };

        query_args.push(!data.session || !data.session.role ? scope.env.role : data.session.role);

        data.readable = Methods[fn].apply(null, query_args);

        try {
            if (data.readable instanceof Array) {
                data.readable.forEach(stream => stream.pause());
            } else {
                data.readable.pause();
            }
        } catch (err) {
            return next(err);
        }

        data.resume = data.readable;
        next(null, data);
    }
}

function postHandler (METHOD) {
    return (scope, state, args, data, next) => {

        // create db client for state
        if (!state.client) {
            connect(state, scope.env.db);
        }

        let count = 1;
        const errors = [];
        const success = [];
        const done = () => {
            data.body = {
                success: success,
                errors: errors
            };

            next(null, data);
        };

        // parse request
        data.req.on('data', req => {
            ++count
            METHOD(state.client, req, (err, res) => {

                if (err) {

                    if (err instanceof Error) {
                        err = err.message;
                    }

                    errors.push(err);
                } else {
                    success.push(res);
                }

                if (--count === 0) {
                    done();
                }
            });
        });

        data.req.on('error', (err) => next(err));

        // parse end
        data.req.on('end', () => {
            if (--count === 0) {
                done();
            }
        });
    };
}

function deleteHandler (scope, state, args, data, next) {

    // create db client for state
    if (!state.client) {
        connect(state, scope.env.db);
    }

    DELETE(state.client, data.req.url);
    data.body = {status: "ok"};
    next(null, data);
}

// export API methods
module.exports = {
    _connect: connect,
    utils: utils,
    flow: getHandler(Adapter, 'flow', ['id']),
    vis: {
        networks: getHandler(VIS, 'vis_networks', ['id']),
        entrypoints: getHandler(VIS, 'vis_entrypoints', ['id']),
        entrypoint: getHandler(VIS, 'vis_entrypoint', ['id']),
        sequence: getHandler(VIS, 'vis_sequence', ['id']),
        handler: getHandler(VIS, 'vis_handler', ['id']),
        object: getHandler(VIS, 'vis_object', ['id'])
    },
    get: getHandler(GET, 'get', ['id', 'type']),
    save: postHandler(POST),
    remove: postHandler(DELETE)
};
<commit_msg>create store instance, stream result for post requests<commit_after>"use strict"

const FLOW = require('./lib/request_flow');
const VIS = require('./lib/request_vis');
const GET = require('./lib/request_get');
const POST = require('./lib/request_post');
const DELETE = require('./lib/request_delete');
const Store = require('./lib/store');
const utils = require('./lib/utils');

function getHandler (Methods, fn, params) {

    if (typeof Methods[fn] !== 'function') {
        throw new Error('Flow-api.cayley: Method "' + fn + '" doesn\' exists.');
    }

    return (scope, state, args, data, next) => {

        // create store instance on state
        if (!state.store) {
            // TODO handle errors
            state.store = Store(scope.env.FlowApiStore);
        }

        let query_args = [state.store];
        for (let i = 0, l = params.length; i < l; ++i) {

            if (typeof data[params[i]] === 'undefined') {
                return next(new Error('Flow-api.get.' + fn  + ': Missing parameter "' + params[i]  + '".'));
            }

            query_args.push(data[params[i]]);
        };

        query_args.push(!data.session || !data.session.role ? scope.env.role : data.session.role);

        data.readable = Methods[fn].apply(null, query_args);
        data.readable.pause();
        data.resume = data.readable;

        next(null, data);
    }
}

function postHandler (METHOD) {
    return (scope, state, args, data, next) => {

        // create store instance on state
        if (!state.store) {
            state.store = Store(scope.env.FlowApiStore);
        }

        data.readable = req.pipe(METHOD(state.store));
        next(null, data);
    };
}

// export API methods
module.exports = {
    utils: utils,
    flow: getHandler(FLOW, 'flow', ['id']),
    vis: {
        networks: getHandler(VIS, 'networks', ['id']),
        entrypoints: getHandler(VIS, 'outNodeNames', ['id']),
        entrypoint: getHandler(VIS, 'outNodeNames', ['id']),
        sequence: getHandler(VIS, 'outNodeNames', ['id']),
        handler: getHandler(VIS, 'handler', ['id']),
        object: getHandler(VIS, 'getObject', ['id'])
    },
    get: getHandler(GET, 'get', ['id', 'type']),
    save: postHandler(POST),
    remove: postHandler(DELETE)
};
<|endoftext|>