A single log event stream.
@constructor
@param {Object} options
349571
function LogStream(options) {
        /**
         * @const
         * @type {string} */
        var _traceCode = options.trace ? (Math.random() + Math.PI).toString(36).substring(2, 10) : null;
        /** @type {string} */
        var _pageInfo = options.page_info;
        /** @type {string} */
        var _token = options.token;
        /** @type {boolean} */
        var _print = options.print;
        /** @type {boolean} */
        var _noFormat = options.no_format;
        /** @type {boolean} */
        var _SSL = function() {
            if (typeof XDomainRequest === "undefined") {
                return options.ssl;
            }
            // If we're relying on XDomainRequest, we
            // must adhere to the page's encryption scheme.
            return window.location.protocol === "https:" ? true : false;
        }();
        /** @type {string} */
        var _endpoint;
        if (window.LEENDPOINT) {
            _endpoint = window.LEENDPOINT;
        } else if (_noFormat) {
            _endpoint = "localhost:8080/noformat";
        }
        else {
            _endpoint = "localhost:8080/v1";
        }
        _endpoint = (_SSL ? "https://" : "http://") + _endpoint + "/logs/" + _token;

        /**
         * Flag to prevent further invocations on network err
         ** @type {boolean} */
        var _shouldCall = true;
        /** @type {Array.<string>} */
        var _backlog = [];
        /** @type {boolean} */
        var _active = false;
        /** @type {boolean} */
        var _sentPageInfo = false;

        if (options.catchall) {
            var oldHandler = window.onerror;
            var newHandler = function(msg, url, line) {
                _rawLog({error: msg, line: line, location: url}).level('ERROR').send();
                if (oldHandler) {
                    return oldHandler(msg, url, line);
                } else {
                    return false;
                }
            };
            window.onerror = newHandler;
        }

        var _agentInfo = function() {
            var nav = window.navigator || {doNotTrack: undefined};
            var screen = window.screen || {};
            var location = window.location || {};

            return {
              url: location.pathname,
              referrer: document.referrer,
              screen: {
                width: screen.width,
                height: screen.height
              },
              window: {
                width: window.innerWidth,
                height: window.innerHeight
              },
              browser: {
                name: nav.appName,
                user_agent: nav.userAgent,
                version: nav.appVersion,
                cookie_enabled: nav.cookieEnabled,
                do_not_track: nav.doNotTrack
              },
              platform: nav.platform
            };
        };

        var _getEvent = function() {
            var raw = null;
            var args = Array.prototype.slice.call(arguments);
            if (args.length === 0) {
                throw new Error("No arguments!");
            } else if (args.length === 1) {
                raw = args[0];
            } else {
                // Handle a variadic overload,
                // e.g. _rawLog("some text ", x, " ...", 1);
              raw = args;
            }
            return raw;
        };

        // Single arg stops the compiler arity warning
        var _rawLog = function(msg) {
            var event = _getEvent.apply(this, arguments);

            var data = {event: event};

            // Add agent info if required
            if (_pageInfo !== 'never') {
                if (!_sentPageInfo || _pageInfo === 'per-entry') {
                    _sentPageInfo = true;
                    if (typeof event.screen === "undefined" &&
                        typeof event.browser === "undefined")
                      _rawLog(_agentInfo()).level('PAGE').send();
                }
            }

            if (_traceCode) {
                data.trace = _traceCode;
            }

            return {level: function(l) {
                // Don't log PAGE events to console
                // PAGE events are generated for the agentInfo function
                    if (_print && typeof console !== "undefined" && l !== 'PAGE') {
                      var serialized = null;
                      if (typeof XDomainRequest !== "undefined") {
                        // We're using IE8/9
                        serialized = data.trace + ' ' + data.event;
                      }
                      try {
                        console[l.toLowerCase()].call(console, (serialized || data));
                      } catch (ex) {
                        // IE compat fix
                        console.log((serialized || data));
                      }
                    }
                    data.level = l;

                    return {send: function() {
                        var cache = [];
                        var serialized = JSON.stringify(data, function(key, value) {

                              if (typeof value === "undefined") {
                                return "undefined";
                              } else if (typeof value === "object" && value !== null) {
                                if (_indexOf(cache, value) !== -1) {
                                  // We've seen this object before;
                                  // return a placeholder instead to prevent
                                  // cycles
                                  return "<?>";
                                }
                                cache.push(value);
                              }
                          return value;
                        });

                            if (_active) {
                                _backlog.push(serialized);
                            } else {
                                _apiCall(_token, serialized);
                            }
                        }};
                }};
        };

        /** @expose */
        this.log = _rawLog;

        var _apiCall = function(token, data) {
            _active = true;

            var request = _getAjaxObject();

            if (_shouldCall) {
                if (request.constructor === XMLHttpRequest) {
                    // Currently we don't support fine-grained error
                    // handling in older versions of IE
                    request.onreadystatechange = function() {
                    if (request.readyState === 4) {
                        // Handle any errors
                        if (request.status >= 400) {
                            console.error("Couldn't submit events.");
                            if (request.status === 410) {
                                // This API version has been phased out
                                console.warn("This version of le_js is no longer supported!");
                            }
                        } else {
                            if (request.status === 301) {
                                // Server issued a deprecation warning
                                console.warn("This version of le_js is deprecated! Consider upgrading.");
                            }
                            if (_backlog.length > 0) {
                                // Submit the next event in the backlog
                                _apiCall(token, _backlog.shift());
                            } else {
                                _active = false;
                            }
                        }
                    }

                    };
                } else {
                  request.onload = function() {
                    if (_backlog.length > 0) {
                      // Submit the next event in the backlog
                      _apiCall(token, _backlog.shift());
                    } else {
                      _active = false;
                    }
                  };
                }

                request.open("POST", _endpoint, true);
                if (request.constructor === XMLHttpRequest) {
                    request.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
                    request.setRequestHeader('Content-type', 'application/json');
                }
                
                if (request.overrideMimeType) {
                    request.overrideMimeType('text');
                }

                request.send(data);
            }
        };
    }
