Beispiel #1
0
exports.DefaultResponseHandler = function (data, ops) {
  if (ops.h) {
    logger.info('REQUEST', data.request);
    logger.info('RESPONSE META', {
      statusCode  : data.response.statusCode,
      headers     : data.response.headers
    });
  }

  var rs = Readable();
  rs.push(data.response.body);
  rs.push(null);

  var format = get_formatter(data.response.headers['content-type']);
  if (format && !ops.r) {
    try {
      var lint = get_linter(format);
      var lint_dup = duplexer(lint.stdin, lint.stdout);
      var pygm = spawn('pygmentize', ['-l', format]);
      var pygm_dup = duplexer(pygm.stdin, pygm.stdout);
      rs.pipe(lint_dup).pipe(pygm_dup).pipe(process.stdout);
    } catch(e) {
      console.log(e);
    }
  } else {
    rs.pipe(process.stdout); // pipe to logger ? huh ? 
  }
}
Beispiel #2
0
module.exports = function (run) {
  var outputA = through()
    , outputB = through()
    , inputA  = through().pause()
    , inputB  = through().pause()
    , count   = 0
    , iv

  setTimeout(function () {
    inputA.pipe(hyperquest.post('http://localhost:8000')).pipe(outputA)
    if (!run)
      inputB.pipe(hyperquest.post('http://localhost:8001')).pipe(outputB)
  }, 500)

  iv = setInterval(function () {
    var w = words[count].trim() + '\n'
    inputA.write(w)
    inputB.write(w)

    if (++count == words.length) {
      clearInterval(iv)
      inputA.end()
      inputB.end()
    }
  }, 50)
    
  return {
      args: []
    , a: duplexer(inputA, outputA)
    , b: duplexer(inputB, outputB)
  }
}
module.exports = function (opts) {
    var inputA = through().pause();
    var inputB = through().pause();
    var aPort = Math.floor(Math.random() * 40000 + 10000);
    var bPort = aPort + 1;
    
    var outputA = through();
    var outputB = through();
    
    setTimeout(function () {
        var hqa = hyperquest.post('http://localhost:' + aPort);
        hqa.on('error', function (err) {
            console.error('ACTUAL SERVER ' + err.stack);
        });
        inputA.pipe(hqa).pipe(outputA);
        
        if (!opts.run) {
            var hqb = hyperquest.post('http://localhost:' + bPort)
            hqb.on('error', function (err) {
                console.error('EXPECTED SERVER ' + err.stack);
            });
            inputB.pipe(hqb).pipe(outputB);
        }
        
        inputA.resume();
        inputB.resume();
    }, 500);
    
    var offset = Math.floor(words.length*Math.random());
    var count = 0;
    var iv = setInterval(function () {
        var w = words[(offset+count)%words.length] + '\n';
        inputA.write(w);
        inputB.write(w);
        
        if (++count === 20) {
            clearInterval(iv);
            inputA.end();
            inputB.end();
            a.emit('kill');
            b.emit('kill');
        }
    }, 50);
    
    var a = duplexer(inputA, outputA);
    var b = duplexer(inputB, outputB);
    return {
        a: a,
        aArgs: [ aPort ],
        b: b,
        bArgs: [ bPort ],
        showStdout: true
    };
};
Beispiel #4
0
 function handler() {
   var args = Array.prototype.slice.call(arguments);
   var callback, cmd;
   if (typeof args[args.length-1] == 'function') {
     callback = args.pop();
   }
   cmd = '"' + args.join('&&') + '"';
   if (!local) {
     _args.push(cmd);
     cmd = 'ssh ';
   }
   var result = exec(cmd + _args.join(' '), function (err, stdout, stderr) {
     if (options.verbose) {
       var uri = 'ssh://%s@%s:%s';
       console.log('\u001b[36m' + uri + '\u001b[39m',
                   options.l, options.host, options.p);
       if (stdout) console.log(stdout);
       if (stderr) console.error(stderr);
       if (err) process.exit(err.code);
     }
     if (callback) callback(err, stdout);
   });
   var stream = duplex(result.stdin, result.stdout);
   stream.stdout = result.stdout;
   stream.stdin = result.stdin;
   stream.stderr = result.stderr;
   return stream;
 }