593294
function Logger(options) {
        var logger;

        // Default values
        var dict = {
            ssl: true,
            catchall: false,
            trace: true,
            page_info: 'never',
            print: false,
            endpoint: null,
            token: null
        };

        if (typeof options === "object")
            for (var k in options)
                dict[k] = options[k];
        else
            throw new Error("Invalid parameters for createLogStream()");

        if (dict.token === null) {
            throw new Error("Token not present.");
        } else {
            logger = new LogStream(dict);
        }

        var _log = function(msg) {
            if (logger) {
                return logger.log.apply(this, arguments);
            } else
                throw new Error("You must call LE.init(...) first.");
        };

         // The public interface
        return {
            log: function() {
                _log.apply(this, arguments).level('LOG').send();
            },
            warn: function() {
                _log.apply(this, arguments).level('WARN').send();
            },
            error: function() {
                _log.apply(this, arguments).level('ERROR').send();
            },
            info: function() {
                _log.apply(this, arguments).level('INFO').send();
            }
        };
    }
507930
function Logger(config) {
    var self    = this;
    var config  = config || {};
    var options = config.options || {};
    var debug   = options.debug || false;
    var dev     = options.dev || false;
    var logging = config.logging || {};

    details = options.debugDetails || false;
    ignored = options.debugIgnore || [];

    if (typeof logging !== 'object') { logging = {}; }

    var enabled = typeof logging.enabled !== 'undefined' ? logging.enabled : false;
    var rewrite = typeof logging.rewrite !== 'undefined' ? logging.rewrite : true;
    var chat    = typeof logging.chat !== 'undefined' ? logging.chat : false;

    timestamp = typeof logging.timestamp !== 'undefined' ? logging.timestamp : true;

    this.options = {
        stream: process.stdout,
        wstream: null,
        level: 'raw'
    };

    if (debug && details) { this.options.level = 'chat'; }
    if (dev) { this.options.level = 'dev'; }
    if (!debug) { this.options.level = 'crash'; }

    if (enabled) {
        ensureExists('./logs', function(err) {
            if (!err) {
                var flag = rewrite ? 'w' : 'a';
                var stream = filesystem.createWriteStream('./logs/status.log', { flags: flag });
                self.options.wstream = stream;
                if (chat) { self.options.level = 'chat'; }
            }
        });
    }

    this.templates = {
        chat:  '[:timestamp] \x1b[35mchat\x1b[39m   - :message',
        action:  '[:timestamp] \x1b[35maction\x1b[39m - :message',
        dev:   '\x1b[90m  :message\x1b[39m',
        raw:   '[:timestamp] \x1b[36mraw\x1b[39m    - :message',
        event: '[:timestamp] \x1b[32mevent\x1b[39m  - :message',
        info:  '[:timestamp] \x1b[33minfo\x1b[39m   - :message',
        error: '[:timestamp] \x1b[31merror\x1b[39m  - :message',
        crash: '[:timestamp] \x1b[31merror\x1b[39m  - :message',
        inspect: true
    };
}
697992
function Logger(options) {
  if (!(this instanceof Logger))
    return new Logger(options);

  this.level = Logger.levels.NONE;
  this.colors = Logger.HAS_TTY;
  this.console = true;
  this.shrink = true;
  this.closed = true;
  this.closing = false;
  this.filename = null;
  this.stream = null;
  this.contexts = Object.create(null);
  this.locker = new Lock();

  if (options)
    this.set(options);
}
150149
function ReadableUSBStream(endpoint, options)
{
	stream.Readable.call(this, options);

	this.endpoint = endpoint;
	this.endpoint.addListener('data', this.onData.bind(this));
	this.endpoint.addListener('error', this.onError.bind(this));
	this.endpoint.addListener('end', this.onEnd.bind(this));

	this.paused = true;
}
429603
function(options) {
    if (!options) {
      options = {};
    }

    if (options.log) {
      if (!_.isFunction(options.log)) {
        throw new Error('setLogOptions expects the log key in the options parameter to be a function');
      }
    } else {
      // if no log function was passed set it to a default no op function.
      options.log = function() {};
    }

    if (options.level) {
      var level = options.level;
      if (level < 0 || level > 3) {
        throw new Error('setLogOptions expects the level key to be in the range 0 to 3 inclusive');
      }
    } else {
      options.level = this.LOGGING_LEVEL.ERROR;
    }

    if (options.loggingWithPII != true) {
      options.loggingWithPII = false;
    }
    
    this.LogOptions = options;
  }
417502
function OSMStream(options) {
  if (!(this instanceof OSMStream)) return new OSMStream(options);

  Transform.call(this, options);

  var primaryElements = ['node', 'way', 'relation']; // emit-ables
  var subElementName = ['tag', 'nd', 'member'];

  // size of bytes read from source so far
  this.bytesRead = 0;
  // size of bytes written to stream so far
  this.bytesWritten = 0;

  // initialize parser and its event handlers
  this._parser = new expat.Parser();

  this._parser.on('pipe', (function onParserPipe(src) {
    logger('_parser received pipe from ', src.path || '<unknown pipe>');
  }).bind(this));

  this._parser.on('startElement', (function onParserStartElement(name, attrs) {
    var funcname = ['__parse_', name].join('');
    if ((primaryElements.indexOf(name) > -1 && (OSMStream.prototype[funcname])) ||
      (subElementName.indexOf(name) > -1 && this._currentElement !== null && (OSMStream.prototype[funcname]))) {
      OSMStream.prototype[funcname].call(this, attrs);
    }
  }).bind(this));

  this._parser.on('endElement', (function onParserEndElement(name) {
    if ((primaryElements.indexOf(name) < 0)) return;

    var clone = extend({}, this._currentElement);
    this._currentElement = null;

    var pushData = function pushData(data) {
      if (!data) return;

      if (this.listeners('writeable').length > 0) {
        this.emit('writeable', data, (function onWriteable(data) {
          this.__push(data);
        }).bind(this));
      } else {
        this.__push(data);
      }

    }.bind(this);

    if (this.listeners(name).length > 0) {
      this.emit(name, clone, (function onElement(data) {
        pushData(data);
      }.bind(this)));
    } else {
      pushData(clone);
    }
  }).bind(this));

  this._parser.on('error', (function onParserError(err) {
    this.emit('error', err);
  }).bind(this));

  this._parser.on('end', (function onParserEnd() {
  }).bind(this));

  this.on('pipe', (function onPipe(src) {
    if (src === this._parser) return;
    // attaching stream pipe to parser
    logger('Received pipe from ', src.toString(), ', attaching pipe to _parser');
    src.pipe(this._parser);
    this._parser.pipe(this);
  }).bind(this));

}
649680
function Startline(options) {

  event.call(this);
  var self = this; // closure
  var temp = '';
  this.options = options;
  this.head = 0;
  this.tail = 0;
  this.line = 0;
  this._stream = null;

  if (options.rc4 || options.autokey) { // cipher
    var cipher;
    this._stream = interfac(this.options, options.start, options.end);
    if (options.rc4) {
      cipher = require('arc4')('arc4', String(options.rc4), options.lodash);
      this._stream.on('data', function(callbacks) {

        var callback = cipher.decodeBuffer(callbacks).toString();
        for (var i = 0, ii = callback.length; i < ii; ++i) {
          if (callback[i] === eol) {
            self.tail = self.head + self.line;
            self.head = self.tail + temp.length;
            self.emit('line', temp);
            self.line = 1;
            temp = '';
          } else {
            temp += callback[i];
          }
        }
        if (temp.length > 0) {
          self.tail = self.head + self.line;
          self.head = self.tail + temp.length;
          self.emit('line', temp);
          self.line = 1;
        }
        return;
      });

    } else {
      cipher = require('autokey')(String(options.autokey), options.lodash);
      this._stream.on('data', function(callbacks) {

        var callback = cipher.decodeBuffer(callbacks).toString();
        for (var i = 0, ii = callback.length; i < ii; ++i) {
          if (callback[i] === eol) {
            self.tail = self.head + self.line;
            self.head = self.tail + temp.length;
            self.emit('line', temp);
            self.line = 1;
            temp = '';
          } else {
            temp += callback[i];
          }
        }
        if (temp.length > 0) {
          self.tail = self.head + self.line;
          self.head = self.tail + temp.length;
          self.emit('line', temp);
          self.line = 1;
        }
        return;
      });
    }

  } else if (options.end >= 0) { // no cipher, EOF
    this._stream = interfac(this.options, options.start, options.end);
    this._stream.on('data', function(callbacks) {

      var callback = callbacks.toString();
      for (var i = 0, ii = callback.length; i < ii; ++i) {
        if (callback[i] === eol) {
          self.tail = self.head + self.line;
          self.head = self.tail + temp.length;
          self.emit('line', temp);
          self.line = 1;
          temp = '';
        } else {
          temp += callback[i];
        }
      }
      if (temp.length > 0) {
        self.tail = self.head + self.line;
        self.head = self.tail + temp.length;
        self.emit('line', temp);
        self.line = 1;
      }
      return;
    });

  } else { // file
    this._stream = readlin(this.options, options.start, options.end);
    this._stream.on('line', function(callback) {

      self.tail = self.head + self.line;
      self.head = self.tail + callback.length;
      self.emit('line', callback);
      self.line = 1;
      return;
    });
  }

  // standard events
  this._stream.on('pause', function() {

    return self.emit('pause');
  }).on('resume', function() {

    return self.emit('resume');
  }).on('open', function(fd) {

    return self.emit('open', fd);
  }).on('close', function() {

    return self.emit('close');
  }).on('end', function() {

    return self.emit('end');
  }).on('error', function(err) {

    return self.emit('error', err);
  });
}
295389
function LogStream(jenkins, opts) {
  var self = this;

  events.EventEmitter.call(self);

  self._jenkins = jenkins;

  opts = opts || {};

  self._delay = opts.delay || 1000;
  delete opts.delay;

  self._opts = {};
  for (var key in opts) {
    if (opts.hasOwnProperty(key)) {
      self._opts[key] = opts[key];
    }
  }
  self._opts.meta = true;

  process.nextTick(function() { self._run(); });
}
1122658
function create(options) {
  options = options || {};

  var scrollParent = (options.scrollTarget && options.scrollTarget.parentNode) || window;

  var oldScrollY;
  var scrollDirty = true;
  var scrollEventsStream = Stream.createFromEvents(scrollParent, 'scroll');

  Stream.onValue(scrollEventsStream, function onScrollSetDirtyBit_() {
    scrollDirty = true;
  });

  var rAF = Stream.createFromRAF();

  var didChangeOnRAFStream = Stream.filter(function filterDirtyFramesFromRAF_() {
    if (!scrollDirty) { return false; }
    scrollDirty = false;

    var newScrollY = DOM.documentScrollY(scrollParent);

    if (oldScrollY !== newScrollY) {
      oldScrollY = newScrollY;
      return true;
    }

    return false;
  }, rAF);

  // It's going to space, will you just give it a second!
  Util.defer(Util.partial(Events.dispatchEvent, scrollParent, 'scroll'), 10);

  return Stream.map(function getWindowPosition_() {
    return oldScrollY;
  }, didChangeOnRAFStream);
}
660199
function WritableUSBStream(endpoint, options)
{
	options = options || {};
	options.decodeStrings = false;
	stream.Writable.call(this, options);

	this.paused = false;

	this.endpoint = endpoint;
	this.endpoint.addListener('drain', this.onDrain.bind(this));
	this.endpoint.addListener('error', this.onError.bind(this));
	this.endpoint.addListener('end', this.onEnd.bind(this));

	this.endpoint.startStream(3, 64);
}
516805
function BufferedStream(opts) {
  opts = opts || {}

  Stream.call(this)

  // up to subclasses to decide what kind of stream we are
  this.writable = false
  this.readable = false

  this.buffers = []
  this.paused = false
  this.concat = !!opts.concat //boolean indicating if we should emit separate buffers or concat buffers into one 'emit' event
}
138128
function(callback) {
    const contentStream = new stream.Writable();
    const data = [];

    contentStream._write = function(chunk) {
      callback(null, chunk.toString());
    };


    // here we can add the options in the future:
    // (options, context, gitRawCommitsOpts, parserOpts, writerOpts);
    const options = {
      preset: program.changelogpreset,
      releaseCount: program.releasecount,
    };
    changelog(options)
    // Use through() to handle multiple chunks which could be returned from changelog()
        .pipe(through({
          objectMode: true,
        }, function(chunk, enc, cb) {
          try {
            data.push(chunk);
          } catch (err) {
            setImmediate(function() {
              throw err;
            });
          }

          cb();
        }, function(cb) {
        // This function is called once ALL the object-chunks have been processed.
          data.push(null);

          cb(null, data.join('')); // Pass the data to the next stream processor
        }))
        .pipe(contentStream);
  }