Beispiel #5
0
brotliSize.stream = function(opt_params) {
  opt_params = opt_params || {};
  var input = new stream.PassThrough();
  var output = new stream.PassThrough();
  var wrapper = duplexer(input, output);

  var brotliSize = 0;
  var brotli = iltorb.compressStream(opt_params)
    .on('data', function(buf) {
      brotliSize += buf.length;
    })
    .on('error', function() {
      wrapper.brotliSize = 0;
    })
    .on('end', function() {
      wrapper.brotliSize = brotliSize;
      wrapper.emit('brotli-size', brotliSize);
      output.end();
    });

  input.pipe(brotli);
  input.pipe(output, {end: false});

  return wrapper;
};
Beispiel #6
0
Client.prototype.createRPCStream = function () {
  var self = this;

  var parser = parse();
  var out = through();
  var stream = duplex(parser, out);

  parser.on('data', function (op) {
    var id = op[1];
    if (id === 0) return;
    var args = op[2];
    self.callbacks[id].apply(null, args);
    delete self.callbacks[id];
  });

  self.on('op', function (method, cb, args) {
    var cbId = 0;

    if (cb) {
      cbId = self.nextId;
      self.callbacks[cbId] = cb;
      self.nextId++;
    }

    out.write(stringify(methods[method], cbId, args));
  });

  return stream;
}
Beispiel #7
0
function BufferStream() {
    var writable = PauseStream()
        , readable = PauseStream()
        , buffered = duplexer(writable, readable)

    buffered.buffer = buffer
    buffered.empty = empty

    return buffered

    function buffer() {
        writable.pause()
        return buffered
    }

    function empty(stream, options) {
        if (stream) {
            options = options || {}
            writable.pipe(stream).pipe(readable, options)
        }

        writable.resume()
        return buffered
    }
}
Beispiel #8
0
module.exports = function () {
    var parser = JSONStream.parse([ true ]);
    var output = through(write, end);
    parser.pipe(output);
    
    var first = true;
    var entries = [];
    
    return duplexer(parser, output);
    
    function write (row) {
        if (first) output.emit('data', prelude);
        
        this.emit('data', [
            (first ? '' : ','),
            JSON.stringify(row.id),
            ':[',
            'function(require,module,exports){' + row.source + '}',
            ',',
            JSON.stringify(row.deps || {}),
            ']'
        ].join(''));
        
        first = false;
        entries.push(row.id);
    }
    
    function end () {
        if (first) output.emit('data', prelude);
        
        this.emit('data', '},{},' + JSON.stringify(entries) + ')');
        this.emit('end');
    }
};
Beispiel #9
0
Client.prototype.createAddStream = function(){
   var path = [this.options.path,this.options.core,'update/json?commit='+ this.autoCommit +'&wt=json']
      .filter(function(element){
         if(element) return true;
         return false;
      })
      .join('/');
   var headers = {
      'content-type' : 'application/json',
      'charset' : 'utf-8'
   };
   if(this.options.authorization){
      headers['authorization'] = this.options.authorization;
   }
   var optionsRequest = {
      url : 'http://' + this.options.host +':' + this.options.port + path ,
      method : 'POST',
      headers : headers
   };
   var jsonStreamStringify = JSONStream.stringify();
   var postRequest = request(optionsRequest);
   jsonStreamStringify.pipe(postRequest);
   var duplex = duplexer(jsonStreamStringify,postRequest);
   return duplex ;
}
Beispiel #10
0
Shux.prototype.attach = function (id, opts) {
    if (!opts) opts = {};
    var sh = this.shells[id];
    if (!sh) return;
    
    if (opts.columns && opts.rows) {
        sh.ps.resize(Number(opts.columns), Number(opts.rows));
    }
    
    var stdin = through();
    var stdout = through();
    
    stdin.pipe(sh.ps, { end: false });
    sh.ps.pipe(stdout);
    
    process.nextTick(function () {
        var x = sh.terminal.x + 1;
        var y = sh.terminal.y + 1;
        stdout.write(Buffer.concat([
            Buffer([ 0x1b, 0x63 ]),
            render(sh.terminal.displayBuffer),
            Buffer([ 0x1b, 0x5b ]),
            Buffer(y + ';' + x + 'f')
        ]));
    });
    
    var dup = duplexer(stdin, stdout);
    sh.ps.on('end', dup.emit.bind(dup, 'end'));
    dup.id = id;
    
    this.emit('attach', id);
    stdin.on('end', this.emit.bind(this, 'detach', id));
    return dup;
};
// Transforms a raw stream into an
// object duplex stream
function toObjectDuplex(stream) {

  stream.setEncoding('utf8');

  //// Write Stream (Server -> Client)

  // Create a write stream that accepts objects
  // and spits out JSON, newline separated
  var objectWriteStream = JSONStream.stringify();

  // Pipe the stream to the client
  objectWriteStream.pipe(stream);


  //// Read Stream (Client -> Server)

  // Create a read stream that parses JSON
  // and spits out objects
  var objectReadStream = JSONStream.parse([true]);

  // Pipe the client raw data into the json parser
  stream.pipe(objectReadStream);

  /// Smush together the write and read streams into
  /// one duplex stream
  var duplexStream = duplexer(objectWriteStream, objectReadStream);
  
  return duplexStream;
}
Beispiel #12
0
function hyperquest (uri, opts, cb, extra) {
    if (typeof uri === 'object') {
        cb = opts;
        opts = uri;
        uri = undefined;
    }
    if (typeof opts === 'function') {
      cb = opts;
      opts = undefined;
    }
    if (!opts) opts = {};
    if (uri !== undefined) opts.uri = uri;
    if (extra) opts.method = extra.method;
    
    var req = new Req(opts);
    var ws = req.duplex && through();
    if (ws) ws.pause();
    var rs = through();
    
    var dup = req.duplex ? duplexer(ws, rs) : rs;
    if (!req.duplex) {
        rs.writable = false;
    }
    dup.request = req;
    dup.setHeader = bind(req, req.setHeader);
    dup.setLocation = bind(req, req.setLocation);
    
    var closed = false;
    dup.on('close', function () { closed = true });
    
    process.nextTick(function () {
        if (closed) return;
        dup.on('close', function () { r.destroy() });
        
        var r = req._send();
        r.on('error', bind(dup, dup.emit, 'error'));
        
        r.on('response', function (res) {
            dup.response = res;
            dup.emit('response', res);
            if (req.duplex) res.pipe(rs)
            else {
                res.on('data', function (buf) { rs.queue(buf) });
                res.on('end', function () { rs.queue(null) });
            }
        });
        
        if (req.duplex) {
            ws.pipe(r);
            ws.resume();
        }
        else r.end();
    });
    
    if (cb) {
        dup.on('error', cb);
        dup.on('response', bind(dup, cb, null));
    }
    return dup;
}
Beispiel #13
0
module.exports = function(cmd, args){
	//spawn the process
	//return a single stream joining together stdin and stdout
	var child = spawn(cmd, args);
	return duplex(child.stdin, child.stdout);

}
Beispiel #14
0
store.prototype.createWriteStream = function (key, opts) {
  if (!opts) opts = {};

  var input = through(function (chunk, cb) {
    this.queue({
      key : key + ' ' + timestamp(),
      value : chunk
    });
  });

  var ws = this.db.createWriteStream();
  var dpl = duplexer(input, input.pipe(ws));

  if (typeof opts.capped != 'undefined') {
    var capped = cap(this.db, key, opts.capped);
    ws.on('end', capped.end.bind(capped));
  }

  // append
  if (!opts.append) {
    input.pause();
    this.delete(key, function (err) {
      if (err) dpl.emit('error', err);
      input.resume();
    });
  }

  return dpl;
}
Beispiel #15
0
Store.prototype.createWriteStream = function (key, opts) {
  if (!opts) opts = {};

  var index = this._getIndex(opts.index, key);
  var input = through(function (chunk) {
    this.queue({
      key: index.newKey(),
      value: chunk
    });
  }).pause();
  var ws = this.db.createWriteStream();

  var dpl = duplexer(input, ws);
  input.pipe(ws);

  if (typeof opts.capped != 'undefined') {
    var capped = cap(this.db, key, opts.capped);
    ws.on('end', capped.end.bind(capped));
  }

  if (opts.append) {
    if (index.initialize) index.initialize(ready);
    else ready();
  } else {
    this.reset(key, ready);
  }

  function ready (err) {
    if (err) dpl.emit('error', err);
    input.resume();
  }

  return dpl;
}
Beispiel #16
0
function createSimulator(interval, stepsPerMM) {
  interval = interval || 0.1;
  stepsPerMM = stepsPerMM || 250;

  var sim_process = child.spawn(path.join(dir, 'grbl_sim.exe'), [interval]);

  sim_process.on('open', function() {
    [0, 1, 2].forEach(function(i) {
      sim_process.stdin.write('$' + i + '=' + stepsPerMM + '\r\n');
    });
  });

  sim_process.stdout.pipe(process.stdout);

  return duplexer(
    sim_process.stdin,
    sim_process.stderr.pipe(split()).pipe(through(function(d) {
      d = d.trim();

      var parts = d.split(', ');

      if (d[0] !== '#' && parts.length) {

        var obj = {
          time : parseFloat(parts[0]),
          x : parseInt(parts[1]) / stepsPerMM,
          y : parseInt(parts[2]) / stepsPerMM,
          z : parseInt(parts[3]) / stepsPerMM
        };
        this.push(JSON.stringify(obj) + '\n');
      }
    })));

  return stream;
};
Beispiel #17
0
module.exports = function () {
  var input = new Writable({objectMode: true})
  var output = new PassThrough()
  var table
  var first = true
  input._write = function (obj, encoding, cb) {
    var keys = Object.keys(obj).sort()
    if(first) {
      first = false
      table = createTable(keys)
      table.pipe(output)  
    }
    table.write(obj)
    cb()
  }
  input.on('finish', function () {
    if(table) table.end()
    else {
      table = createTable(['[empty]'])
      table.write({empty: ''})
      table.pipe(output)
    }
  })
  return duplexer(input, output)
}
Beispiel #18
0
var populate = function () {
  var splitter = split();
  var input = this.input;
  var rowTemplate = this.rowTemplate;
  var value, re, i;
  var replacer = through(function (data) {
    var matches = data.match(/%[a-zA-Z0-9_]+%/g);
    _.each(matches, function (match) {
      if(match) {
        var regexp = new RegExp(match, 'g');
        var key = match.substr(1, match.length - 2).toLowerCase();
        if(_.isObject(input[key])) {
          data = data.replace(regexp, '€ ' + Number(parseFloat(input[key].value)).toFixed(2));
        } else {
          if(input[key]) {
            data = data.replace(regexp, input[key]);
          } else {
            data = data.replace(regexp, '');
          }
        }
      }
    });
    var itemsMatch = data.match(/@[a-zA-Z0-9_]+@/g);
    _.each(itemsMatch, function (match) {
      var regexp = new RegExp(match, 'g');
      data = data.replace(regexp, generateItemList(input.items, input.currencyFormat, rowTemplate));
    });
    this.queue(data + "\n");
  });

  splitter.pipe(replacer);
  return duplexer(splitter, replacer);
};
Beispiel #19
0
 arrays.forEachEmission(actions, function(action, index, done){
     var outputBuffer = new BufferedOutputStream();
     outputBuffer.halt();
     outputBuffer.setMaxListeners(20);
     // duplex copy of input stream to paused output buffer
     var stream = duplexer(
         //fork paused stream
         outputBuffer,
         //fork stream
         bufferedInputStream.pipe(through())
     );
     var doAction = function(){
         action.act(stream, req, res, function(producedOutput, isRaw){
             if( producedOutput &&
                 ((!outputStream) || outputPos > index)
             ){
                 outputStream = producedOutput;
                 outputPos = index;
                 outputRaw = !!isRaw;
                 output = outputBuffer;
                 outputAction = action;
             }
             done();
         });
     }
     if(actions.where){
         var testAction = sift(actions.where);
         if(testAction({req:req, res:res})){
             doAction();
         }//else don't
     }else doAction(); //no conditions
 }, function(){
Beispiel #20
0
exports.interimStream = function(setPipes) {
  var input = through();
  var output = through();
  var duplex = duplexer(input, output);
  setPipes(input, output);
  return duplex;
};
Beispiel #21
0
Client.prototype.createAddStream = function(options){
   var path = [this.options.path,this.options.core, this.UPDATE_JSON_HANDLER + '?' + querystring.stringify(options) +'&wt=json']
      .filter(function(element){
         return element;
      })
      .join('/');
   var headers = {
      'content-type' : 'application/json',
      'charset' : 'utf-8'
   };
   if(this.options.authorization){
      headers['authorization'] = this.options.authorization;
   }
   var protocol = this.options.secure ? 'https' : 'http';
   var optionsRequest = {
      url : protocol + '://' + this.options.host +':' + this.options.port + path ,
      method : 'POST',
      headers : headers
   };
   var jsonStreamStringify = JSONStream.stringify();
   var postRequest = request(optionsRequest);
   jsonStreamStringify.pipe(postRequest);
   var duplex = duplexer(jsonStreamStringify,postRequest);
   return duplex ;
}
var ignoreIncoming = function (outgoingStream) {
  var incomingStream = map(function (data, callback) {
    callback();
  });
  // the incoming stream is not connected to the outgoing stream
  return duplex(incomingStream, outgoingStream);
};
Beispiel #23
0
module.exports = function (cmd, args) {
    var proc = spawn(cmd, args);
    //debug
    proc.stdout.on('data', function(data) {
        console.log(data.toString());
    });
    return dup(proc.stdin, proc.stdout);
};
Beispiel #24
0
module.exports = function(obj, info){
  var readable = new ReadStream(obj, info);
  var writable = new WriteStream(obj);
  writable.on('info', function(){
    readable.prepare();
  });
  return duplex(writable, readable);
};
module.exports = function (counter) {
  var count = {};
  return duplexer(through(function write (row) {
    count[row.country] = (count[row.country] || 0) + 1;
  }, function end() {
    counter.setCounts(count)
  }), counter);
};
function ast() {
  var tokens = tokenizer()
    , parse = parser()

  tokens.pipe(parse)

  return duplex(tokens, parse)
}
Beispiel #27
0
module.exports = function (run) {
  var outputA = through()
    , outputB = through()
    , inputA  = through().pause()
    , inputB  = through().pause()
    , portA = 1024 + Math.floor(Math.random() * 64511)
    , portB = portA+1
    , count   = 0
    , iv

  function error (url, out, err) {
    out.write('Error connecting to ' + url + ': ' + err.message)
    out.end()
  }

  setTimeout(function () {
    inputA.pipe(hyperquest.post('http://localhost:' + portA)
      .on('error', error.bind(null, 'http://localhost:' + portA, outputA)))
        .pipe(outputA)
    if (!run) {
      inputB.pipe(hyperquest.post('http://localhost:' + portB)
        .on('error', error.bind(null, 'http://localhost:' + portB, outputB)))
          .pipe(outputB)
    }
  }, 500)

  iv = setInterval(function () {
    var w = words[count].trim() + '\n'
    inputA.write(w)
    inputB.write(w)

    if (++count == words.length) {
      clearInterval(iv)
      inputA.end()
      inputB.end()
    }
  }, 50)

  return {
      submissionArgs : [portA]
    , solutionArgs : [portB]
    , a: duplexer(inputA, outputA)
    , b: duplexer(inputB, outputB)
  }
}
Beispiel #28
0
module.exports = function (opts) {
    if (!opts) opts = {};
    var parser = opts.raw ? through() : JSONStream.parse([ true ]);
    var output = through(write, end);
    parser.pipe(output);
    
    var first = true;
    var entries = [];
    var order = []; 
    
    var lineno = 1 + newlinesIn(prelude);
    var sourcemap;

    return duplexer(parser, output);
    
    function write (row) {
        if (first) this.queue((opts.prelude || prelude) + '({');
        
        if (row.sourceFile) { 
            sourcemap = sourcemap || combineSourceMap.create();
            sourcemap.addFile(
                { sourceFile: row.sourceFile, source: row.source },
                { line: lineno }
            );
        }
        
        var wrappedSource = [
            (first ? '' : ','),
            JSON.stringify(row.id),
            ':[',
            'function(require,module,exports){\n',
            combineSourceMap.removeComments(row.source),
            '\n},',
            JSON.stringify(row.deps || {}),
            ']'
        ].join('');

        this.queue(wrappedSource);
        lineno += newlinesIn(wrappedSource);
        
        first = false;
        if (row.entry && row.order !== undefined) {
            entries[row.order] = row.id;
        }
        else if (row.entry) entries.push(row.id);
    }
    
    function end () {
        if (first) this.queue(prelude + '({');
        entries = entries.filter(function (x) { return x !== undefined });
        
        this.queue('},{},' + JSON.stringify(entries) + ')');
        if (sourcemap) this.queue('\n' + sourcemap.comment());

        this.queue(null);
    }
};
Beispiel #29
0
module.exports = function() {
  var tap = parser()
  var out = through()
  var stream = duplexer(tap, out)

  function output(str) {
    out.push('  ' + str)
    out.push('\n')
  }

  function format(total, time) {
    var word = (total > 1) ? 'tests' : 'test'
    return total + ' ' + word + ' complete (' + time + ')'
  }

  var timer = hirestime()
  var errors = []
  var current = null

  tap.on('comment', function(res) {
    current = '\n' + '  ' + res
  })

  tap.on('assert', function(res) {
    var assert = current + ' ' + res.name
    if (!res.ok) errors.push(chalk.white(assert))
  })

  tap.on('extra', function(res) {
    if (res === '') return
    if (res.indexOf('---') === 0) {
      errors.push(chalk.gray(res))
    } else {
      output(chalk.gray(res))
    }
  })

  tap.on('results', function(res) {
    var count = res.asserts.length
    var time = prettyms(timer())
    out.push('\n')

    if (errors.length) {
      output(chalk.red(format(count, time)))
      errors.forEach(function(error) {
        output(error)
      })
    } else {
      output(chalk.green(format(count, time)))
    }

    out.push('\n')
  })

  stream.errors = errors
  return stream
}
module.exports = function(counter) {
    var counts = {};
    var input = through(function(data) {
        counts[data.country] = (counts[data.country] || 0) + 1;
    }, function end() {
        counter.setCounts(counts);
    });
    return duplex(input, counter);
};