765877
function Stream (options) {

  //check options
  if (!options) {

    throw new Error('Initialization error: missing transport options')
  }

  this._initDefaults() //Initialize default params
  this._updateParams(options)
  this._initTransport(options.transport)

  var self = this

  self.on('error', nop)

  this.subscriptions = []

  this.getSubscriptions = function () {

    return this.subscriptions
  }

  this.addSubscription = function (args, callback) {

    var c = new Subscription(args, callback, this)
    this.subscriptions[c.eid] = c
    return c
  }

  this.getSubscription = function (channel, resource) {

    if (this.subscriptions[channel + this.seperator + resource]) {
      return this.subscriptions[channel + this.seperator + resource]
    }
    return null
  }

  this.getAnySubscription = function (channel, resource) {

    if (this.subscriptions[channel + this.seperator + resource]) {
      return this.subscriptions[channel + this.seperator + resource]
    } else if (this.subscriptions[channel + this.seperator + this.wildcard]) {
      return this.subscriptions[channel + this.seperator + this.wildcard]
    } else {
      return null
    }
  }

  this.removeSubscription = function (channel, resource) {

    resource = resource || this.wildcard
    if (this.subscriptions[channel + this.seperator + resource]) {
      var retval = this.subscriptions[channel + this.seperator + resource]
      delete this.subscriptions[channel + this.seperator + resource]
      return retval
    }

    return null
  }

  this.getSubscriptionWithPermission = function (channel, resource, read, write) {

    var Subscription = this.subscriptions[channel + this.seperator + resource]
    var match = false

    if (Subscription) {

      match = true

      if (read) {
        match = Subscription.hasReadPermission()
      }

      if (write) {
        match = Subscription.hasWritePermission()
      }

      if (match) {
        return Subscription
      }
    } else {

      Subscription = this.subscriptions[channel + this.seperator + this.wildcard]

      if (Subscription) {

        match = true

        if (read) {
          match = Subscription.hasReadPermission()
        }

        if (write) {
          match = Subscription.hasWritePermission()
        }

        if (match) {
          return Subscription
        }
      }
    }

    return null
  }

  this.connection = new this.ConnectionFactory(this)
  this.connect()
}
1314092
function stream(out, err) {
  if(!err) err = out;

  if(typeof out === 'string') {
    this._out = fs.createWriteStream(out);
  }else{
    this._out = out;
  }

  if(typeof err === 'string') {
    this._err = fs.createWriteStream(err);
  }else{
    this._err = err;
  }

  if((!(this._out instanceof Writable)
      && this._out !== process.stdout)
    || (!(this._err instanceof Writable)
      && this._err !== process.stderr)) {
    throw new Error('invalid log stream');
  }
}
603508
function(eventName, options) {
    if (!this.__eventListeners) {
      this.__eventListeners = { }
    }
    var listenersForEvent = this.__eventListeners[eventName];
    if (!listenersForEvent) return;
    for (var i = 0, len = listenersForEvent.length; i < len; i++) {
      // avoiding try/catch for perf. reasons
      listenersForEvent[i](options || { });
    }
  }
715464
function IOStream(options) {
  if (!(this instanceof IOStream)) {
    return new IOStream(options);
  }

  IOStream.super_.call(this, options);

  this.options = options;
  this.id = uuid();
  this.socket = null;

  // Buffers
  this.pushBuffer = [];
  this.writeBuffer = [];

  // Op states
  this._readable = false;
  this._writable = false;
  this.destroyed = false;

  // default to *not* allowing half open sockets
  this.allowHalfOpen = options && options.allowHalfOpen || false;

  this.on('finish', this._onfinish);
  this.on('end', this._onend);
  this.on('error', this._onerror);
}