(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.highland = f()}})(function(){var define,module,exports;return (function(){function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o { req: IncomingMessage, res: ServerResponse } * * // creating a stream from events with a mapping function * _('request', httpServer, function(req, res) { * return res; * }).each(handleEvent); * //=> IncomingMessage * * // from a Promise object * var foo = _($.getJSON('/api/foo')); * * // from an iterator * var map = new Map([['a', 1], ['b', 2]]); * var bar = _(map.values()).toArray(_.log); * //=> [1, 2] * * // from an iterable * var set = new Set([1, 2, 2, 3, 4]); * var bar = _(set).toArray(_.log); * //=> [1, 2, 3, 4] * * // from an async iterator * async function* generator() { * yield 1; * yield 2; * } * var stream = _(generator()).toArray(_.log); * //=> [1, 2] * * // from an async iterable * var asyncIterable = { * [Symbol.asyncIterable]: generator * }; * var stream = _(asyncIterable).toArray(_.log); * //=> [1, 2] */ /*eslint-disable no-multi-spaces */ var _ = exports = module.exports = __(Stream); function __(StreamCtor) { return function (/*optional*/xs, /*optional*/secondArg, /*optional*/ mappingHint) { /*eslint-enable no-multi-spaces */ var s = null; if (_.isUndefined(xs)) { // nothing else to do s = new StreamCtor(); s.writable = true; } else if (_.isStream(xs)) { if (!(xs instanceof StreamCtor)) { // different subclass or version var ret = new StreamCtor(); xs.on('error', bindContext(ret.write, ret)); s = xs.pipe(ret); } else { s = xs; } } else if (_.isArray(xs)) { s = new StreamCtor(); s._outgoing.enqueueAll(xs); s._outgoing.enqueue(_.nil); } else if (_.isFunction(xs)) { s = new StreamCtor(xs); } else if (_.isObject(xs)) { // check to see if we have a readable stream if (_.isFunction(xs.on) && _.isFunction(xs.pipe)) { var onFinish = _.isFunction(secondArg) ? secondArg : defaultReadableOnFinish; s = new StreamCtor(); s.writable = true; pipeReadable(xs, onFinish, s); // s has to be writable so that the pipe works // return a non-writable stream return s.map(function (x) { return x; }); } else if (_.isFunction(xs.then)) { // probably a promise s = promiseStream(StreamCtor, xs); } // must check iterators and iterables in this order // because generators are both iterators and iterables: // their Symbol.iterator method returns the `this` object // and an infinite loop would result otherwise else if (_.isFunction(xs.next)) { // probably an iterator. This handle both sync and async iterators. return iteratorStream(StreamCtor, xs); } else if (!_.isUndefined(_global.Symbol) && xs[_global.Symbol.iterator]) { // probably an iterable return iteratorStream(StreamCtor, xs[_global.Symbol.iterator]()); } else if (!_.isUndefined(_global.Symbol) && xs[_global.Symbol.asyncIterator]) { // probably an async iterable return iteratorStream(StreamCtor, xs[_global.Symbol.asyncIterator]()); } else { throw new Error( 'Object was not a stream, promise, iterator or iterable: ' + (typeof xs) ); } } else if (_.isString(xs)) { var mapper = hintMapper(mappingHint); s = new StreamCtor(); var callback_func = function () { var ctx = mapper.apply(this, arguments); s.write(ctx); }; secondArg.on(xs, callback_func); var removeMethod = secondArg.removeListener // EventEmitter || secondArg.unbind; // jQuery if (removeMethod) { s._destructors.push(function() { removeMethod.call(secondArg, xs, callback_func); }); } } else { throw new Error( 'Unexpected argument type to Stream constructor: ' + (typeof xs) ); } return s; }; } /*eslint-enable no-use-before-define */ function checkIsNumber(parameter, paramName) { if (typeof parameter != 'number') { throw new TypeError('Parameter "' + paramName + '" is not a number.'); } } function checkRange(predicate, message) { if (!predicate) { throw new RangeError(message); } } _.isUndefined = function (x) { return typeof x === 'undefined'; }; _.isFunction = isFunction; _.isObject = function (x) { return typeof x === 'object' && x !== null; }; _.isString = function (x) { return typeof x === 'string'; }; _.isArray = Array.isArray || function (x) { return Object.prototype.toString.call(x) === '[object Array]'; }; // setImmediate browser fallback if (typeof setImmediate === 'undefined') { _.setImmediate = function (fn) { setTimeout(fn, 0); }; } else { // We don't use a direct alias since some tests depend // on allowing Sinon.Js to override the global // setImmediate. _.setImmediate = function (fn) { setImmediate(fn); }; } /** * The end of stream marker. This is sent along the data channel of a Stream * to tell consumers that the Stream has ended. See the example map code for * an example of detecting the end of a Stream. * * Note: `nil` is setup as a global where possible. This makes it convenient * to access, but more importantly lets Streams from different Highland * instances work together and detect end-of-stream properly. This is mostly * useful for NPM where you may have many different Highland versions installed. * * @id nil * @section Utils * @name _.nil * @api public * * var map = function (iter, source) { * return source.consume(function (err, val, push, next) { * if (err) { * push(err); * next(); * } * else if (val === _.nil) { * push(null, val); * } * else { * push(null, iter(val)); * next(); * } * }); * }; */ // set up a global nil object in cases where you have multiple Highland // instances installed (often via npm) var nil = _.nil = require('./nil'); /** * Transforms a function with specific arity (all arguments must be * defined) in a way that it can be called as a chain of functions until * the arguments list is saturated. * * This function is not itself curryable. * * @id curry * @name _.curry(fn, [*arguments]) * @section Functions * @param {Function} fn - the function to curry * @param args.. - any number of arguments to pre-apply to the function * @returns Function * @api public * * fn = curry(function (a, b, c) { * return a + b + c; * }); * * fn(1)(2)(3) == fn(1, 2, 3) * fn(1, 2)(3) == fn(1, 2, 3) * fn(1)(2, 3) == fn(1, 2, 3) */ _.curry = function (fn /* args... */) { var args = slice.call(arguments); return _.ncurry.apply(this, [fn.length].concat(args)); }; /** * Same as `curry` but with a specific number of arguments. This can be * useful when functions do not explicitly define all its parameters. * * This function is not itself curryable. * * @id ncurry * @name _.ncurry(n, fn, [args...]) * @section Functions * @param {Number} n - the number of arguments to wait for before apply fn * @param {Function} fn - the function to curry * @param args... - any number of arguments to pre-apply to the function * @returns Function * @api public * * fn = ncurry(3, function () { * return Array.prototype.join.call(arguments, '.'); * }); * * fn(1, 2, 3) == '1.2.3'; * fn(1, 2)(3) == '1.2.3'; * fn(1)(2)(3) == '1.2.3'; */ _.ncurry = function (n, fn /* args... */) { var largs = slice.call(arguments, 2); if (largs.length >= n) { return fn.apply(this, largs.slice(0, n)); } return _.partial.apply(this, [_.ncurry, n, fn].concat(largs)); }; /** * Partially applies the function (regardless of whether it has had curry * called on it). This will always postpone execution until at least the next * call of the partially applied function. * * @id partial * @name _.partial(fn, args...) * @section Functions * @param {Function} fn - function to partial apply * @param args... - the arguments to apply to the function * @api public * * var addAll = function () { * var args = Array.prototype.slice.call(arguments); * return foldl1(add, args); * }; * var f = partial(addAll, 1, 2); * f(3, 4) == 10 */ _.partial = function (f /* args... */) { var args = slice.call(arguments, 1); return function () { return f.apply(this, args.concat(slice.call(arguments))); }; }; /** * Evaluates the function `fn` with the argument positions swapped. Only * works with functions that accept two arguments. * * @id flip * @name _.flip(fn, [x, y]) * @section Functions * @param {Function} fn - function to flip argument application for * @param x - parameter to apply to the right hand side of f * @param y - parameter to apply to the left hand side of f * @api public * * div(2, 4) == 0.5 * flip(div, 2, 4) == 2 * flip(div)(2, 4) == 2 */ _.flip = _.curry(function (fn, x, y) { return fn(y, x); }); /** * Creates a composite function, which is the application of function1 to * the results of function2. You can pass an arbitrary number of arguments * and have them composed. This means you can't partially apply the compose * function itself. * * @id compose * @name _.compose(fn1, fn2, ...) * @section Functions * @api public * * var add1 = add(1); * var mul3 = mul(3); * * var add1mul3 = compose(mul3, add1); * add1mul3(2) == 9 */ _.compose = function (/*functions...*/) { var fns = slice.call(arguments).reverse(); return _.seq.apply(null, fns); }; /** * The reversed version of [compose](#compose). Where arguments are in the * order of application. * * @id seq * @name _.seq(fn1, fn2, ...) * @section Functions * @api public * * var add1 = add(1); * var mul3 = mul(3); * * var add1mul3 = seq(add1, mul3); * add1mul3(2) == 9 */ _.seq = function () { var fns = slice.call(arguments); return function () { if (!fns.length) { return null; } var r = fns[0].apply(this, arguments); for (var i = 1; i < fns.length; i++) { r = fns[i].call(this, r); } return r; }; }; function nop() { // Do nothing. } function defaultReadableOnFinish(readable, callback) { // It's possible that `close` is emitted *before* `end`, so we simply // cannot handle that case. See // https://github.com/caolan/highland/issues/490 for details. // pipe already pushes on end, so no need to bind to `end`. // write any errors into the stream readable.once('error', callback); return function () { readable.removeListener('error', callback); }; } function pipeReadable(xs, onFinish, stream) { var response = onFinish(xs, streamEndCb); var unbound = false; var cleanup = null; var endOnError = true; if (_.isFunction(response)) { cleanup = response; } else if (response != null) { cleanup = response.onDestroy; endOnError = !response.continueOnError; } xs.pipe(stream); stream.onDestroy(unbind); function streamEndCb(error) { if (stream._nil_pushed) { return; } if (error) { stream.write(new StreamError(error)); } if (error == null || endOnError) { unbind(); stream.end(); } } function unbind() { if (unbound) { return; } unbound = true; if (cleanup) { cleanup(); } if (xs.unpipe) { xs.unpipe(stream); } } } function newPullFunction(xs) { return function pull(cb) { xs.pull(cb); }; } function newDelegateGenerator(pull) { return function delegateGenerator(push, next) { var self = this; pull(function (err, x) { // Minor optimization to immediately call the // generator if requested. var old = self._defer_run_generator; self._defer_run_generator = true; push(err, x); if (x !== nil) { next(); } self._defer_run_generator = old; if (!old && self._run_generator_deferred) { self._runGenerator(); } }); }; } function promiseStream(StreamCtor, promise) { var nilScheduled = false; return new StreamCtor(function (push) { // We need to push asynchronously so that errors thrown from handling // these values are not caught by the promise. Also, return null so // that bluebird-based promises don't complain about handlers being // created but not returned. See // https://github.com/caolan/highland/issues/588. promise = promise.then(function (value) { nilScheduled = true; _.setImmediate(function () { push(null, value); push(null, nil); }); return null; }, function (err) { nilScheduled = true; _.setImmediate(function () { push(err); push(null, nil); }); return null; }); // Using finally also handles bluebird promise cancellation, so we do // it if we can. if (_.isFunction(promise['finally'])) { // eslint-disable-line dot-notation promise['finally'](function () { // eslint-disable-line dot-notation if (!nilScheduled) { _.setImmediate(function () { push(null, nil); }); } return null; }); } }); } function iteratorStream(StreamCtor, it) { return new StreamCtor(function (push, next) { function pushIt(iterElem) { if (iterElem.done) { if (!_.isUndefined(iterElem.value)) { // generators can return a final // value on completion using return // keyword otherwise value will be // undefined push(null, iterElem.value); } push(null, _.nil); } else { push(null, iterElem.value); next(); } } try { var iterElem = it.next(); if (_.isFunction(iterElem.then)) { iterElem .then(pushIt) .catch(function(err) { push(err); push(null, _.nil); }); } else { pushIt(iterElem); } } catch (err) { push(err); push(null, _.nil); } }); } function hintMapper(mappingHint) { var mappingHintType = (typeof mappingHint); var mapper; if (mappingHintType === 'function') { mapper = mappingHint; } else if (mappingHintType === 'number') { mapper = function () { return slice.call(arguments, 0, mappingHint); }; } else if (_.isArray(mappingHint)) { mapper = function () { var args = arguments; return mappingHint.reduce(function (ctx, hint, idx) { ctx[hint] = args[idx]; return ctx; }, {}); }; } else { mapper = function (x) { return x; }; } return mapper; } function pipeStream(src, dest, write, end, passAlongErrors) { var resume = null; if (!passAlongErrors) { src._send_events = true; } var s = src.consume(function (err, x, push, next) { var canContinue; if (err) { if (passAlongErrors) { canContinue = write.call(dest, new StreamError(err)); } else { canContinue = true; } } else if (x === nil) { end.call(dest); return; } else { canContinue = write.call(dest, x); } if (canContinue !== false) { next(); } else { resume = next; } }); dest.on('drain', onConsumerDrain); // Since we don't keep a reference to piped-to streams, // save a callback that will unbind the event handler. src.onDestroy(function () { dest.removeListener('drain', onConsumerDrain); }); dest.emit('pipe', src); // Calling resume() may cause data to be synchronously pushed. // That can cause data loss if the destination is a through stream and it // is unpaused. That is, this chain won't work correctly: // stream.pipe(unpaused).pipe(otherDest); _.setImmediate(function () { s.resume(); }); return dest; function onConsumerDrain() { if (resume) { resume(); resume = null; } } } /** * Actual Stream constructor wrapped the the main exported function */ function Stream(generator) { EventEmitter.call(this); // used to detect Highland Streams using isStream(x), this // will work even in cases where npm has installed multiple // versions, unlike an instanceof check this.__HighlandStream__ = true; this.id = ('' + Math.random()).substr(2, 6); this.paused = true; this.ended = false; // Old-style node Stream.pipe() checks for writable, and gulp checks for // readable. Discussion at https://github.com/caolan/highland/pull/438. this.readable = true; this.writable = false; this._outgoing = new Queue(); this._observers = []; this._destructors = []; this._send_events = false; this._nil_pushed = false; // Sets to true when a nil has been queued. this._explicitly_destroyed = false; // Sets to true when destroy() is called. this._request = null; this._multiplexer = null; this._consumer = null; this._generator = generator; this._generator_requested = true; this._defer_run_generator = false; this._run_generator_deferred = false; // Signals whether or not a call to write() returned false, and thus we can // drain. This is only relevant for streams constructed with _(). this._can_drain = false; var self = this; // These are defined here instead of on the prototype // because bind is super slow. this._push_fn = function (err, x) { if (x === nil) { // It's possible that next was called before the // nil, causing the generator to be deferred. This // is allowed since push can be called at any time. // We have to cancel the deferred call to preserve the // generator contract. self._run_generator_deferred = false; } // This will set _nil_pushed if necessary. self._writeOutgoing(err ? new StreamError(err) : x); }; this._next_fn = function (xs) { if (self._explicitly_destroyed) { return; } // It's possible to get into a situation where a call to next() is // scheduled asynchonously, but before it is run, destroy() is called, // usually by a downstream consumer like take(1). The call to next() // still completes, and there is nothing the original caller can do can // do. We do not want to throw in that situation. if (self._nil_pushed) { throw new Error('Cannot call next after nil'); } self._generator_requested = true; if (xs) { xs = self.create(xs); var pull = newPullFunction(xs); self._generator = newDelegateGenerator(pull); } if (!self.paused) { if (self._defer_run_generator) { self._run_generator_deferred = true; } else { _.setImmediate(function () { self._runGenerator(); }); } } }; this.on('newListener', function (ev) { if (ev === 'data') { self._send_events = true; _.setImmediate(bindContext(self.resume, self)); } else if (ev === 'end') { // this property avoids us checking the length of the // listners subscribed to each event on each _send() call self._send_events = true; } }); // TODO: write test to cover this removeListener code this.on('removeListener', function (ev) { if (ev === 'end' || ev === 'data') { var end_listeners = self.listeners('end').length; var data_listeners = self.listeners('data').length; if (end_listeners + data_listeners === 0) { // stop emitting events self._send_events = false; } } }); } inherits(Stream, EventEmitter); function _addMethod(proto, topLevel) { return function(name, f) { proto[name] = f; var n = f.length; function relevel(coerce) { return _.ncurry(n + 1, function () { var args = slice.call(arguments); var s = coerce(args.pop()); return f.apply(s, args); }); } topLevel[name] = relevel(topLevel); topLevel[name]._relevel = relevel; }; } var addMethod = _addMethod(Stream.prototype, _); function _addMethods(proto, topLevel, methods) { for (var p in methods) { if (hasOwn.call(methods, p)) { _addMethod(proto, topLevel)(p, methods[p]); } } } function _addToplevelMethod(topLevel) { return function (name, fn) { function relevel(_topLevel) { var bound = bindContext(fn, _topLevel); bound._relevel = relevel; return bound; } topLevel[name] = relevel(topLevel); }; } var addToplevelMethod = _addToplevelMethod(_); function _addToplevelMethods(topLevel, methods) { for (var p in methods) { if (hasOwn.call(methods, p)) { _addToplevelMethod(topLevel)(p, methods[p]); } } } function use(Super, originalTopLevel) { return function(methods, toplevelMethods) { function Sub() { Stream.apply(this, arguments); } inherits(Sub, Super); function topLevel() { return __(Sub).apply(null, arguments); } for (var p in originalTopLevel) { if (hasOwn.call(originalTopLevel, p)) { var fn = originalTopLevel[p]; topLevel[p] = (typeof fn._relevel === 'function') ? fn._relevel(topLevel) : fn; } } _addMethods(Sub.prototype, topLevel, methods || {}); _addToplevelMethods(topLevel, toplevelMethods || {}); topLevel.use = use(Sub, topLevel); return topLevel; }; } _.use = use(Stream, _); /** * Creates a stream that sends a single value then ends. * * @id of * @section Utils * @name _.of(x) * @param x - the value to send * @returns Stream * @api public * * _.of(1).toArray(_.log); // => [1] */ addToplevelMethod('of', function (x) { return this([x]); }); Stream['fantasy-land/of'] = Stream.of; _['fantasy-land/of'] = _.of; /** * Creates an empty stream. * * @id empty * @section Utils * @name _.empty() * @returns Stream * @api public * * _.empty().toArray(_.log); // => [] */ addToplevelMethod('empty', function () { return this([]); }); Stream['fantasy-land/empty'] = Stream.empty; _['fantasy-land/empty'] = _.empty; Stream['fantasy-land/zero'] = Stream.empty; _['fantasy-land/zero'] = _.empty; /** * Creates a stream that sends a single error then ends. * * @id fromError * @section Utils * @name _.fromError(err) * @param error - the error to send * @returns Stream * @api public * * _.fromError(new Error('Single Error')).toCallback(function (err, result) { * // err contains Error('Single Error') object * } */ addToplevelMethod('fromError', function (error) { return _(function (push) { push(error); push(null, _.nil); }); }); Stream.prototype.create = function () { return __(this.constructor).apply(null, arguments); }; Stream.prototype.createChild = function createChild(/*varargs*/) { var child = this.create.apply(this, arguments); child.onDestroy(bindContext(this.destroy, this)); return child; }; /** * Used as an Error marker when writing to a Stream's incoming buffer */ function StreamError(err) { this.__HighlandStreamError__ = true; this.error = err; } /** * Returns true if `x` is the end of stream marker. * * @id isNil * @section Utils * @name _.isNil(x) * @param x - the object to test * @api public */ _.isNil = function (x) { return x === _.nil; }; /** * Returns true if `x` is a Highland Stream. * * @id isStream * @section Utils * @name _.isStream(x) * @param x - the object to test * @returns {Boolean} * @api public * * _.isStream('foo') // => false * _.isStream(_([1,2,3])) // => true */ _.isStream = function (x) { return _.isObject(x) && !!x.__HighlandStream__; }; _._isStreamError = function (x) { return _.isObject(x) && !!x.__HighlandStreamError__; }; /** * Sends errors / data to consumers, observers and event handlers */ Stream.prototype._send = function (token) { // console.log(this.id, '_send', token, this._send_events); var err = null, x; if (_._isStreamError(token)) { err = token.error; this.readable = false; } else { x = token; } if (x === nil) { // Per https://nodejs.org/docs/v0.8.28/api/stream.html#stream_stream_readable // streams stop being readable when they end or are destroyed this.readable = false; } if (this._request) { // Allow pull to be called within the callback function. var cb = this._request; this._request = null; // If we have a request, then it was from a pull() and we need to // pause. this.pause(); cb(err, x); } // this._observers may be changed from under us, // so we keep a copy. var observers = this._observers; for (var j = 0, len2 = observers.length; j < len2; j++) { observers[j].write(token); } if (this._send_events) { if (err) { this.emit('error', err); } else if (x === nil) { this.emit('end'); } else { this.emit('data', x); } } if (x === nil) { this._onEnd(); } }; Stream.prototype._onEnd = function _onEnd() { if (this.ended) { return; } this.pause(); this.ended = true; // Don't use _removeObserver for efficiency reasons. var i, len, observer; for (i = 0, len = this._observers.length; i < len; i++) { observer = this._observers[i]; if (observer.source === this) { observer.source = null; } } for (i = 0, len = this._destructors.length; i < len; i++) { this._destructors[i].call(this); } this._outgoing.clear(); this._observers = []; this._destructors = []; this._request = null; this._multiplexer = null; this._consumer = null; this._generator = null; this._generator_requested = false; this._defer_run_generator = false; this._run_generator_deferred = false; }; /** * Pauses the stream. All Highland Streams start in the paused state. * * It is unlikely that you will need to manually call this method. * * @id pause * @section Stream Objects * @name Stream.pause() * @api public * * var xs = _(generator); * xs.pause(); */ addMethod('pause', function () { //console.log(['pause', this.id]); this.paused = true; }); /* * Emit as many buffered token as possible, but not to exceed num. * If num is null, then emit as much as possible. */ Stream.prototype._emitNext = function (num) { var emitted = 0; while ((num == null || emitted < num) && this._outgoing.length && !this.paused) { this._send(this._outgoing.dequeue()); emitted++; } }; /** * Resumes a paused Stream. This will either read from the Stream's incoming * buffer or request more data from an upstream source. Never call this method * on a stream that has been consumed (via a call to [consume](#consume) or any * other transform). * * @id resume * @section Stream Objects * @name Stream.resume() * @api public * * var xs = _(generator); * xs.resume(); */ addMethod('resume', function () { // console.log(this.id, 'resume', this.paused); if (!this.paused || (this._consumer && this._consumer.paused) || (this._multiplexer && this._multiplexer.paused)) { return; } this.paused = false; // Emit all pending tokens in _outgoing. if (this._outgoing.length) { this._emitNext(); // The emit may have caused the stream to pause. if (this.paused) { return; } } if (this._generator) { this._runGenerator(); } else if (this._can_drain) { // perhaps a node stream is being piped in this.emit('drain'); } }); /** * Ends a Stream. This is the same as sending a [nil](#nil) value as data. * You shouldn't need to call this directly, rather it will be called by * any [Node Readable Streams](http://nodejs.org/api/stream.html#stream_class_stream_readable) * you pipe in. * * Only call this function on streams that were constructed with no source * (i.e., with `_()`). * * @id end * @section Stream Objects * @name Stream.end() * @aprototype.ppi public * * mystream.end(); */ addMethod('end', function () { if (this._nil_pushed) { // Allow ending multiple times. return; } this.write(nil); }); /** * Pipes a Highland Stream to a [Node Writable * Stream](http://nodejs.org/api/stream.html#stream_class_stream_writable). * This will pull all the data from the source Highland Stream and write it to * the destination, automatically managing flow so that the destination is not * overwhelmed by a fast source. * * Users may optionally pass an object that may contain any of these fields: * * - `end` - Ends the destination when this stream ends. Default: `true`. This * option has no effect if the destination is either `process.stdout` or * `process.stderr`. Those two streams are never ended. * * Like [Readable#pipe](https://nodejs.org/api/stream.html#stream_readable_pipe_destination_options), * this function will throw errors if there is no `error` handler installed on * the stream. * * This function returns the destination so you can chain together `pipe` calls. * * **NOTE**: While Highland streams created via `_()` and [pipeline](#pipeline) * support being piped to, it is almost never appropriate to `pipe` from a * Highland stream to another Highland stream. Those two cases are meant for * use when piping from *Node* streams. You might be tempted to use `pipe` to * construct reusable transforms. Do not do it. See [through](#through) for a * better way. * * @id pipe * @section Consumption * @name Stream.pipe(dest, options) * @param {Writable Stream} dest - the destination to write all data to * @param {Object} options - (optional) pipe options. * @api public * * var source = _(generator); * var dest = fs.createWriteStream('myfile.txt') * source.pipe(dest); * * // chained call * source.pipe(through).pipe(dest); * * // DO NOT do this! It will not work. The stream returned by oddDoubler does * // not support being piped to. * function oddDoubler() { * return _() * return x % 2; // odd numbers only * }) * .map(function (x) { * return x * 2; * }); * } * * _([1, 2, 3, 4]).pipe(oddDoubler()) // => Garbage */ addMethod('pipe', function (dest, options) { options = options || {}; // stdout and stderr are special case writables that cannot be closed var canClose = dest !== process.stdout && dest !== process.stderr && options.end !== false; var end; if (canClose) { end = dest.end; } else { end = nop; } return pipeStream(this, dest, dest.write, end, false); }); /** * Destroys a stream by unlinking it from any consumers and sources. This will * stop all consumers from receiving events from this stream and removes this * stream as a consumer of any source stream. * * This function calls end() on the stream and unlinks it from any piped-to streams. * * @id destroy * @section Stream Objects * @name Stream.destroy() * @api public */ addMethod('destroy', function () { this._explicitly_destroyed = true; // Already destroyed. if (this.ended) { return; } this.readable = this.writable = false; if (!this._nil_pushed) { this.end(); } this._onEnd(); }); Stream.prototype._writeOutgoing = function _writeOutgoing(token) { if (this._explicitly_destroyed) { return; } if (this._nil_pushed) { throw new Error('Cannot write to stream after nil'); } if (token === _.nil) { this._nil_pushed = true; } //console.log('_writeOutgoing', token, this.id); if (token === nil || _._isStreamError(token)) { // Per https://nodejs.org/docs/v0.8.28/api/stream.html#stream_stream_writable // writable should turn false after end is called or an error occurs this.writable = false; } if (this.paused) { this._outgoing.enqueue(token); } else { this._send(token); } }; /** * Runs the generator function for this Stream. If the generator is already * running (it has been called and not called next() yet) then this function * will do nothing. */ Stream.prototype._runGenerator = function () { //console.log(this.id, '_runGenerator'); // if _generator already running, exit if (!this._generator_requested) { return; } if (this._defer_run_generator) { this._run_generator_deferred = true; return; } this._defer_run_generator = true; do { this._run_generator_deferred = false; this._generator_requested = false; // this._generator(this._push_fn, this._next_fn); var gen = this._generator; // Special handling for consume generators. if (gen.__ConsumeGenerator__) { var source = gen.source; if (source._outgoing.length) { var token = source._outgoing.dequeue(); // Inline the pull -> resume -> _emitNext call chain. source._request = gen.pullCb; source.paused = false; source._send(token); } else { // Inline pull. source._request = gen.pullCb; source.resume(); } } else { gen.call(this, this._push_fn, this._next_fn); } } while (this._run_generator_deferred); this._defer_run_generator = false; }; /** * Removes an observer from this Stream. */ Stream.prototype._removeObserver = function (s) { this._observers = this._observers.filter(function (o) { return o !== s; }); if (s.source === this) { s.source = null; } }; /** * Consumes values from a Stream (once resumed) and returns a new Stream for * you to optionally push values onto using the provided push / next functions. * * This function forms the basis of many higher-level Stream operations. * It will not cause a paused stream to immediately resume, but behaves more * like a 'through' stream, handling values as they are read. * * @id consume * @section Transforms * @name Stream.consume(f) * @param {Function} f - the function to handle errors and values * @api public * * var filter = function (f, source) { * return source.consume(function (err, x, push, next) { * if (err) { * // pass errors along the stream and consume next value * push(err); * next(); * } * else if (x === _.nil) { * // pass nil (end event) along the stream * push(null, x); * } * else { * // pass on the value only if the value passes the predicate * if (f(x)) { * push(null, x); * } * next(); * } * }); * }; */ addMethod('consume', function (f) { var source = this, consumer; if (this._consumer) { throw new Error( 'Stream already being consumed, you must either fork() or observe()' ); } if (this._multiplexer) { throw new Error( 'Stream has been forked. You must either fork() or observe().' ); } // This should be a subclass, but prototype resolution is slow, and // consume is on the critical path, so we inline it. var gen = function () { // Important. next may not be called outside of // pullCb. source.pull(pullCb); }; gen.__ConsumeGenerator__ = true; gen.pullCb = pullCb; gen.source = source; consumer = this._consumer = this.createChild(gen); consumer.id = 'consume:' + consumer.id; return consumer; function pullCb(err, x) { // Minor optimization to immediately call the // generator if requested. if (consumer._defer_run_generator) { f(err, x, consumer._push_fn, consumer._next_fn); } else { consumer._defer_run_generator = true; f(err, x, consumer._push_fn, consumer._next_fn); consumer._defer_run_generator = false; if (consumer._run_generator_deferred) { consumer._runGenerator(); } } } }); /** * Consumes a single item from the Stream. Unlike consume, this function will * not provide a new stream for you to push values onto, and it will unsubscribe * as soon as it has a single error, value or nil from the source. * * You probably won't need to use this directly, but it is used internally by * some functions in the Highland library. * * @id pull * @section Consumption * @name Stream.pull(f) * @param {Function} f - the function to handle data * @api public * * xs.pull(function (err, x) { * // do something * }); */ addMethod('pull', function (f) { // console.log(this.id, 'pull', this._outgoing.toArray(), this.paused); if (f == null) { throw new Error('Cannot pull() with a null callback.'); } if (this._request) { f(new Error('Cannot service a second pull() request while one is in progress.')); } // Register the callback and send a message. // Don't need to pause. _send will do it for us. this._request = f; this.resume(); }); /** * Writes a value to the Stream. If the Stream is paused it will go into the * Stream's incoming buffer, otherwise it will be immediately processed and * sent to the Stream's consumers (if any). Returns false if the Stream is * paused, true otherwise. This lets Node's pipe method handle back-pressure. * * You shouldn't need to call this yourself, but it may be called by Node * functions which treat Highland Streams as a [Node Writable Stream](http://nodejs.org/api/stream.html#stream_class_stream_writable). * * Only call this function on streams that were constructed with no source * (i.e., with `_()`). * @id write * @section Stream Objects * @name Stream.write(x) * @param x - the value to write to the Stream * @api public * * var xs = _(); * xs.write(1); * xs.write(2); * xs.end(); * * xs.toArray(function (ys) { * // ys will be [1, 2] * }); * * // Do *not* do this. * var xs2 = _().toArray(_.log); * xs2.write(1); // This call is illegal. */ addMethod('write', function (x) { // console.log(this.id, 'write', x, this.paused); this._writeOutgoing(x); if (!this._generator && this.paused) { this._can_drain = true; } return !this.paused; }); /** * Forks a stream, allowing you to add additional consumers with shared * back-pressure. A stream forked to multiple consumers will only pull values * from its source as fast as the slowest consumer can handle them. * * **NOTE**: Do not depend on a consistent execution order between the forks. * This transform only guarantees that all forks will process a value `foo` * before any will process a second value `bar`. It does *not* guarantee the * order in which the forks process `foo`. * * **TIP**: Be careful about modifying stream values within the forks (or using * a library that does so). Since the same value will be passed to every fork, * changes made in one fork will be visible in any fork that executes after it. * Add to that the inconsistent execution order, and you can end up with subtle * data corruption bugs. If you need to modify any values, you should make a * copy and modify the copy instead. * * @id fork * @section Higher-order Streams * @name Stream.fork() * @api public * * var xs = _([1, 2, 3, 4]); * var ys = xs.fork(); * var zs = xs.fork(); * * // no values will be pulled from xs until zs also resume * ys.resume(); * * // now both ys and zs will get values from xs * zs.resume(); */ addMethod('fork', function () { if (this._requests) { throw new Error('Cannot fork a stream with an outstanding pull() request.'); } if (this._consumer) { throw new Error('Cannot fork a stream that has already been consumed().'); } if (!this._multiplexer) { this._multiplexer = new StreamMultiplexer(this); } var s = this._multiplexer.newStream(); s.id = 'fork:' + s.id; return s; }); /** * Observes a stream, allowing you to handle values as they are emitted, without * adding back-pressure or causing data to be pulled from the source. This can * be useful when you are performing two related queries on a stream where one * would block the other. Just be aware that a slow observer could fill up its * buffer and cause memory issues. Where possible, you should use [fork](#fork). * * @id observe * @section Higher-order Streams * @name Stream.observe() * @api public * * var xs = _([1, 2, 3, 4]); * var ys = xs.fork(); * var zs = xs.observe(); * * // now both zs and ys will receive data as fast as ys can handle it * ys.resume(); */ addMethod('observe', function () { var s = this.create(); s.id = 'observe:' + s.id; s.writable = false; var self = this; s.onDestroy(function () { self._removeObserver(s); }); // s.source = this; this._observers.push(s); return s; }); /** * Extracts errors from a Stream and applies them to an error handler * function. Returns a new Stream with the errors removed (unless the error * handler chooses to rethrow them using `push`). Errors can also be * transformed and put back onto the Stream as values. * * @id errors * @section Transforms * @name Stream.errors(f) * @param {Function} f - the function to pass all errors to * @api public * * getDocument.errors(function (err, push) { * if (err.statusCode === 404) { * // not found, return empty doc * push(null, {}); * } * else { * // otherwise, re-throw the error * push(err); * } * }); */ addMethod('errors', function (f) { return this.consume(function (err, x, push, next) { if (err) { f(err, push); next(); } else if (x === nil) { push(null, nil); } else { push(null, x); next(); } }); }); /** * Like the [errors](#errors) method, but emits a Stream end marker after * an Error is encountered. * * @id stopOnError * @section Transforms * @name Stream.stopOnError(f) * @param {Function} f - the function to handle an error * @api public * * brokenStream.stopOnError(function (err, push) { * // console.error('Something broke: ' + err); * * // Rethrow if needed * // push(err); * }); */ addMethod('stopOnError', function (f) { return this.consume(function (err, x, push, next) { if (err) { f(err, push); push(null, nil); } else if (x === nil) { push(null, nil); } else { push(null, x); next(); } }); }); /** * Iterates over every value from the Stream, calling the iterator function * on each of them. This method consumes the Stream. * * If an error from the Stream reaches this call, it will emit an `error` event * (i.e., it will call `emit('error')` on the stream being consumed). This * event will cause an error to be thrown if unhandled. * * While `each` consumes the stream, it is possible to chain [done](#done) (and * *only* `done`) after it. * * @id each * @section Consumption * @name Stream.each(f) * @param {Function} f - the iterator function * @api public * * _([1, 2, 3, 4]).each(function (x) { * // will be called 4 times with x being 1, 2, 3 and 4 * }); */ addMethod('each', function (f) { var self = this; var s = this.consume(function (err, x, push, next) { if (err) { self.emit('error', err); } else if (x === nil) { push(null, nil); } else { f(x); next(); } }); s.resume(); return s; }); /** * Applies all values from a Stream as arguments to a function. This method consumes the stream. * `f` will always be called when the `nil` token is encountered, even when the stream is empty. * * @id apply * @section Consumption * @name Stream.apply(f) * @param {Function} f - the function to apply arguments to * @api public * * _([1, 2, 3]).apply(function (a, b, c) { * // a === 1 * // b === 2 * // c === 3 * }); * * _([1, 2, 3]).apply(function (a) { * // arguments.length === 3 * // a === 1 * }); */ addMethod('apply', function (f) { return this.toArray(function (args) { f.apply(null, args); }); }); /** * Collects all values from a Stream into an Array and calls a function with * the result. This method consumes the stream. * * If an error from the Stream reaches this call, it will emit an `error` event * (i.e., it will call `emit('error')` on the stream being consumed). This * event will cause an error to be thrown if unhandled. * * @id toArray * @section Consumption * @name Stream.toArray(f) * @param {Function} f - the callback to provide the completed Array to * @api public * * _([1, 2, 3, 4]).toArray(function (x) { * // parameter x will be [1,2,3,4] * }); */ addMethod('toArray', function (f) { var self = this; return this.collect().pull(function (err, x) { if (err) { self.emit('error', err); } else { f(x); } }); }); /** * Calls a function once the Stream has ended. This method consumes the stream. * If the Stream has already ended, the function is called immediately. * * If an error from the Stream reaches this call, it will emit an `error` event * (i.e., it will call `emit('error')` on the stream being consumed). This * event will cause an error to be thrown if unhandled. * * As a special case, it is possible to chain `done` after a call to * [each](#each) even though both methods consume the stream. * * @id done * @section Consumption * @name Stream.done(f) * @param {Function} f - the callback * @api public * * var total = 0; * _([1, 2, 3, 4]).each(function (x) { * total += x; * }).done(function () { * // total will be 10 * }); */ addMethod('done', function (f) { if (this.ended) { f(); return null; } var self = this; return this.consume(function (err, x, push, next) { if (err) { self.emit('error', err); } else if (x === nil) { f(); } else { next(); } }).resume(); }); /** * Registers a callback that will be called when the stream is destroyed. The * callback will have its `this` variable bound to the stream being destroyed. * * This method can be used to free any resources that were allocated when * creating the stream. * * @id onDestroy * @section Consumption * @name Stream.onDestroy(f) * @param {Function} f - the callback * @api public * * var _([1]).onDestroy(function () { * console.log('freed'); * }).each(console.log); * // => 1 * // => freed */ Stream.prototype.onDestroy = function onDestroy(f) { this._destructors.push(f); return this; }; /** * * @id toCallbackHandler * @param {string} transformName Description to compose user-friendly error messages * @param {function} cb Node.js style callback * @return {function} Function passed to .consume * @private */ function toCallbackHandler(transformName, cb) { var value; var hasValue = false; // In case an emitted value === null or === undefined. return function (err, x, push, next) { if (err) { push(null, nil); if (hasValue) { cb(new Error(transformName + ' called on stream emitting multiple values')); } else { cb(err); } } else if (x === nil) { if (hasValue) { cb(null, value); } else { cb(); } } else { if (hasValue) { push(null, nil); cb(new Error(transformName + ' called on stream emitting multiple values')); } else { value = x; hasValue = true; next(); } } }; } /** * Returns the result of a stream to a nodejs-style callback function. * * If the stream contains a single value, it will call `cb` * with the single item emitted by the stream (if present). * If the stream is empty, `cb` will be called without any arguments. * If an error is encountered in the stream, this function will stop * consumption and call `cb` with the error. * If the stream contains more than one item, it will stop consumption * and call `cb` with an error. * * @id toCallback * @section Consumption * @name Stream.toCallback(cb) * @param {Function} cb - the callback to provide the error/result to * @api public * * _([1, 2, 3, 4]).collect().toCallback(function (err, result) { * // parameter result will be [1,2,3,4] * // parameter err will be null * }); */ addMethod('toCallback', function (cb) { this.consume(toCallbackHandler('toCallback', cb)).resume(); }); /** * Converts the result of a stream to Promise. * * If the stream contains a single value, it will return * with the single item emitted by the stream (if present). * If the stream is empty, `undefined` will be returned. * If an error is encountered in the stream, this function will stop * consumption and call `cb` with the error. * If the stream contains more than one item, it will stop consumption * and reject with an error. * * @id toPromise * @section Consumption * @name Stream.toPromise(PromiseCtor) * @param {Function} PromiseCtor - Promises/A+ compliant constructor * @api public * * _([1, 2, 3, 4]).collect().toPromise(Promise).then(function (result) { * // parameter result will be [1,2,3,4] * }); */ addMethod('toPromise', function (PromiseCtor) { var self = this; return new PromiseCtor(function(resolve, reject) { self.consume(toCallbackHandler('toPromise', function(err, res) { if (err) { reject(err); } else { resolve(res); } })).resume(); }); }); /** * Consumes values using the Observable subscribe signature. Unlike other * consumption methods, subscribe can be called multiple times. Each * subscription will receive the current value before receiving the next value. * Subscribing to an already consumed stream will result in an error. * * Implements the Observable subscribe functionality as defined by the spec: * https://tc39.github.io/proposal-observable/#observable-prototype-subscribe * * @id subscribe * @section Consumption * @name Stream.subscribe(onNext, onError, onComplete) * @param {Function|object|null} onNext - Handler for next value or observer * @param {Function|null} onError - Handler function for errors. * @param {Function|null} onCompleted - Handler Function when stream is done. * @returns {ObservableSubscription} - Subscription with unsubscribed method * @api public * * // with callbacks * _([1, 2, 3, 4]).subscribe( * function onNext (x) { * // Called for each value that comes downstream * console.log('Received onNext value', x); * }, * function onError (err) { * // Called one time with error or zero if no errors occur upstream * console.error('Single highland stream error', err); * }, * function onComplete () { * // Receives no arguments * // Called only once when stream is completed. * console.log('Completed!'); * } * ); * * // with an observer * _([1, 2, 3, 4]).subscribe({ * next (x) { * console.log('Received next value', x); * }, * error (err) { * console.error('An error occurred upstream', err); * }, * complete () { * console.log('Completed!') * } * }); */ addMethod('subscribe', function (onNext, onError, onComplete) { var observer = createObserver(onNext, onError, onComplete); return new ObservableSubscription(this, observer); }); /* * Create a variable we can use as a dynamic method name depending on the * environment. * * If Symbols are available get the observable symbol. Otherwise use the a * fallback string. * https://tc39.github.io/proposal-observable/#observable-prototype-@@observable * * Source taken from RxJS * https://github.com/ReactiveX/rxjs/commit/4a5aaafc99825ae9b61e410bc0b5e86c7ae75837#diff-d26bc4881b94c82f3c0ae7d3914e9577R13 */ /* eslint-disable no-undef */ var observable = typeof Symbol === 'function' && Symbol.observable || '@@observable'; /* eslint-enable no-undef */ /** * Returns an Observable spec-compliant instance (itself) that has a subscribe * method and a Symbol.observable method. If Symbol is not available in the * current environment it defaults to '@@observable'. Used by other tools and * libraries that want to get an observable spec compliant stream interface. * * https://tc39.github.io/proposal-observable/#observable-prototype-@@observable * * @id Symbol.observable * @section Consumption * @name Symbol.observable * @api public * * _([1, 2, 3])[Symbol.observable || "@@observable"]().subscribe(x => { * console.log("Received value", x); * }); */ addMethod(observable, function () { return this; }); /** * Converts the stream to a node Readable Stream for use in methods * or pipes that depend on the native stream type. * * The options parameter can be an object passed into the [`Readable` * constructor](http://nodejs.org/api/stream.html#stream_class_stream_readable). * * @id toNodeStream * @section Consumption * @name Stream.toNodeStream(options) * @param {Object} options - (optional) [`Readable` constructor](http://nodejs.org/api/stream.html#stream_class_stream_readable) options * @api public * * _(fs.createReadStream('./abc')).toNodeStream() * _(fs.createReadStream('./abc')).toNodeStream({objectMode: false}) * _([{a: 1}]).toNodeStream({objectMode: true}) */ addMethod('toNodeStream', function (options) { return new ReadableProxy(this, options, _.nil); }); /** * Creates a new Stream of transformed values by applying a function to each * value from the source. * * @id map * @section Transforms * @name Stream.map(f) * @param {Function} f - the transformation function * @api public * * var doubled = _([1, 2, 3, 4]).map(function (x) { * return x * 2; * }); // => 2, 4, 6, 8 */ addMethod('map', function (f) { if (!_.isFunction(f)) { throw new Error('map expects a function as its only argument.'); } return this.consume(function (err, x, push, next) { if (err) { push(err); next(); } else if (x === nil) { push(err, x); } else { var fnVal, fnErr; try { fnVal = f(x); } catch (e) { fnErr = e; } push(fnErr, fnVal); next(); } }); }); Stream.prototype['fantasy-land/map'] = Stream.prototype.map; /** * Creates a new Stream which applies a function to each value from the source * and re-emits the source value. Useful when you want to mutate the value or * perform side effects * * @id doto * @section Transforms * @name Stream.doto(f) * @param {Function} f - the function to apply * @api public * * var appended = _([[1], [2], [3], [4]]).doto(function (x) { * x.push(1); * }); * * _([1, 2, 3]).doto(console.log) * // 1 * // 2 * // 3 * // => 1, 2, 3 */ addMethod('doto', function (f) { return this.map(function (x) { f(x); return x; }); }); /** * An alias for the [doto](#doto) method. * * @id tap * @section Transforms * @name Stream.tap(f) * @param {Function} f - the function to apply * @api public * * _([1, 2, 3]).tap(console.log) */ Stream.prototype.tap = Stream.prototype.doto; _.tap = _.doto; /** * Limits number of values through the stream to a maximum of number of values * per window. Errors are not limited but allowed to pass through as soon as * they are read from the source. * * @id ratelimit * @section Transforms * @name Stream.ratelimit(num, ms) * @param {Number} num - the number of operations to perform per window * @param {Number} ms - the window of time to limit the operations in (in ms) * @api public * * _([1, 2, 3, 4, 5]).ratelimit(2, 100); * * // after 0ms => 1, 2 * // after 100ms => 1, 2, 3, 4 * // after 200ms => 1, 2, 3, 4, 5 */ addMethod('ratelimit', function (num, ms) { if (num < 1) { throw new Error('Invalid number of operations per ms: ' + num); } var sent = 0; return this.consume(function (err, x, push, next) { if (err) { push(err); next(); } else if (x === nil) { push(null, nil); } else { if (sent < num) { sent++; push(null, x); next(); } else { setTimeout(function () { sent = 1; push(null, x); next(); }, ms); } } }); }); /** * Creates a new Stream of values by applying each item in a Stream to an * iterator function which must return a (possibly empty) Stream. Each item on * these result Streams are then emitted on a single output Stream. * * This transform is functionally equivalent to `.map(f).sequence()`. * * @id flatMap * @section Higher-order Streams * @name Stream.flatMap(f) * @param {Function} f - the iterator function * @api public * * var readFile = _.wrapCallback(fs.readFile); * filenames.flatMap(readFile) */ addMethod('flatMap', function (f) { return this.map(f).sequence(); }); Stream.prototype['fantasy-land/chain'] = Stream.prototype.flatMap; /** * Creates a new Stream of values by applying each item in a Stream to each * value in a Stream of functions * * @id ap * @section Higher-order Streams * @name Stream.ap(m) * @param {Stream} m - incoming stream of function(s) to apply to value(s) in stream * @api public * * var asyncUnit = () => _([]); * var asyncAutocomplete = e => _(fetch(`/autocomplete?s=${e.target.value}`)); * * var fns = _('change', checkbox) * .flatMap(e => _.of(e.target.checked ? asyncAutocomplete : asyncUnit)); * * _('change', input) * .ap(fns) * .sequence() * .map(showAutocompleteResults); */ addMethod('ap', function(m) { return _([ this.map(function (u1) { return { u: u1, }; }), m.map(function (m1) { return { m: m1, }; }), ]) .merge() .scan1(function (x, y) { return _.extend(y, x); }) .filter(function (x) { return x.u && x.m; }) .map(function (x) { return x.m(x.u); }); }); Stream.prototype['fantasy-land/ap'] = Stream.prototype.ap; /** * Retrieves values associated with a given property from all elements in * the collection. * * @id pluck * @section Transforms * @name Stream.pluck(property) * @param {String} prop - the property to which values should be associated * @api public * * var docs = [ * {type: 'blogpost', title: 'foo'}, * {type: 'blogpost', title: 'bar'}, * {type: 'comment', title: 'baz'} * ]; * * _(docs).pluck('title').toArray(function (xs) { * // xs is now ['foo', 'bar', 'baz'] * }); */ addMethod('pluck', function (prop) { return this.consume(function (err, x, push, next) { if (err) { push(err); next(); } else if (x === nil) { push(err, x); } else if (_.isObject(x)) { push(null, x[prop]); next(); } else { push(new Error( 'Expected Object, got ' + (typeof x) )); next(); } }); }); /** * Only applies the transformation strategy on Objects. * This helper is used in `pick` and `pickBy` **/ var objectOnly = _.curry(function(strategy, x) { if (_.isObject(x)) { return strategy(x); } else { throw new Error( 'Expected Object, got ' + (typeof x) ); } }); /** * * Retrieves copies of all the elements in the collection * that satisfy a given predicate. Note: When using ES3, * only enumerable elements are selected. Both enumerable * and non-enumerable elements are selected when using ES5. * * @id pickBy * @section Transforms * @name Stream.pickBy(f) * @param {Function} f - the predicate function * @api public * * var dogs = [ * {breed: 'chihuahua', name: 'Princess', age: 5}, * {breed: 'labrador', name: 'Rocky', age: 3}, * {breed: 'german-shepherd', name: 'Waffles', age: 9} * ]; * _(dogs).pickBy(function (value, key) { * return value > 4; * }).toArray(function (xs) { * // xs is now: * [ * { age: 5 }, * {}, * { age: 9 } * ] * }); */ addMethod('pickBy', function (f) { return this.map(objectOnly(function (x) { var out = {}; // prevents testing overridden properties multiple times. var seen = isES5 ? Object.create(null) : {}; var obj = x; // variable used to traverse prototype chain function testAndAdd (prop) { if (seen[prop] !== true && f(x[prop], prop)) { out[prop] = x[prop]; seen[prop] = true; } } if (isES5) { do { Object.getOwnPropertyNames(obj).forEach(testAndAdd); obj = Object.getPrototypeOf(obj); } while (obj); } else { for (var k in x) { testAndAdd(k); } } return out; })); }); /** * * Retrieves copies of all elements in the collection, * with only the whitelisted keys. If one of the whitelisted * keys does not exist, it will be ignored. * * @id pick * @section Transforms * @name Stream.pick(properties) * @param {Array} properties - property names to white filter * @api public * * var dogs = [ * {breed: 'chihuahua', name: 'Princess', age: 5}, * {breed: 'labrador', name: 'Rocky', age: 3}, * {breed: 'german-shepherd', name: 'Waffles', age: 9} * ]; * * _(dogs).pick(['breed', 'age']).toArray(function (xs) { * // xs is now: * [ * {breed: 'chihuahua', age: 5}, * {breed: 'labrador', age: 3}, * {breed: 'german-shepherd', age: 9} * ] * }); * * _(dogs).pick(['owner']).toArray(function (xs) { * // xs is now: * [ * {}, * {}, * {} * ] * });*/ addMethod('pick', function (properties) { return this.map(objectOnly(function(x) { var out = {}; for (var i = 0, length = properties.length; i < length; i++) { var p = properties[i]; if (p in x) { out[p] = x[p]; } } return out; })); }); /** * Creates a new Stream that includes only the values that pass a truth test. * * @id filter * @section Transforms * @name Stream.filter(f) * @param {Function} f - the truth test function * @api public * * var evens = _([1, 2, 3, 4]).filter(function (x) { * return x % 2 === 0; * }); */ addMethod('filter', function (f) { return this.consume(function (err, x, push, next) { if (err) { push(err); next(); } else if (x === nil) { push(err, x); } else { var fnVal, fnErr; try { fnVal = f(x); } catch (e) { fnErr = e; } if (fnErr) { push(fnErr); } else if (fnVal) { push(null, x); } next(); } }); }); Stream.prototype['fantasy-land/filter'] = Stream.prototype.filter; /** * Filters using a predicate which returns a Stream. If you need to check * against an asynchronous data source when filtering a Stream, this can * be convenient. The Stream returned from the filter function should have * a Boolean as its first value (all other values on the Stream will be * disregarded). * * @id flatFilter * @section Higher-order Streams * @name Stream.flatFilter(f) * @param {Function} f - the truth test function which returns a Stream * @api public * * var checkExists = _.wrapCallback(fs.access); * * filenames.flatFilter(checkExists) */ addMethod('flatFilter', function (f) { return this.flatMap(function (x) { return f(x).take(1).otherwise(errorStream()) .flatMap(function (bool) { return _(bool ? [x] : []); }); }); function errorStream() { return _(function (push) { push(new Error('Stream returned by function was empty.')); push(null, _.nil); }); } }); /** * The inverse of [filter](#filter). * * @id reject * @section Transforms * @name Stream.reject(f) * @param {Function} f - the truth test function * @api public * * var odds = _([1, 2, 3, 4]).reject(function (x) { * return x % 2 === 0; * }); */ addMethod('reject', function (f) { return this.filter(_.compose(_.not, f)); }); /** * A convenient form of [filter](#filter), which returns the first object from a * Stream that passes the provided truth test. * * @id find * @section Transforms * @name Stream.find(f) * @param {Function} f - the truth test function which returns a Stream * @api public * * var docs = [ * {type: 'blogpost', title: 'foo'}, * {type: 'blogpost', title: 'bar'}, * {type: 'comment', title: 'foo'} * ]; * * var f = function (x) { * return x.type == 'blogpost'; * }; * * _(docs).find(f); * // => {type: 'blogpost', title: 'foo'} * * // example with partial application * var firstBlogpost = _.find(f); * * firstBlogpost(docs) * // => {type: 'blogpost', title: 'foo'} */ addMethod('find', function (f) { return this.filter(f).take(1); }); /** * A convenient form of [where](#where), which returns the first object from a * Stream that matches a set of property values. findWhere is to [where](#where) as [find](#find) is to [filter](#filter). * * @id findWhere * @section Transforms * @name Stream.findWhere(props) * @param {Object} props - the properties to match against * @api public * * var docs = [ * {type: 'blogpost', title: 'foo'}, * {type: 'blogpost', title: 'bar'}, * {type: 'comment', title: 'foo'} * ]; * * _(docs).findWhere({type: 'blogpost'}) * // => {type: 'blogpost', title: 'foo'} * * // example with partial application * var firstBlogpost = _.findWhere({type: 'blogpost'}); * * firstBlogpost(docs) * // => {type: 'blogpost', title: 'foo'} */ addMethod('findWhere', function (props) { return this.where(props).take(1); }); /** * A convenient form of [reduce](#reduce), which groups items based on a function or property name * * @id group * @section Transforms * @name Stream.group(f) * @param {Function | String} f - the function or property name on which to group, * toString() is called on the result of a function. * @api public * * var docs = [ * {type: 'blogpost', title: 'foo'}, * {type: 'blogpost', title: 'bar'}, * {type: 'comment', title: 'foo'} * ]; * * var f = function (x) { * return x.type; * }; * * _(docs).group(f); OR _(docs).group('type'); * // => { * // => 'blogpost': [{type: 'blogpost', title: 'foo'}, {type: 'blogpost', title: 'bar'}] * // => 'comment': [{type: 'comment', title: 'foo'}] * // => } * */ addMethod('group', function (f) { var lambda = _.isString(f) ? _.get(f) : f; return this.reduce(function (m, o) { var key = lambda(o); if (!hasOwn.call(m, key)) { m[key] = []; } m[key].push(o); return m; }, {}); }); /** * Filters a Stream to drop all non-truthy values. * * @id compact * @section Transforms * @name Stream.compact() * @api public * * var compacted = _([0, 1, false, 3, null, undefined, 6]).compact(); * // => 1, 3, 6 */ addMethod('compact', function () { return this.filter(function (x) { return x; }); }); /** * A convenient form of [filter](#filter), which returns all objects from a Stream * which match a set of property values. * * @id where * @section Transforms * @name Stream.where(props) * @param {Object} props - the properties to match against * @api public * * var docs = [ * {type: 'blogpost', title: 'foo'}, * {type: 'blogpost', title: 'bar'}, * {type: 'comment', title: 'foo'} * ]; * * _(docs).where({title: 'foo'}) * // => {type: 'blogpost', title: 'foo'} * // => {type: 'comment', title: 'foo'} * * // example with partial application * var getBlogposts = _.where({type: 'blogpost'}); * * getBlogposts(docs) * // => {type: 'blogpost', title: 'foo'} * // => {type: 'blogpost', title: 'bar'} */ addMethod('where', function (props) { return this.filter(function (x) { for (var k in props) { if (x[k] !== props[k]) { return false; } } return true; }); }); /** * Filters out all duplicate values from the stream and keeps only the first * occurence of each value, using the provided function to define equality. * * Note: * * - Memory: In order to guarantee that each unique item is chosen only once, * we need to keep an internal buffer of all unique values. This may outgrow * the available memory if you are not cautious about the size of your stream * and the number of unique objects you may receive on it. * - Errors: The comparison function should never throw an error. However, if * it does, this transform will emit an error for each all that throws. This * means that one value may turn into multiple errors. * * @id uniqBy * @section Transforms * @name Stream.uniqBy(compare) * @param {Function} compare - custom equality predicate * @api public * * var colors = [ 'blue', 'red', 'red', 'yellow', 'blue', 'red' ] * * _(colors).uniqBy(function(a, b) { return a[1] === b[1]; }) * // => 'blue' * // => 'red' * */ addMethod('uniqBy', function (compare) { var uniques = []; return this.consume(function (err, x, push, next) { if (err) { push(err); next(); } else if (x === nil) { push(err, x); } else { var seen = false; var hasErr; for (var i = 0, len = uniques.length; i < len; i++) { try { seen = compare(x, uniques[i]); } catch (e) { hasErr = e; seen = true; } if (seen) { break; } } if (!seen) { uniques.push(x); push(null, x); } if (hasErr) { push(hasErr); } next(); } }); }); /** * Filters out all duplicate values from the stream and keeps only the first * occurence of each value, using `===` to define equality. * * Like [uniqBy](#uniqBy), this transform needs to store a buffer containing * all unique values that has been encountered. Be careful about using this * transform on a stream that has many unique values. * * @id uniq * @section Transforms * @name Stream.uniq() * @api public * * var colors = [ 'blue', 'red', 'red', 'yellow', 'blue', 'red' ] * * _(colors).uniq() * // => 'blue' * // => 'red' * // => 'yellow' */ addMethod('uniq', function () { if (!_.isUndefined(_global.Set)) { var uniques = new _global.Set(), size = uniques.size; return this.consume(function (err, x, push, next) { if (err) { push(err); next(); } else if (x === nil) { push(err, x); } // pass NaN through as Set does not respect strict // equality in this case. else if (x !== x) { push(null, x); next(); } else { uniques.add(x); if (uniques.size > size) { size = uniques.size; push(null, x); } next(); } }); } return this.uniqBy(function (a, b) { return a === b; }); }); /** * Takes a *finite* stream of streams and returns a stream where the first * element from each separate stream is combined into a single data event, * followed by the second elements of each stream and so on until the shortest * input stream is exhausted. * * @id zipAll * @section Higher-order Streams * @name Stream.zipAll() * @api public * * _([ * _([1, 2, 3]), * _([4, 5, 6]), * _([7, 8, 9]), * _([10, 11, 12]) * ]).zipAll() * // => [1, 4, 7, 10], [2, 5, 8, 11], [3, 6, 9, 12] * * // shortest stream determines length of output stream * _([ * _([1, 2, 3, 4]), * _([5, 6, 7, 8]), * _([9, 10, 11, 12]), * _([13, 14]) * ]).zipAll() * // => [1, 5, 9, 13], [2, 6, 10, 14] */ addMethod('zipAll', function () { var returned = 0; var z = []; var finished = false; function nextValue(index, max, src, push, next) { src.pull(function (err, x) { if (err) { push(err); nextValue(index, max, src, push, next); } else if (x === _.nil) { if (!finished) { finished = true; push(null, nil); } } else { returned++; z[index] = x; if (returned === max) { push(null, z); next(); } } }); } var self = this; return self.collect().flatMap(function (array) { if (!array.length) { return self.create([]); } return self.create(function (push, next) { returned = 0; z = []; for (var i = 0, length = array.length; i < length; i++) { nextValue(i, length, array[i], push, next); } }); }); }); /** * Takes a stream and a *finite* stream of `N` streams * and returns a stream of the corresponding `(N+1)`-tuples. * * @id zipEach * @section Higher-order Streams * @name Stream.zipEach(ys) * @param {Array | Stream} ys - the array of streams to combine values with * @api public * * _([1,2,3]).zipEach([[4, 5, 6], [7, 8, 9], [10, 11, 12]]) * // => [1, 4, 7, 10], [2, 5, 8, 11], [3, 6, 9, 12] * * // shortest stream determines length of output stream * _([1, 2, 3, 4]).zipEach([[5, 6, 7, 8], [9, 10, 11, 12], [13, 14]]) * // => [1, 5, 9, 13], [2, 6, 10, 14] */ addMethod('zipEach', function (ys) { return this.create([this]) .concat(this.create(ys).map(bindContext(this.create, this))) .zipAll(); }); /** * Takes two Streams and returns a Stream of corresponding pairs. The size of * the resulting stream is the smaller of the two source streams. * * @id zip * @section Higher-order Streams * @name Stream.zip(ys) * @param {Array | Stream} ys - the other stream to combine values with * @api public * * _(['a', 'b', 'c']).zip([1, 2, 3]) // => ['a', 1], ['b', 2], ['c', 3] * * _(['a', 'b', 'c']).zip(_([1])) // => ['a', 1] */ addMethod('zip', function (ys) { return this.create([this, this.create(ys)]).zipAll(); }); /** * Takes one Stream and batches incoming data into arrays of given length * * @id batch * @section Transforms * @name Stream.batch(n) * @param {Number} n - length of the array to batch * @api public * * _([1, 2, 3, 4, 5]).batch(2) // => [1, 2], [3, 4], [5] */ addMethod('batch', function (n) { return this.batchWithTimeOrCount(-1, n); }); /** * Takes one Stream and batches incoming data within a maximum time frame * into arrays of a maximum length. * * @id batchWithTimeOrCount * @section Transforms * @name Stream.batchWithTimeOrCount(ms, n) * @param {Number} ms - the maximum milliseconds to buffer a batch * @param {Number} n - the maximum length of the array to batch * @api public * * _(function (push) { * push(1); * push(2); * push(3); * setTimeout(push, 20, 4); * }).batchWithTimeOrCount(10, 2) * * // => [1, 2], [3], [4] */ addMethod('batchWithTimeOrCount', function (ms, n) { var batched = [], timeout; return this.consume(function (err, x, push, next) { if (err) { push(err); next(); } else if (x === nil) { if (batched.length > 0) { push(null, batched); clearTimeout(timeout); } push(null, nil); } else { batched.push(x); if (batched.length === n) { push(null, batched); batched = []; clearTimeout(timeout); } else if (batched.length === 1 && ms >= 0) { timeout = setTimeout(function () { push(null, batched); batched = []; }, ms); } next(); } }); }); /** * Creates a new Stream with the separator interspersed between the elements of the source. * * `intersperse` is effectively the inverse of [splitBy](#splitBy). * * @id intersperse * @section Transforms * @name Stream.intersperse(sep) * @param {String} sep - the value to intersperse between the source elements * @api public * * _(['ba', 'a', 'a']).intersperse('n') // => 'ba', 'n', 'a', 'n', 'a' * _(['mississippi']).splitBy('ss').intersperse('ss') // => 'mi', 'ss', 'i', 'ss', 'ippi' * _(['foo']).intersperse('bar') // => 'foo' */ addMethod('intersperse', function (separator) { var started = false; return this.consume(function (err, x, push, next) { if (err) { push(err); next(); } else if (x === nil) { push(null, nil); } else { if (started) { push(null, separator); } else { started = true; } push(null, x); next(); } }); }); /** * Splits the source Stream by a separator and emits the pieces in between, much like splitting a string. * * `splitBy` is effectively the inverse of [intersperse](#intersperse). * * @id splitBy * @section Transforms * @name Stream.splitBy(sep) * @param {String | RegExp} sep - the separator to split on * @api public * * _(['mis', 'si', 's', 'sippi']).splitBy('ss') // => 'mi', 'i', 'ippi' * _(['ba', 'a', 'a']).intersperse('n').splitBy('n') // => 'ba', 'a', 'a' * _(['foo']).splitBy('bar') // => 'foo' */ addMethod('splitBy', function (sep) { var decoder = new Decoder(); var buffer = false; function drain(x, push) { buffer = (buffer || '') + decoder.write(x); var pieces = buffer.split(sep); buffer = pieces.pop(); pieces.forEach(function (piece) { push(null, piece); }); } return this.consume(function (err, x, push, next) { if (err) { push(err); next(); } else if (x === nil) { if (_.isString(buffer)) { drain(decoder.end(), push); push(null, buffer); } push(null, nil); } else { drain(x, push); next(); } }); }); /** * [splitBy](#splitBy) over newlines. * * @id split * @section Transforms * @name Stream.split() * @api public * * _(['a\n', 'b\nc\n', 'd', '\ne']).split() // => 'a', 'b', 'c', 'd', 'e' * _(['a\r\nb\nc']]).split() // => 'a', 'b', 'c' */ addMethod('split', function () { return this.splitBy(/\r?\n/); }); /** * Creates a new Stream with the values from the source in the range of `start` * (inclusive) to `end` (exclusive). * * @id slice * @section Transforms * @name Stream.slice(start, end) * @param {Number} start - (optional) integer representing index to start * reading from source (inclusive). Defaults to `0` if not specified. * @param {Number} stop - (optional) integer representing index to stop * reading from source (exclusive). Defaults to `Infinity` if not * specified. * @throws {TypeError} if either parameters are not numbers. * @throws {RangeError} if either parameters are negative. * @api public * * _([1, 2, 3, 4]).slice(1, 3) // => 2, 3 */ addMethod('slice', function(start, end) { if (start == null) { start = 0; } if (end == null) { end = Infinity; } checkIsNumber(start, 'start'); checkIsNumber(end, 'end'); checkRange(start >= 0, 'start cannot be negative.'); checkRange(end >= 0, 'end cannot be negative.'); var index = 0; if (start === 0 && end === Infinity) { return this; } else if (start >= end) { return _([]); } var s = this.consume(function (err, x, push, next) { var done = x === nil; if (err) { push(err); } else if (!done && index++ >= start) { push(null, x); } if (!done && index < end) { next(); } else { push(null, nil); } }); s.id = 'slice:' + s.id; return s; }); /** * Creates a new Stream with the first `n` values from the source. * * @id take * @section Transforms * @name Stream.take(n) * @param {Number} n - integer representing number of values to read from source * @throws {TypeError} if `n` is not a number. * @throws {RangeError} if `n` is negative. * @api public * * _([1, 2, 3, 4]).take(2) // => 1, 2 */ addMethod('take', function (n) { var s = this.slice(0, n); s.id = 'take:' + s.id; return s; }); /** * Creates a new Stream with the first values from the source as long as the function * returns true. * * @id takeWhile * @section Transforms * @name Stream.takeWhile(f) * @param {Function} f - the filter function * @throws {TypeError} if `f` is not a function. * @api public * * _([1, 2, 3, 4]).takeWhile(x => x < 3) // => 1, 2 */ addMethod('takeWhile', function (f) { if (!_.isFunction(f)) { throw new Error('takeWhile expects a function as its only argument.'); } return this.consume(function (err, x, push, next) { if (err) { push(err); next(); } else if (x === nil) { push(err, x); } else { var fnVal, fnErr; try { fnVal = f(x); } catch (e) { fnErr = e; } if (fnErr) { push(fnErr, null); next(); } else if (fnVal) { push(null, x); next(); } else { push(null, nil); } } }); }); /** * Acts as the inverse of [`take(n)`](#take) - instead of returning the first * `n` values, it ignores the first `n` values and then emits the rest. All * errors (even ones emitted before the nth value) will be emitted. * * @id drop * @section Transforms * @name Stream.drop(n) * @param {Number} n - integer representing number of values to read from source * @throws {TypeError} if `n` is not a number. * @throws {RangeError} if `n` is negative. * @api public * * _([1, 2, 3, 4]).drop(2) // => 3, 4 */ addMethod('drop', function (n) { return this.slice(n, Infinity); }); /** * Creates a new Stream with only the first value from the source. * * @id head * @section Transforms * @name Stream.head() * @api public * * _([1, 2, 3, 4]).head() // => 1 */ addMethod('head', function () { return this.take(1); }); /** * Drops all values from the Stream apart from the last one (if any). * * @id last * @section Transforms * @name Stream.last() * @api public * * _([1, 2, 3, 4]).last() // => 4 */ addMethod('last', function () { var nothing = {}; var prev = nothing; return this.consume(function (err, x, push, next) { if (err) { push(err); next(); } else if (x === nil) { if (prev !== nothing) { push(null, prev); } push(null, nil); } else { prev = x; next(); } }); }); /** * Collects all values together then emits each value individually in sorted * order. The method for sorting the elements is defined by the comparator * function supplied as a parameter. * * The comparison function takes two arguments `a` and `b` and should return * * - a negative number if `a` should sort before `b`. * - a positive number if `a` should sort after `b`. * - zero if `a` and `b` may sort in any order (i.e., they are equal). * * This function must also define a [partial * order](https://en.wikipedia.org/wiki/Partially_ordered_set). If it does not, * the resulting ordering is undefined. * * @id sortBy * @section Transforms * @name Stream.sortBy(f) * @param {Function} f - the comparison function * @api public * * var sorts = _([3, 1, 4, 2]).sortBy(function (a, b) { * return b - a; * }).toArray(_.log); * * //=> [4, 3, 2, 1] */ addMethod('sortBy', function (f) { return this.collect().invoke('sort', [f]).sequence(); }); /** * Collects all values together then emits each value individually but in sorted order. * The method for sorting the elements is ascending lexical. * * @id sort * @section Transforms * @name Stream.sort() * @api public * * var sorted = _(['b', 'z', 'g', 'r']).sort().toArray(_.log); * // => ['b', 'g', 'r', 'z'] */ addMethod('sort', function () { return this.sortBy(); }); /** * Transforms a stream using an arbitrary target transform. * * If `target` is a function, this transform passes the current Stream to it, * returning the result. * * If `target` is a [Duplex * Stream](https://nodejs.org/api/stream.html#stream_class_stream_duplex_1), * this transform pipes the current Stream through it. It will always return a * Highland Stream (instead of the piped to target directly as in * [pipe](#pipe)). Any errors emitted will be propagated as Highland errors. * * **TIP**: Passing a function to `through` is a good way to implement complex * reusable stream transforms. You can even construct the function dynamically * based on certain inputs. See examples below. * * @id through * @section Higher-order Streams * @name Stream.through(target) * @param {Function | Duplex Stream} target - the stream to pipe through or a * function to call. * @api public * * // This is a static complex transform. * function oddDoubler(s) { * return s.filter(function (x) { * return x % 2; // odd numbers only * }) * .map(function (x) { * return x * 2; * }); * } * * // This is a dynamically-created complex transform. * function multiplyEvens(factor) { * return function (s) { * return s.filter(function (x) { * return x % 2 === 0; * }) * .map(function (x) { * return x * factor; * }); * }; * } * * _([1, 2, 3, 4]).through(oddDoubler); // => 2, 6 * * _([1, 2, 3, 4]).through(multiplyEvens(5)); // => 10, 20 * * // Can also be used with Node Through Streams * _(filenames).through(jsonParser).map(function (obj) { * // ... * }); * * // All errors will be propagated as Highland errors * _(['zz{"a": 1}']).through(jsonParser).errors(function (err) { * console.log(err); // => SyntaxError: Unexpected token z * }); */ addMethod('through', function (target) { var output; if (_.isFunction(target)) { return target(this); } else { output = this.createChild(); this.on('error', writeErr); target.on('error', writeErr); // Intentionally bypass this.pipe so that through() and pipe() can // evolve independently of each other. return pipeStream(this, target, target.write, target.end, false) .pipe(output); } function writeErr(err) { output.write(new StreamError(err)); } }); /** * Creates a 'Through Stream', which passes data through a pipeline * of functions or other through Streams. This is particularly useful * when combined with partial application of Highland functions to expose a * Node-compatible Through Stream. * * This is not a method on a Stream, and it only exposed at the top-level * as `_.pipeline`. It takes an arbitrary number of arguments. * * @id pipeline * @section Higher-order Streams * @name _.pipeline(...) * @api public * * var through = _.pipeline( * _.map(parseJSON), * _.filter(isBlogpost), * _.reduce(collectCategories) * _.through(otherPipeline) * ); * * readStream.pipe(through).pipe(outStream); * * // Alternatively, you can use pipeline to manipulate a stream in * // the chained method call style: * * var through2 = _.pipeline(function (s) { * return s.map(parseJSON).filter(isBlogpost); // etc. * }); */ addToplevelMethod('pipeline', function (/*through...*/) { if (!arguments.length) { return this(); } var start = arguments[0], rest, startHighland; if (!_.isStream(start) && !_.isFunction(start.resume)) { // not a Highland stream or Node stream, start with empty stream start = this(); startHighland = start; rest = slice.call(arguments); } else { // got a stream as first argument, co-erce to Highland stream startHighland = this(start); rest = slice.call(arguments, 1); } var end = rest.reduce(function (src, dest) { return src.through(dest); }, startHighland); var wrapper = this(function (push, next) { end.pull(function (err, x) { push(err, x); if (x !== nil) { next(); } }); }); wrapper.writable = true; wrapper.write = function (x) { return start.write(x); }; wrapper.end = function () { wrapper.writable = false; return start.end(); }; start.on('drain', function () { wrapper.emit('drain'); }); return wrapper; }); /** * Reads values from a Stream of Streams or Arrays, emitting them on a single * output Stream. This can be thought of as a [flatten](#flatten), just one * level deep, often used for resolving asynchronous actions such as a HTTP * request or reading a file. * * @id sequence * @section Higher-order Streams * @name Stream.sequence() * @api public * * var nums = _([ * _([1, 2, 3]), * _([4, 5, 6]) * ]); * * nums.sequence() // => 1, 2, 3, 4, 5, 6 * * // using sequence to read from files in series * var readFile = _.wrapCallback(fs.readFile); * filenames.map(readFile).sequence() */ addMethod('sequence', function () { var original = this; var curr = this; return this.create(function (push, next) { curr.pull(function (err, x) { if (err) { push(err); next(); } else if (_.isArray(x)) { if (onOriginalStream()) { // just send all values from array directly x.forEach(function (y) { push(null, y); }); } else { push(null, x); } next(); } else if (_.isStream(x)) { if (onOriginalStream()) { // switch to reading new stream curr = x; next(); } else { // sequence only goes 1 level deep push(null, x); next(); } } else if (x === nil) { if (onOriginalStream()) { push(null, nil); } else { // resume reading from original curr = original; next(); } } else { if (onOriginalStream()) { // we shouldn't be getting non-stream (or array) // values from the top-level stream push(new Error( 'Expected Stream, got ' + (typeof x) )); next(); } else { push(null, x); next(); } } }); }); function onOriginalStream() { return curr === original; } }); /** * An alias for the [sequence](#sequence) method. * * @id series * @section Higher-order Streams * @name Stream.series() * @api public * * var readFile = _.wrapCallback(fs.readFile); * filenames.map(readFile).series() */ Stream.prototype.series = Stream.prototype.sequence; _.series = _.sequence; /** * Recursively reads values from a Stream which may contain nested Streams * or Arrays. As values or errors are encountered, they are emitted on a * single output Stream. * * @id flatten * @section Higher-order Streams * @name Stream.flatten() * @api public * * _([1, [2, 3], [[4]]]).flatten(); // => 1, 2, 3, 4 * * var nums = _( * _([1, 2, 3]), * _([4, _([5, 6]) ]) * ); * * nums.flatten(); // => 1, 2, 3, 4, 5, 6 */ addMethod('flatten', function () { var curr = this; var stack = []; return this.createChild(function (push, next) { curr.pull(function (err, x) { if (err) { push(err); next(); return; } if (_.isArray(x)) { x = _(x); } if (_.isStream(x)) { stack.push(curr); curr = x; next(); } else if (x === nil) { if (stack.length) { curr = stack.pop(); next(); } else { push(null, nil); } } else { push(null, x); next(); } }); }); }); /** * Takes a Stream of Streams and reads from them in parallel, buffering * the results until they can be returned to the consumer in their original * order. * * @id parallel * @section Higher-order Streams * @name Stream.parallel(n) * @param {Number} n - the maximum number of concurrent reads/buffers * @api public * * var readFile = _.wrapCallback(fs.readFile); * var filenames = _(['foo.txt', 'bar.txt', 'baz.txt']); * * // read from up to 10 files at once * filenames.map(readFile).parallel(10); */ addMethod('parallel', function (n) { var source = this; var running = []; var ended = false; var reading_source = false; if (typeof n !== 'number') { throw new Error('Must specify a number to parallel().'); } if (n <= 0) { throw new Error('The parallelism factor must be positive'); } return this.create(function (push, next) { if (running.length < n && !ended && !reading_source) { // get another stream if not already waiting for one reading_source = true; source.pull(function (err, x) { reading_source = false; if (err) { push(err); } else if (x === nil) { ended = true; } else if (!_.isStream(x)) { push(new Error('Expected Stream, got ' + (typeof x))); } else { // got a new source, add it to the running array var run = {stream: x, buffer: []}; running.push(run); x.consume(function (_err, y, _push, _next) { if (running[0] === run) { // current output stream if (y === nil) { // remove self from running and check // to see if we need to read from source again running.shift(); flushBuffer(); next(); } else { // push directly onto parallel output stream push(_err, y); } } else { // we're reading ahead, buffer the output run.buffer.push([_err, y]); } if (y !== nil) { // keep reading until we hit nil _next(); } }).resume(); } // check if we need to get any more streams return next(); }); } else if (!running.length && ended) { // nothing more to do push(null, nil); } function flushBuffer() { while (running.length && running[0].buffer.length) { var buf = running[0].buffer; for (var i = 0; i < buf.length; i++) { if (buf[i][1] === nil) { // this stream has ended running.shift(); break; } else { // send the buffered output push.apply(null, buf[i]); } } buf.length = 0; } } // else wait for more data to arrive from running streams }); }); /** * Switches source to an alternate Stream if the current Stream is empty. * * @id otherwise * @section Higher-order Streams * @name Stream.otherwise(ys) * @param {Stream | Function} ys - alternate stream (or stream-returning function) to use if this stream is empty * @api public * * _([1,2,3]).otherwise(['foo']) // => 1, 2, 3 * _([]).otherwise(['foo']) // => 'foo' * * _.otherwise(_(['foo']), _([1,2,3])) // => 1, 2, 3 * _.otherwise(_(['foo']), _([])) // => 'foo' */ addMethod('otherwise', function (ys) { var xs = this; return xs.consume(function (err, x, push, next) { if (err) { // got an error, just keep going push(err); next(); } else if (x === nil) { // hit the end without redirecting to xs, use alternative if (_.isFunction(ys)) { next(ys()); } else { next(ys); } } else { // got a value, push it, then redirect to xs push(null, x); next(xs); } }); }); Stream.prototype['fantasy-land/alt'] = Stream.prototype.otherwise; /** * Adds a value to the end of a Stream. * * @id append * @section Transforms * @name Stream.append(y) * @param y - the value to append to the Stream * @api public * * _([1, 2, 3]).append(4) // => 1, 2, 3, 4 */ addMethod('append', function (y) { return this.consume(function (err, x, push, next) { if (x === nil) { push(null, y); push(null, _.nil); } else { push(err, x); next(); } }); }); /** * Boils down a Stream to a single value. The memo is the initial state * of the reduction, and each successive step of it should be returned by * the iterator function. The iterator is passed two arguments: * the memo and the next value. * * If the iterator throws an error, the reduction stops and the resulting * stream will emit that error instead of a value. * * @id reduce * @section Transforms * @name Stream.reduce(iterator, memo) * @param memo - the initial state of the reduction * @param {Function} iterator - the function which reduces the values * @api public * * var add = function (a, b) { * return a + b; * }; * * _([1, 2, 3, 4]).reduce(add, 0) // => 10 */ addMethod('reduce', function (f, z) { // This can't be implemented with scan(), because we don't know if the // errors that we see from the scan were thrown by the iterator or just // passed through from the source stream. return this.consume(function (err, x, push, next) { if (x === nil) { push(null, z); push(null, _.nil); } else if (err) { push(err); next(); } else { try { z = f(z, x); } catch (e) { push(e); push(null, _.nil); return; } next(); } }); }); /** * Same as [reduce](#reduce), but uses the first element as the initial * state instead of passing in a `memo` value. * * @id reduce1 * @section Transforms * @name Stream.reduce1(iterator) * @param {Function} iterator - the function which reduces the values * @api public * * _([1, 2, 3, 4]).reduce1(add) // => 10 */ addMethod('reduce1', function (f) { var self = this; return self.createChild(function (push, next) { self.pull(function (err, x) { if (err) { push(err); next(); } else if (x === nil) { push(null, nil); } else { next(self.reduce(f, x)); } }); }); }); /** * Groups all values into an Array and passes down the stream as a single * data event. This is a bit like doing [toArray](#toArray), but instead * of accepting a callback and consuming the stream, it passes the value on. * * @id collect * @section Transforms * @name Stream.collect() * @api public * * _(['foo', 'bar']).collect().toArray(function (xs) { * // xs will be [['foo', 'bar']] * }); */ addMethod('collect', function () { var xs = []; return this.consume(function (err, x, push, next) { if (err) { push(err); next(); } else if (x === nil) { push(null, xs); push(null, nil); } else { xs.push(x); next(); } }); }); /** * Like [reduce](#reduce), but emits each intermediate value of the * reduction as it is calculated. * * If the iterator throws an error, the scan will stop and the stream will * emit that error. Any intermediate values that were produced before the * error will still be emitted. * * @id scan * @section Transforms * @name Stream.scan(iterator, memo) * @param memo - the initial state of the reduction * @param {Function} iterator - the function which reduces the values * @api public * * _([1, 2, 3, 4]).scan(add, 0) // => 0, 1, 3, 6, 10 */ addMethod('scan', function (f, z) { var self = this; return this.create([z]).concat( self.consume(function (err, x, push, next) { if (x === nil) { push(null, _.nil); } else if (err) { push(err); next(); } else { try { z = f(z, x); } catch (e) { push(e); push(null, _.nil); return; } push(null, z); next(); } }) ); }); /** * Same as [scan](#scan), but uses the first element as the initial * state instead of passing in a `memo` value. * * @id scan1 * @section Transforms * @name Stream.scan1(iterator) * @param {Function} iterator - the function which reduces the values * @api public * * _([1, 2, 3, 4]).scan1(add) // => 1, 3, 6, 10 */ addMethod('scan1', function (f) { var self = this; return self.createChild(function (push, next) { self.pull(function (err, x) { if (err) { push(err); next(); } else if (x === nil) { push(null, nil); } else { next(self.scan(f, x)); } }); }); }); function HighlandTransform(push) { this.push = push; } HighlandTransform.prototype['@@transducer/init'] = function () { return this.push; }; HighlandTransform.prototype['@@transducer/result'] = function (push) { // Don't push nil here. Otherwise, we can't catch errors from `result` // and propagate them. The `transduce` implementation will do it. return push; }; HighlandTransform.prototype['@@transducer/step'] = function (push, input) { push(null, input); return push; }; /** * Applies the transformation defined by the the given *transducer* to the * stream. A transducer is any function that follows the * [Transducer Protocol](https://github.com/cognitect-labs/transducers-js#transformer-protocol). * See * [transduce-js](https://github.com/cognitect-labs/transducers-js#transducers-js) * for more details on what transducers actually are. * * The `result` object that is passed in through the * [Transformer Protocol](https://github.com/cognitect-labs/transducers-js#transformer-protocol) * will be the `push` function provided by the [consume](#consume) transform. * * Like [scan](#scan), if the transducer throws an exception, the transform * will stop and emit that error. Any intermediate values that were produced * before the error will still be emitted. * * @id transduce * @section Transforms * @name Stream.transduce(xf) * @param {Function} xf - The transducer. * @api public * * var xf = require('transducer-js').map(_.add(1)); * _([1, 2, 3, 4]).transduce(xf); * // => 2, 3, 4, 5 */ addMethod('transduce', function transduce(xf) { var transform = null, memo = null; return this.consume(function (err, x, push, next) { if (transform == null) { transform = xf(new HighlandTransform(push)); memo = transform['@@transducer/init'](); } if (err) { // Pass through errors, like we always do. push(err); next(); } else if (x === _.nil) { // Push may be different from memo depending on the transducer that // we get. runResult(push, memo); } else { var res = runStep(push, memo, x); if (!res) { return; } memo = res; if (memo['@@transducer/reduced']) { runResult(memo['@@transducer/value']); } else { next(); } } }); function runResult(push, _memo) { try { transform['@@transducer/result'](_memo); } catch (e) { push(e); } push(null, _.nil); } function runStep(push, _memo, x) { try { return transform['@@transducer/step'](_memo, x); } catch (e) { push(e); push(null, _.nil); return null; } } }); /** * Concatenates a Stream to the end of this Stream. * * Be aware that in the top-level export, the args may be in the reverse * order to what you'd expect `_([a], [b]) => b, a`, as this follows the * convention of other top-level exported functions which do `x` to `y`. * * @id concat * @section Higher-order Streams * @name Stream.concat(ys) * @param {Stream | Array} ys - the values to concatenate onto this Stream * @api public * * _([1, 2]).concat([3, 4]) // => 1, 2, 3, 4 * _.concat([3, 4], [1, 2]) // => 1, 2, 3, 4 */ addMethod('concat', function (ys) { ys = _(ys); return this.consume(function (err, x, push, next) { if (x === nil) { next(ys); } else { push(err, x); next(); } }); }); Stream.prototype['fantasy-land/concat'] = Stream.prototype.concat; /** * Takes a Stream of Streams and merges their values and errors into a * single new Stream. The merged stream ends when all source streams have * ended. * * Note that no guarantee is made with respect to the order in which * values for each stream end up in the merged stream. Values in the * merged stream will, however, respect the order they were emitted from * their respective streams. * * @id merge * @section Higher-order Streams * @name Stream.merge() * @api public * * var readFile = _.wrapCallback(fs.readFile); * * var txt = _(['foo.txt', 'bar.txt']).map(readFile) * var md = _(['baz.md']).map(readFile) * * _([txt, md]).merge(); * // => contents of foo.txt, bar.txt and baz.txt in the order they were read */ addMethod('merge', function () { var self = this; var srcs = []; var srcsNeedPull = [], first = true, async = false; return this.create(function (push, next) { if (first) { first = false; getSourcesSync(push, next); } if (srcs.length === 0) { push(null, nil); } else if (srcsNeedPull.length) { pullFromAllSources(push, next); next(); } else { async = true; } }); // Make a handler for the main merge loop. function srcPullHandler(push, next, src) { return function (err, x) { if (err) { push(err); srcsNeedPull.push(src); } else if (x === nil) { srcs = srcs.filter(function (s) { return s !== src; }); } else { if (src === self) { srcs.push(x); srcsNeedPull.push(x); srcsNeedPull.unshift(self); } else { push(null, x); srcsNeedPull.push(src); } } if (async) { async = false; next(); } }; } function pullFromAllSources(push, next) { var _srcs = srcsNeedPull; srcsNeedPull = []; _srcs.forEach(function (src) { src.pull(srcPullHandler(push, next, src)); }); } // Pulls as many sources as possible from self synchronously. function getSourcesSync(push, next) { // Shadows the outer async variable. var asynchronous; var done = false; var pull_cb = function(err, x) { asynchronous = false; if (done) { // This means the pull was async. Handle like // regular async. srcPullHandler(push, next, self)(err, x); } else { if (err) { push(err); } else if (x === nil) { done = true; } else { srcs.push(x); srcsNeedPull.push(x); } } }; while (!done) { asynchronous = true; self.pull(pull_cb); // Async behavior, record self as a src and return. if (asynchronous) { done = true; srcs.unshift(self); } } } }); /** * Takes a Stream of Streams and merges their values and errors into a * single new Stream, limitting the number of unpaused streams that can * running at any one time. * * Note that no guarantee is made with respect to the order in which * values for each stream end up in the merged stream. Values in the * merged stream will, however, respect the order they were emitted from * their respective streams. * * @id mergeWithLimit * @section Higher-order Streams * @name Stream.mergeWithLimit(n) * @param {Number} n - the maximum number of streams to run in parallel * @api public * * var readFile = _.wrapCallback(fs.readFile); * * var txt = _(['foo.txt', 'bar.txt']).flatMap(readFile) * var md = _(['baz.md']).flatMap(readFile) * var js = _(['bosh.js']).flatMap(readFile) * * _([txt, md, js]).mergeWithLimit(2); * // => contents of foo.txt, bar.txt, baz.txt and bosh.js in the order * // they were read, but bosh.js is not read until either foo.txt and bar.txt * // has completely been read or baz.md has been read */ addMethod('mergeWithLimit', function mergeWithLimit(n){ var self = this; var processCount = 0; var waiting = false; if (typeof n !== 'number' || n < 1) { throw new Error('mergeWithLimit expects a positive number, but got: ' + n); } if (n === Infinity) { return this.merge(); } return this.create(function(push, next){ self.pull(function(err, x){ var done = x === nil; if (err){ push(err); next(); } else if (x === nil) { push(null, nil); } else { processCount++; push(err, x); // console.log('start', x.id); x.onDestroy(function() { processCount--; // console.log('end', x.id); if (waiting) { // console.log('get more'); waiting = false; next(); } }); if (!done && processCount < n) { next(); } else { // console.log('wait till something ends'); waiting = true; } } }); }).merge(); }); /** * Calls a named method on each object from the Stream - returning * a new stream with the result of those calls. * * @id invoke * @section Transforms * @name Stream.invoke(method, args) * @param {String} method - the method name to call * @param {Array} args - the arguments to call the method with * @api public * * _(['foo', 'bar']).invoke('toUpperCase', []) // => 'FOO', 'BAR' * * var readFile = _.wrapCallback(fs.readFile); * filenames.flatMap(readFile).invoke('toString', ['utf8']); */ addMethod('invoke', function (method, args) { return this.map(function (x) { return x[method].apply(x, args); }); }); /** * Takes a Stream of callback-accepting node-style functions, * [wraps](#wrapCallback) each one into a stream-returning function, * calls them with the arguments provided, and returns the results * as a Stream. * * This can be used as a control flow shortcut and draws parallels * with some control flow functions from [async](https://github.com/caolan/async). * A few rough correspondences include: * * - `.nfcall([]).series()` to `async.series()` * - `.nfcall([]).parallel(n)` to `async.parallelLimit(n)` * - `.nfcall(args)` to `async.applyEach(..., args)` * - `.nfcall(args).series()` to `async.applyEachSeries(..., args)` * * @id nfcall * @section Transforms * @name Stream.nfcall(args) * @param {Array} args - the arguments to call each function with * @api public * * _([ * function (callback) { * setTimeout(function () { * callback(null, 'one'); * }, 200); * }, * function (callback) { * setTimeout(function () { * callback(null, 'two'); * }, 100); * } * ]).nfcall([]).parallel(2).toArray(function (xs) { * // xs is ['one', 'two'] even though second function had a shorter timeout * }); * * _([enableSearch, updateSchema]).nfcall(['bucket']).toArray(callback); * // does roughly the same as * async.applyEach([enableSearch, updateSchema], 'bucket', callback); * * _([ * fs.appendFile, * fs.appendFile * ]).nfcall(['example.txt', 'hello']).series().toArray(function() { * // example.txt now contains 'hellohello' * }); * */ addMethod('nfcall', function (args) { var wrap = _.wrapCallback._relevel(bindContext(this.create, this)); return this.map(function (x) { return wrap(x).apply(x, args); }); }); /** * Ensures that only one data event is push downstream (or into the buffer) * every `ms` milliseconds, any other values are dropped. * * @id throttle * @section Transforms * @name Stream.throttle(ms) * @param {Number} ms - the minimum milliseconds between each value * @api public * * _('mousemove', document).throttle(1000); */ addMethod('throttle', function (ms) { var last = 0 - ms; return this.consume(function (err, x, push, next) { var now = new Date().getTime(); if (err) { push(err); next(); } else if (x === nil) { push(null, nil); } else if (now - ms >= last) { last = now; push(null, x); next(); } else { next(); } }); }); /** * Holds off pushing data events downstream until there has been no more * data for `ms` milliseconds. Sends the last value that occurred before * the delay, discarding all other values. * * **Implementation Note**: This transform will will not wait the full `ms` * delay to emit a pending value (if any) once it see a `nil`, as that * guarantees that there will be no more values. * * @id debounce * @section Transforms * @name Stream.debounce(ms) * @param {Number} ms - the milliseconds to wait before sending data * @api public * * function delay(x, ms, push) { * setTimeout(function () { * push(null, x); * }, ms); * } * * // sends last keyup event after user has stopped typing for 1 second * $('keyup', textbox).debounce(1000); * * // A nil triggers the emit immediately * _(function (push, next) { * delay(0, 100, push); * delay(1, 200, push); * delay(_.nil, 250, push); * }).debounce(75); * // => after 175ms => 1 * // => after 250ms (not 275ms!) => 1 2 */ addMethod('debounce', function (ms) { var t = null; var nothing = {}; var last = nothing; return this.consume(function (err, x, push, next) { if (err) { // let errors through regardless push(err); next(); } else if (x === nil) { if (t) { clearTimeout(t); } if (last !== nothing) { push(null, last); } push(null, nil); } else { last = x; if (t) { clearTimeout(t); } t = setTimeout(function () { push(null, x); }, ms); next(); } }); }); /** * Creates a new Stream, which when read from, only returns the last * seen value from the source. The source stream does not experience * back-pressure. Useful if you're using a Stream to model a changing * property which you need to query periodically. * * @id latest * @section Transforms * @name Stream.latest() * @api public * * // slowThing will always get the last known mouse position * // when it asks for more data from the mousePosition stream * mousePosition.latest().map(slowThing) */ addMethod('latest', function () { var nothing = {}, latest = nothing, errors = [], ended = false, onValue = null; this.consume(function (err, x, push, next) { if (onValue != null) { var cb = onValue; onValue = null; cb(err, x); } if (err) { errors.push(err); next(); } else if (x === nil) { ended = true; } else { latest = x; next(); } }).resume(); return this.create(function (push, next) { var oldErrors = errors; errors = []; if (!oldErrors.length && latest === nothing && !ended) { // We haven't gotten any data yet. We can't call next // because that might cause the stream to call the generator // again, resulting in an infinite loop. Thus, we stick a // a callback to be called whenever we get a value. onValue = function (err, x) { push(err, x); if (x !== nil) { next(); } }; } else { oldErrors.forEach(push); if (latest !== nothing) { push(null, latest); } if (ended) { push(null, nil); } else { next(); } } }); }); function StreamMultiplexer(stream) { this._stream = stream; this._consumers = new IntMap(); this._requests = new IntMap(); this._nonce = 0; this._emitting = false; this._repeatEmit = false; this._cached_value = null; this.paused = true; var self = this; this._pullCb = function _pullCb(err, x) { self.paused = true; if (self._requests.size === self._consumers.size) { self._send(err, x); } else { self._saved_token = [err, x]; } }; } /** * Emit downstream. The caller must guarantee that * this._consumers.size === this._requests.size. * * @param err - an error. * @param x - a value. */ StreamMultiplexer.prototype._send = function _send(err, x) { // Take a snapshot of the current request since calling the callbacks // may trigger more request to be registered. var requests = this._requests; this._requests = new IntMap(); requests.forEach(function (requestCb) { requestCb(err, x); }); }; /** * Emit if we've met the backpressure requirements. */ StreamMultiplexer.prototype._resume = function _resume() { if (this._emitting) { this._repeatEmit = true; return; } this._emitting = true; do { // use a repeat flag to avoid recursing pull() calls this._repeatEmit = false; if (this._requests.size === this._consumers.size) { if (this._saved_token) { var token = this._saved_token; this._saved_token = null; this.paused = true; this._send(token[0], token[1]); } else if (this.paused) { this.paused = false; this._stream.pull(this._pullCb); } } } while (this._repeatEmit); this._emitting = false; }; StreamMultiplexer.prototype.pull = function pull(id, cb) { if (!cb) { return; } if (this._requests.has(id)) { cb(new Error('Cannot service a second pull() request while one is in progress.')); return; } this._requests.set(id, cb); this._resume(); }; StreamMultiplexer.prototype.newStream = function newStream() { var self = this, id = self._nonce++; self._consumers.set(id, true); var generator = newDelegateGenerator(function (cb) { self.pull(id, cb); }); return new this._stream.constructor(generator) .onDestroy(function () { self.removeConsumer(id); }); }; StreamMultiplexer.prototype.removeConsumer = function removeConsumer(id) { if (!this._consumers.has(id)) { return; } this._consumers.delete(id); this._requests.delete(id); this._resume(); }; /** * Returns values from an Object as a Stream. Reads properties * lazily, so if you don't read from all keys on an object, not * all properties will be read from (may have an effect where getters * are used). * * @id values * @section Objects * @name _.values(obj) * @param {Object} obj - the object to return values from * @api public * * _.values({foo: 1, bar: 2, baz: 3}) // => 1, 2, 3 */ _.values = function (obj) { return _.keys(obj).map(function (k) { return obj[k]; }); }; /** * Returns keys from an Object as a Stream. * * @id keys * @section Objects * @name _.keys(obj) * @param {Object} obj - the object to return keys from * @api public * * _.keys({foo: 1, bar: 2, baz: 3}) // => 'foo', 'bar', 'baz' */ function keys (obj) { var keysArray = []; for (var k in obj) { if (hasOwn.call(obj, k)) { keysArray.push(k); } } return keysArray; } _.keys = function (obj) { return _(keys(obj)); }; /** * Returns key/value pairs for an Object as a Stream. Reads properties * lazily, so if you don't read from all keys on an object, not * all properties will be read from (may have an effect where getters * are used). * * @id pairs * @section Objects * @name _.pairs(obj) * @param {Object} obj - the object to return key/value pairs from * @api public * * _.pairs({foo: 1, bar: 2}) // => ['foo', 1], ['bar', 2] */ _.pairs = function (obj) { return _.keys(obj).map(function (k) { return [k, obj[k]]; }); }; /** * Extends one object with the properties of another. **Note:** The * arguments are in the reverse order of other libraries such as * underscore. This is so it follows the convention of other functions in * this library and so you can more meaningfully partially apply it. * * @id extend * @section Objects * @name _.extend(a, b) * @param {Object} a - the properties to extend b with * @param {Object} b - the original object to extend * @api public * * _.extend({name: 'bar'}, {name: 'foo', price: 20}) * // => {name: 'bar', price: 20} * * // example of partial application * var publish = _.extend({published: true}); * * publish({title: 'test post'}) * // => {title: 'test post', published: true} */ _.extend = _.curry(function (extensions, target) { for (var k in extensions) { if (hasOwn.call(extensions, k)) { target[k] = extensions[k]; } } return target; }); /** * Returns a property from an object. * * @id get * @section Objects * @name _.get(prop, obj) * @param {String} prop - the property to return * @param {Object} obj - the object to read properties from * @api public * * var obj = {foo: 'bar', baz: 123}; * _.get('foo', obj) // => 'bar' * * // making use of partial application * var posts = [ * {title: 'one'}, * {title: 'two'}, * {title: 'three'} * ]; * * _(posts).map(_.get('title')) // => 'one', 'two', 'three' */ _.get = _.curry(function (prop, obj) { return obj[prop]; }); /** * Updates a property on an object, returning the updated object. * * @id set * @section Objects * @name _.set(prop, value, obj) * @param {String} prop - the property to return * @param value - the value to set the property to * @param {Object} obj - the object to set properties on * @api public * * var obj = {foo: 'bar', baz: 123}; * _.set('foo', 'wheeee', obj) // => {foo: 'wheeee', baz: 123} * * // making use of partial application * var publish = _.set('published', true); * * publish({title: 'example'}) // => {title: 'example', published: true} */ _.set = _.curry(function (prop, val, obj) { obj[prop] = val; return obj; }); /** * Logs values to the console, a simple wrapper around `console.log` that * it suitable for passing to other functions by reference without having to * call `bind`. * * @id log * @section Utils * @name _.log(args..) * @api public * * _.log('Hello, world!'); * * _([1, 2, 3, 4]).each(_.log); */ _.log = function () { console.log.apply(console, arguments); }; /** * Wraps a node-style async function which accepts a callback, transforming * it to a function which accepts the same arguments minus the callback and * returns a Highland Stream instead. The wrapped function keeps its context, * so you can safely use it as a method without binding (see the second * example below). * * `wrapCallback` also accepts an optional `mappingHint`, which specifies how * callback arguments are pushed to the stream. This can be used to handle * non-standard callback protocols that pass back more than one value. * * `mappingHint` can be a function, number, or array. See the documentation on * [EventEmitter Stream Objects](#Stream Objects) for details on the mapping * hint. If `mappingHint` is a function, it will be called with all but the * first argument that is passed to the callback. The first is still assumed to * be the error argument. * * @id wrapCallback * @section Utils * @name _.wrapCallback(f) * @param {Function} f - the node-style function to wrap * @param {Array | Function | Number} mappingHint - (optional) how to pass the * arguments to the callback * @api public * * var fs = require('fs'); * * var readFile = _.wrapCallback(fs.readFile); * * readFile('example.txt').apply(function (data) { * // data is now the contents of example.txt * }); * * function Reader(file) { * this.file = file; * } * * Reader.prototype.read = function(cb) { * fs.readFile(this.file, cb); * }; * * Reader.prototype.readStream = _.wrapCallback(Reader.prototype.read); */ /*eslint-disable no-multi-spaces */ addToplevelMethod('wrapCallback', function (f, /*optional*/mappingHint) { /*eslint-enable no-multi-spaces */ var stream = this; var mapper = hintMapper(mappingHint); return function () { var self = this; var args = slice.call(arguments); return stream(function (push) { var cb = function (err) { if (err) { push(err); } else { var cbArgs = slice.call(arguments, 1); var v = mapper.apply(this, cbArgs); push(null, v); } push(null, nil); }; f.apply(self, args.concat([cb])); }); }; }); /** * Wraps a function that returns a promise, transforming it to a function * which accepts the same arguments and returns a Highland Stream instead. * The wrapped function keeps its context, so you can safely use it as a * method without binding. * * @id wrapAsync * @section Utils * @name _.wrapAsync(f) * @param {Function} f - the function that returns a promise * @api public * * var resolve = _.wrapAsync(Promise.resolve); * var reject = _.wrapAsync(Promise.reject); * * resolve([1, 2, 3]).apply(function (a, b, c) { * // a === 1 * // b === 2 * // c === 3 * }); * * reject('boom').errors(function (err) { * // err === 'boom' * }); */ addToplevelMethod('wrapAsync', function (f) { var stream = this; return function () { var promise; try { promise = f.apply(this, arguments); if (!_.isObject(promise) || !_.isFunction(promise.then)) { return _.fromError(new Error('Wrapped function did not return a promise')); } return stream(promise); } catch (e) { return _.fromError(e); } }; }); /** * Takes an object or a constructor function and returns that object or * constructor with streamified versions of its function properties. * Passed constructors will also have their prototype functions * streamified. This is useful for wrapping many node style async * functions at once, and for preserving those functions' context. * * @id streamifyAll * @section Utils * @name _.streamifyAll(source) * @param {Object | Function} source - the function or object with * node-style function properties. * @api public * * var fs = _.streamifyAll(require('fs')); * * fs.readFileStream('example.txt').apply(function (data) { * // data is now the contents of example.txt * }); */ function isClass (fn) { if (!(typeof fn === 'function' && fn.prototype)) { return false; } var getKeys = isES5 ? Object.getOwnPropertyNames : keys; var allKeys = getKeys(fn.prototype); return allKeys.length > 0 && !(allKeys.length === 1 && allKeys[0] === 'constructor'); } function inheritedKeys (obj) { var allProps = {}; var curr = obj; var handleProp = function (prop) { allProps[prop] = true; }; while (Object.getPrototypeOf(curr)) { var props = Object.getOwnPropertyNames(curr); props.forEach(handleProp); curr = Object.getPrototypeOf(curr); } return keys(allProps); } function streamifyAll (wrapCallback, inp, suffix) { // will not streamify inherited functions in ES3 var getKeys = isES5 ? inheritedKeys : keys; var allKeys = getKeys(inp); for (var i = 0, len = allKeys.length; i < len; i++) { var key = allKeys[i]; var val; // will skip context aware getters try { val = inp[key]; } catch (e) { // Ignore } if (val && typeof val === 'function' && !isClass(val) && !val.__HighlandStreamifiedFunction__) { var streamified = wrapCallback(val); streamified.__HighlandStreamifiedFunction__ = true; inp[key + suffix] = streamified; } } return inp; } addToplevelMethod('streamifyAll', function (arg) { if (typeof arg !== 'function' && typeof arg !== 'object') { throw new TypeError('takes an object or a constructor function'); } var suffix = 'Stream'; var ret = streamifyAll(this.wrapCallback, arg, suffix); if (isClass(arg)) { ret.prototype = streamifyAll(this.wrapCallback, arg.prototype, suffix); } return ret; }); /** * Add two values. Can be partially applied. * * @id add * @section Operators * @name _.add(a, b) * @api public * * _.add(1, 2) === 3 * _.add(1)(5) === 6 */ _.add = _.curry(function (a, b) { return a + b; }); /** * Perform logical negation on a value. If `x` is truthy then returns false, * otherwise returns true. * * @id not * @section Operators * @name _.not(x) * @param x - the value to negate * @api public * * _.not(true) // => false * _.not(false) // => true */ _.not = function (x) { return !x; }; }).call(this,require('_process')) },{"./createObserver":1,"./global":2,"./intMap":4,"./isFunction":5,"./nil":6,"./observableSubscription":7,"./queue":8,"./readableProxy":9,"_process":21,"events":12,"string_decoder":13,"util":41}],4:[function(require,module,exports){ (function (global){ var hasOwn = Object.prototype.hasOwnProperty; /** * A very simple polyfill for Map with limited functionality * that only works for integer keys. */ function IntMap() { this.map = {}; this.size = 0; } IntMap.prototype.set = function set(key, value) { if (this.has(key)) { this.map[key] = value; } else { this.map[key] = value; this.size++; } return this; }; IntMap.prototype.get = function get(key) { return this.map[key]; }; IntMap.prototype.delete = function intMapDelete(key) { var deleted = this.has(key); if (deleted) { delete this.map[key]; this.size--; } return deleted; }; IntMap.prototype.has = function has(key) { return hasOwn.call(this.map, key); }; IntMap.prototype.forEach = function forEach(f, thisArg) { for (var key in this.map) { f.call(thisArg, this.map[key], key, this); } }; if (global.Map === void 0) { module.exports = IntMap; } else { module.exports = global.Map; } }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],5:[function(require,module,exports){ /** * Predicate function takes a value and returns true if it is a function. * * @id isFunction * @name isFunction(x) * @param {any} x - Any value to test against * @returns {bool} True if x is a function */ function isFunction (x) { return typeof x === 'function'; } module.exports = isFunction; },{}],6:[function(require,module,exports){ var _global = require('./global'); /* * Resolve nil value from global namespace if it exists. This may happen when * there are multiple versions of highland (like npm). * * nil is only equal to itself: * * nil === {} => false * nil === nil => true * * This property makes it valuable for determining a lack of input from a * falsey value such as nil or undefined. When a highland stream encounters * nil it knows for sure the intention is to end the stream. */ if (!_global.nil) { _global.nil = {}; } module.exports = _global.nil; },{"./global":2}],7:[function(require,module,exports){ var nil = require('./nil'); /** * An implementation of the TC39 Subscription object * https://tc39.github.io/proposal-observable/#subscription-objects * * This class is intended for internal use only. * * Constructor takes a source highland stream, and an observer object with * an optional next, error, and complete methods. * * Returns a subscription object with a closed boolean and unsubscribe * method. * * @id ObservableSubscription * @name ObservableSubscription * @param {stream} stream - Highland stream to subscribe to * @param {object} observer - Observer to publish from stream subscription * @api private */ function ObservableSubscription (stream, observer) { var self = this; // Set attributes this._source = stream.fork(); this.closed = false; // Don't let users subscribe to an already completed stream if (stream.ended) { if (observer.error) { observer.error(new Error('Subscribe called on an already completed stream.')); } this._cleanup(); return; } // Consume the stream and emit data to the observer this._source = this._source.consume(function (err, x, push, next) { if (err) { push(null, nil); if (observer.error) { observer.error(err); } self._cleanup(); } else if (x === nil) { if (observer.complete) { observer.complete(); } self._cleanup(); } else { if (observer.next) { observer.next(x); } next(); } }); this._source.resume(); } // Instance Methods /** * Perform cleanup routine on a subscription. This can only be called once per * subscription. Once its closed the subscription cannot be cleaned up again. * * Note: This relies heavily upon side-effects and mutates itself. * * @id ObservableSubscription.prototype._cleanup(subscription) * @name ObservableSubscription.prototype._cleanup * @returns {undefined} Side-effectful function cleans up subscription * @api private */ ObservableSubscription.prototype._cleanup = function cleanup () { // Don't want to destroy\cleanup an already closed stream if (this.closed) { return; } this._source = null; this.closed = true; }; /** * Destroy the stream resources and cleanup the subscription. * @id ObservableSubscription.prototype.unsubscribe() * @name ObservableSubscription.prototype.unsubscribe() * @returns {undefined} Side-effectful. Destroys stream and cleans up subscription. * @api private */ ObservableSubscription.prototype.unsubscribe = function unsubscribe () { // Don't want to destroy\cleanup an already closed stream if (this.closed) { return; } this._source.destroy(); this._cleanup(); }; module.exports = ObservableSubscription; },{"./nil":6}],8:[function(require,module,exports){ function Queue() { this._in = []; this._out = []; this.length = 0; } /* * Enqueue all elements of a list in order. Equivalent to * list.forEach(queue.enqueue.bind(queue)); */ Queue.prototype.enqueueAll = function enqueueList(list) { this._in = this._in.concat(list); this.length += list.length; }; Queue.prototype.enqueue = function enqueue(item) { this._in.push(item); this.length++; }; Queue.prototype.dequeue = function dequeue() { if (this._out.length) { this.length--; return this._out.pop(); } else if (this._in.length) { this._out = this._in.reverse(); this._in = []; this.length--; return this._out.pop(); } else { return undefined; } }; Queue.prototype.clear = function clear() { this._out = []; this._in = []; this.length = 0; }; Queue.prototype.toArray = function toArray() { var res = []; res = res.concat(this._out); res.reverse(); res = res.concat(this._in); return res; }; Queue.prototype.toString = function toString() { return this.toArray().toString(); }; module.exports = Queue; },{}],9:[function(require,module,exports){ var inherits = require('util').inherits; var Readable = require('stream').Readable; function ReadableProxy(stream, options, nil) { Readable.call(this, options); this._source = stream; this._is_reading = false; this._nil = nil; } inherits(ReadableProxy, Readable); ReadableProxy.prototype._readOnce = function () { if (this._is_reading) { return; } var self = this; self._is_reading = true; self._source.pull(function (err, x) { self._is_reading = false; if (err) { self.emit('error', err); self._readOnce(); } else if (x === self._nil) { self.push(null); } else { if (self.push(x)) { self._readOnce(); } } }); }; ReadableProxy.prototype._read = function (ignore) { this._readOnce(); }; module.exports = ReadableProxy; },{"stream":37,"util":41}],10:[function(require,module,exports){ 'use strict' exports.byteLength = byteLength exports.toByteArray = toByteArray exports.fromByteArray = fromByteArray var lookup = [] var revLookup = [] var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' for (var i = 0, len = code.length; i < len; ++i) { lookup[i] = code[i] revLookup[code.charCodeAt(i)] = i } // Support decoding URL-safe base64 strings, as Node.js does. // See: https://en.wikipedia.org/wiki/Base64#URL_applications revLookup['-'.charCodeAt(0)] = 62 revLookup['_'.charCodeAt(0)] = 63 function placeHoldersCount (b64) { var len = b64.length if (len % 4 > 0) { throw new Error('Invalid string. Length must be a multiple of 4') } // the number of equal signs (place holders) // if there are two placeholders, than the two characters before it // represent one byte // if there is only one, then the three characters before it represent 2 bytes // this is just a cheap hack to not do indexOf twice return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0 } function byteLength (b64) { // base64 is 4/3 + up to two characters of the original data return (b64.length * 3 / 4) - placeHoldersCount(b64) } function toByteArray (b64) { var i, l, tmp, placeHolders, arr var len = b64.length placeHolders = placeHoldersCount(b64) arr = new Arr((len * 3 / 4) - placeHolders) // if there are placeholders, only get up to the last complete 4 chars l = placeHolders > 0 ? len - 4 : len var L = 0 for (i = 0; i < l; i += 4) { tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)] arr[L++] = (tmp >> 16) & 0xFF arr[L++] = (tmp >> 8) & 0xFF arr[L++] = tmp & 0xFF } if (placeHolders === 2) { tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4) arr[L++] = tmp & 0xFF } else if (placeHolders === 1) { tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2) arr[L++] = (tmp >> 8) & 0xFF arr[L++] = tmp & 0xFF } return arr } function tripletToBase64 (num) { return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] } function encodeChunk (uint8, start, end) { var tmp var output = [] for (var i = start; i < end; i += 3) { tmp = ((uint8[i] << 16) & 0xFF0000) + ((uint8[i + 1] << 8) & 0xFF00) + (uint8[i + 2] & 0xFF) output.push(tripletToBase64(tmp)) } return output.join('') } function fromByteArray (uint8) { var tmp var len = uint8.length var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes var output = '' var parts = [] var maxChunkLength = 16383 // must be multiple of 3 // go through the array every three bytes, we'll deal with trailing stuff later for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))) } // pad the end with zeros, but make sure to not forget the extra bytes if (extraBytes === 1) { tmp = uint8[len - 1] output += lookup[tmp >> 2] output += lookup[(tmp << 4) & 0x3F] output += '==' } else if (extraBytes === 2) { tmp = (uint8[len - 2] << 8) + (uint8[len - 1]) output += lookup[tmp >> 10] output += lookup[(tmp >> 4) & 0x3F] output += lookup[(tmp << 2) & 0x3F] output += '=' } parts.push(output) return parts.join('') } },{}],11:[function(require,module,exports){ },{}],12:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var objectCreate = Object.create || objectCreatePolyfill var objectKeys = Object.keys || objectKeysPolyfill var bind = Function.prototype.bind || functionBindPolyfill function EventEmitter() { if (!this._events || !Object.prototype.hasOwnProperty.call(this, '_events')) { this._events = objectCreate(null); this._eventsCount = 0; } this._maxListeners = this._maxListeners || undefined; } module.exports = EventEmitter; // Backwards-compat with node 0.10.x EventEmitter.EventEmitter = EventEmitter; EventEmitter.prototype._events = undefined; EventEmitter.prototype._maxListeners = undefined; // By default EventEmitters will print a warning if more than 10 listeners are // added to it. This is a useful default which helps finding memory leaks. var defaultMaxListeners = 10; var hasDefineProperty; try { var o = {}; if (Object.defineProperty) Object.defineProperty(o, 'x', { value: 0 }); hasDefineProperty = o.x === 0; } catch (err) { hasDefineProperty = false } if (hasDefineProperty) { Object.defineProperty(EventEmitter, 'defaultMaxListeners', { enumerable: true, get: function() { return defaultMaxListeners; }, set: function(arg) { // check whether the input is a positive number (whose value is zero or // greater and not a NaN). if (typeof arg !== 'number' || arg < 0 || arg !== arg) throw new TypeError('"defaultMaxListeners" must be a positive number'); defaultMaxListeners = arg; } }); } else { EventEmitter.defaultMaxListeners = defaultMaxListeners; } // Obviously not all Emitters should be limited to 10. This function allows // that to be increased. Set to zero for unlimited. EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) { if (typeof n !== 'number' || n < 0 || isNaN(n)) throw new TypeError('"n" argument must be a positive number'); this._maxListeners = n; return this; }; function $getMaxListeners(that) { if (that._maxListeners === undefined) return EventEmitter.defaultMaxListeners; return that._maxListeners; } EventEmitter.prototype.getMaxListeners = function getMaxListeners() { return $getMaxListeners(this); }; // These standalone emit* functions are used to optimize calling of event // handlers for fast cases because emit() itself often has a variable number of // arguments and can be deoptimized because of that. These functions always have // the same number of arguments and thus do not get deoptimized, so the code // inside them can execute faster. function emitNone(handler, isFn, self) { if (isFn) handler.call(self); else { var len = handler.length; var listeners = arrayClone(handler, len); for (var i = 0; i < len; ++i) listeners[i].call(self); } } function emitOne(handler, isFn, self, arg1) { if (isFn) handler.call(self, arg1); else { var len = handler.length; var listeners = arrayClone(handler, len); for (var i = 0; i < len; ++i) listeners[i].call(self, arg1); } } function emitTwo(handler, isFn, self, arg1, arg2) { if (isFn) handler.call(self, arg1, arg2); else { var len = handler.length; var listeners = arrayClone(handler, len); for (var i = 0; i < len; ++i) listeners[i].call(self, arg1, arg2); } } function emitThree(handler, isFn, self, arg1, arg2, arg3) { if (isFn) handler.call(self, arg1, arg2, arg3); else { var len = handler.length; var listeners = arrayClone(handler, len); for (var i = 0; i < len; ++i) listeners[i].call(self, arg1, arg2, arg3); } } function emitMany(handler, isFn, self, args) { if (isFn) handler.apply(self, args); else { var len = handler.length; var listeners = arrayClone(handler, len); for (var i = 0; i < len; ++i) listeners[i].apply(self, args); } } EventEmitter.prototype.emit = function emit(type) { var er, handler, len, args, i, events; var doError = (type === 'error'); events = this._events; if (events) doError = (doError && events.error == null); else if (!doError) return false; // If there is no 'error' event listener then throw. if (doError) { if (arguments.length > 1) er = arguments[1]; if (er instanceof Error) { throw er; // Unhandled 'error' event } else { // At least give some kind of context to the user var err = new Error('Unhandled "error" event. (' + er + ')'); err.context = er; throw err; } return false; } handler = events[type]; if (!handler) return false; var isFn = typeof handler === 'function'; len = arguments.length; switch (len) { // fast cases case 1: emitNone(handler, isFn, this); break; case 2: emitOne(handler, isFn, this, arguments[1]); break; case 3: emitTwo(handler, isFn, this, arguments[1], arguments[2]); break; case 4: emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]); break; // slower default: args = new Array(len - 1); for (i = 1; i < len; i++) args[i - 1] = arguments[i]; emitMany(handler, isFn, this, args); } return true; }; function _addListener(target, type, listener, prepend) { var m; var events; var existing; if (typeof listener !== 'function') throw new TypeError('"listener" argument must be a function'); events = target._events; if (!events) { events = target._events = objectCreate(null); target._eventsCount = 0; } else { // To avoid recursion in the case that type === "newListener"! Before // adding it to the listeners, first emit "newListener". if (events.newListener) { target.emit('newListener', type, listener.listener ? listener.listener : listener); // Re-assign `events` because a newListener handler could have caused the // this._events to be assigned to a new object events = target._events; } existing = events[type]; } if (!existing) { // Optimize the case of one listener. Don't need the extra array object. existing = events[type] = listener; ++target._eventsCount; } else { if (typeof existing === 'function') { // Adding the second element, need to change to array. existing = events[type] = prepend ? [listener, existing] : [existing, listener]; } else { // If we've already got an array, just append. if (prepend) { existing.unshift(listener); } else { existing.push(listener); } } // Check for listener leak if (!existing.warned) { m = $getMaxListeners(target); if (m && m > 0 && existing.length > m) { existing.warned = true; var w = new Error('Possible EventEmitter memory leak detected. ' + existing.length + ' "' + String(type) + '" listeners ' + 'added. Use emitter.setMaxListeners() to ' + 'increase limit.'); w.name = 'MaxListenersExceededWarning'; w.emitter = target; w.type = type; w.count = existing.length; if (typeof console === 'object' && console.warn) { console.warn('%s: %s', w.name, w.message); } } } } return target; } EventEmitter.prototype.addListener = function addListener(type, listener) { return _addListener(this, type, listener, false); }; EventEmitter.prototype.on = EventEmitter.prototype.addListener; EventEmitter.prototype.prependListener = function prependListener(type, listener) { return _addListener(this, type, listener, true); }; function onceWrapper() { if (!this.fired) { this.target.removeListener(this.type, this.wrapFn); this.fired = true; switch (arguments.length) { case 0: return this.listener.call(this.target); case 1: return this.listener.call(this.target, arguments[0]); case 2: return this.listener.call(this.target, arguments[0], arguments[1]); case 3: return this.listener.call(this.target, arguments[0], arguments[1], arguments[2]); default: var args = new Array(arguments.length); for (var i = 0; i < args.length; ++i) args[i] = arguments[i]; this.listener.apply(this.target, args); } } } function _onceWrap(target, type, listener) { var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener }; var wrapped = bind.call(onceWrapper, state); wrapped.listener = listener; state.wrapFn = wrapped; return wrapped; } EventEmitter.prototype.once = function once(type, listener) { if (typeof listener !== 'function') throw new TypeError('"listener" argument must be a function'); this.on(type, _onceWrap(this, type, listener)); return this; }; EventEmitter.prototype.prependOnceListener = function prependOnceListener(type, listener) { if (typeof listener !== 'function') throw new TypeError('"listener" argument must be a function'); this.prependListener(type, _onceWrap(this, type, listener)); return this; }; // Emits a 'removeListener' event if and only if the listener was removed. EventEmitter.prototype.removeListener = function removeListener(type, listener) { var list, events, position, i, originalListener; if (typeof listener !== 'function') throw new TypeError('"listener" argument must be a function'); events = this._events; if (!events) return this; list = events[type]; if (!list) return this; if (list === listener || list.listener === listener) { if (--this._eventsCount === 0) this._events = objectCreate(null); else { delete events[type]; if (events.removeListener) this.emit('removeListener', type, list.listener || listener); } } else if (typeof list !== 'function') { position = -1; for (i = list.length - 1; i >= 0; i--) { if (list[i] === listener || list[i].listener === listener) { originalListener = list[i].listener; position = i; break; } } if (position < 0) return this; if (position === 0) list.shift(); else spliceOne(list, position); if (list.length === 1) events[type] = list[0]; if (events.removeListener) this.emit('removeListener', type, originalListener || listener); } return this; }; EventEmitter.prototype.removeAllListeners = function removeAllListeners(type) { var listeners, events, i; events = this._events; if (!events) return this; // not listening for removeListener, no need to emit if (!events.removeListener) { if (arguments.length === 0) { this._events = objectCreate(null); this._eventsCount = 0; } else if (events[type]) { if (--this._eventsCount === 0) this._events = objectCreate(null); else delete events[type]; } return this; } // emit removeListener for all listeners on all events if (arguments.length === 0) { var keys = objectKeys(events); var key; for (i = 0; i < keys.length; ++i) { key = keys[i]; if (key === 'removeListener') continue; this.removeAllListeners(key); } this.removeAllListeners('removeListener'); this._events = objectCreate(null); this._eventsCount = 0; return this; } listeners = events[type]; if (typeof listeners === 'function') { this.removeListener(type, listeners); } else if (listeners) { // LIFO order for (i = listeners.length - 1; i >= 0; i--) { this.removeListener(type, listeners[i]); } } return this; }; function _listeners(target, type, unwrap) { var events = target._events; if (!events) return []; var evlistener = events[type]; if (!evlistener) return []; if (typeof evlistener === 'function') return unwrap ? [evlistener.listener || evlistener] : [evlistener]; return unwrap ? unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length); } EventEmitter.prototype.listeners = function listeners(type) { return _listeners(this, type, true); }; EventEmitter.prototype.rawListeners = function rawListeners(type) { return _listeners(this, type, false); }; EventEmitter.listenerCount = function(emitter, type) { if (typeof emitter.listenerCount === 'function') { return emitter.listenerCount(type); } else { return listenerCount.call(emitter, type); } }; EventEmitter.prototype.listenerCount = listenerCount; function listenerCount(type) { var events = this._events; if (events) { var evlistener = events[type]; if (typeof evlistener === 'function') { return 1; } else if (evlistener) { return evlistener.length; } } return 0; } EventEmitter.prototype.eventNames = function eventNames() { return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : []; }; // About 1.5x faster than the two-arg version of Array#splice(). function spliceOne(list, index) { for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1) list[i] = list[k]; list.pop(); } function arrayClone(arr, n) { var copy = new Array(n); for (var i = 0; i < n; ++i) copy[i] = arr[i]; return copy; } function unwrapListeners(arr) { var ret = new Array(arr.length); for (var i = 0; i < ret.length; ++i) { ret[i] = arr[i].listener || arr[i]; } return ret; } function objectCreatePolyfill(proto) { var F = function() {}; F.prototype = proto; return new F; } function objectKeysPolyfill(obj) { var keys = []; for (var k in obj) if (Object.prototype.hasOwnProperty.call(obj, k)) { keys.push(k); } return k; } function functionBindPolyfill(context) { var fn = this; return function () { return fn.apply(context, arguments); }; } },{}],13:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. 'use strict'; /**/ var Buffer = require('safe-buffer').Buffer; /**/ var isEncoding = Buffer.isEncoding || function (encoding) { encoding = '' + encoding; switch (encoding && encoding.toLowerCase()) { case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw': return true; default: return false; } }; function _normalizeEncoding(enc) { if (!enc) return 'utf8'; var retried; while (true) { switch (enc) { case 'utf8': case 'utf-8': return 'utf8'; case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return 'utf16le'; case 'latin1': case 'binary': return 'latin1'; case 'base64': case 'ascii': case 'hex': return enc; default: if (retried) return; // undefined enc = ('' + enc).toLowerCase(); retried = true; } } }; // Do not cache `Buffer.isEncoding` when checking encoding names as some // modules monkey-patch it to support additional encodings function normalizeEncoding(enc) { var nenc = _normalizeEncoding(enc); if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc); return nenc || enc; } // StringDecoder provides an interface for efficiently splitting a series of // buffers into a series of JS strings without breaking apart multi-byte // characters. exports.StringDecoder = StringDecoder; function StringDecoder(encoding) { this.encoding = normalizeEncoding(encoding); var nb; switch (this.encoding) { case 'utf16le': this.text = utf16Text; this.end = utf16End; nb = 4; break; case 'utf8': this.fillLast = utf8FillLast; nb = 4; break; case 'base64': this.text = base64Text; this.end = base64End; nb = 3; break; default: this.write = simpleWrite; this.end = simpleEnd; return; } this.lastNeed = 0; this.lastTotal = 0; this.lastChar = Buffer.allocUnsafe(nb); } StringDecoder.prototype.write = function (buf) { if (buf.length === 0) return ''; var r; var i; if (this.lastNeed) { r = this.fillLast(buf); if (r === undefined) return ''; i = this.lastNeed; this.lastNeed = 0; } else { i = 0; } if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i); return r || ''; }; StringDecoder.prototype.end = utf8End; // Returns only complete characters in a Buffer StringDecoder.prototype.text = utf8Text; // Attempts to complete a partial non-UTF-8 character using bytes from a Buffer StringDecoder.prototype.fillLast = function (buf) { if (this.lastNeed <= buf.length) { buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed); return this.lastChar.toString(this.encoding, 0, this.lastTotal); } buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length); this.lastNeed -= buf.length; }; // Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a // continuation byte. If an invalid byte is detected, -2 is returned. function utf8CheckByte(byte) { if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4; return byte >> 6 === 0x02 ? -1 : -2; } // Checks at most 3 bytes at the end of a Buffer in order to detect an // incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4) // needed to complete the UTF-8 character (if applicable) are returned. function utf8CheckIncomplete(self, buf, i) { var j = buf.length - 1; if (j < i) return 0; var nb = utf8CheckByte(buf[j]); if (nb >= 0) { if (nb > 0) self.lastNeed = nb - 1; return nb; } if (--j < i || nb === -2) return 0; nb = utf8CheckByte(buf[j]); if (nb >= 0) { if (nb > 0) self.lastNeed = nb - 2; return nb; } if (--j < i || nb === -2) return 0; nb = utf8CheckByte(buf[j]); if (nb >= 0) { if (nb > 0) { if (nb === 2) nb = 0;else self.lastNeed = nb - 3; } return nb; } return 0; } // Validates as many continuation bytes for a multi-byte UTF-8 character as // needed or are available. If we see a non-continuation byte where we expect // one, we "replace" the validated continuation bytes we've seen so far with // a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding // behavior. The continuation byte check is included three times in the case // where all of the continuation bytes for a character exist in the same buffer. // It is also done this way as a slight performance increase instead of using a // loop. function utf8CheckExtraBytes(self, buf, p) { if ((buf[0] & 0xC0) !== 0x80) { self.lastNeed = 0; return '\ufffd'; } if (self.lastNeed > 1 && buf.length > 1) { if ((buf[1] & 0xC0) !== 0x80) { self.lastNeed = 1; return '\ufffd'; } if (self.lastNeed > 2 && buf.length > 2) { if ((buf[2] & 0xC0) !== 0x80) { self.lastNeed = 2; return '\ufffd'; } } } } // Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer. function utf8FillLast(buf) { var p = this.lastTotal - this.lastNeed; var r = utf8CheckExtraBytes(this, buf, p); if (r !== undefined) return r; if (this.lastNeed <= buf.length) { buf.copy(this.lastChar, p, 0, this.lastNeed); return this.lastChar.toString(this.encoding, 0, this.lastTotal); } buf.copy(this.lastChar, p, 0, buf.length); this.lastNeed -= buf.length; } // Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a // partial character, the character's bytes are buffered until the required // number of bytes are available. function utf8Text(buf, i) { var total = utf8CheckIncomplete(this, buf, i); if (!this.lastNeed) return buf.toString('utf8', i); this.lastTotal = total; var end = buf.length - (total - this.lastNeed); buf.copy(this.lastChar, 0, end); return buf.toString('utf8', i, end); } // For UTF-8, a replacement character is added when ending on a partial // character. function utf8End(buf) { var r = buf && buf.length ? this.write(buf) : ''; if (this.lastNeed) return r + '\ufffd'; return r; } // UTF-16LE typically needs two bytes per character, but even if we have an even // number of bytes available, we need to check if we end on a leading/high // surrogate. In that case, we need to wait for the next two bytes in order to // decode the last character properly. function utf16Text(buf, i) { if ((buf.length - i) % 2 === 0) { var r = buf.toString('utf16le', i); if (r) { var c = r.charCodeAt(r.length - 1); if (c >= 0xD800 && c <= 0xDBFF) { this.lastNeed = 2; this.lastTotal = 4; this.lastChar[0] = buf[buf.length - 2]; this.lastChar[1] = buf[buf.length - 1]; return r.slice(0, -1); } } return r; } this.lastNeed = 1; this.lastTotal = 2; this.lastChar[0] = buf[buf.length - 1]; return buf.toString('utf16le', i, buf.length - 1); } // For UTF-16LE we do not explicitly append special replacement characters if we // end on a partial character, we simply let v8 handle that. function utf16End(buf) { var r = buf && buf.length ? this.write(buf) : ''; if (this.lastNeed) { var end = this.lastTotal - this.lastNeed; return r + this.lastChar.toString('utf16le', 0, end); } return r; } function base64Text(buf, i) { var n = (buf.length - i) % 3; if (n === 0) return buf.toString('base64', i); this.lastNeed = 3 - n; this.lastTotal = 3; if (n === 1) { this.lastChar[0] = buf[buf.length - 1]; } else { this.lastChar[0] = buf[buf.length - 2]; this.lastChar[1] = buf[buf.length - 1]; } return buf.toString('base64', i, buf.length - n); } function base64End(buf) { var r = buf && buf.length ? this.write(buf) : ''; if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed); return r; } // Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) function simpleWrite(buf) { return buf.toString(this.encoding); } function simpleEnd(buf) { return buf && buf.length ? this.write(buf) : ''; } },{"safe-buffer":36}],14:[function(require,module,exports){ /*! * The buffer module from node.js, for the browser. * * @author Feross Aboukhadijeh * @license MIT */ /* eslint-disable no-proto */ 'use strict' var base64 = require('base64-js') var ieee754 = require('ieee754') exports.Buffer = Buffer exports.SlowBuffer = SlowBuffer exports.INSPECT_MAX_BYTES = 50 var K_MAX_LENGTH = 0x7fffffff exports.kMaxLength = K_MAX_LENGTH /** * If `Buffer.TYPED_ARRAY_SUPPORT`: * === true Use Uint8Array implementation (fastest) * === false Print warning and recommend using `buffer` v4.x which has an Object * implementation (most compatible, even IE6) * * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, * Opera 11.6+, iOS 4.2+. * * We report that the browser does not support typed arrays if the are not subclassable * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array` * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support * for __proto__ and has a buggy typed array implementation. */ Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport() if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' && typeof console.error === 'function') { console.error( 'This browser lacks typed array (Uint8Array) support which is required by ' + '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.' ) } function typedArraySupport () { // Can typed array instances can be augmented? try { var arr = new Uint8Array(1) arr.__proto__ = { __proto__: Uint8Array.prototype, foo: function () { return 42 } } return arr.foo() === 42 } catch (e) { return false } } Object.defineProperty(Buffer.prototype, 'parent', { enumerable: true, get: function () { if (!Buffer.isBuffer(this)) return undefined return this.buffer } }) Object.defineProperty(Buffer.prototype, 'offset', { enumerable: true, get: function () { if (!Buffer.isBuffer(this)) return undefined return this.byteOffset } }) function createBuffer (length) { if (length > K_MAX_LENGTH) { throw new RangeError('The value "' + length + '" is invalid for option "size"') } // Return an augmented `Uint8Array` instance var buf = new Uint8Array(length) buf.__proto__ = Buffer.prototype return buf } /** * The Buffer constructor returns instances of `Uint8Array` that have their * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of * `Uint8Array`, so the returned instances will have all the node `Buffer` methods * and the `Uint8Array` methods. Square bracket notation works as expected -- it * returns a single octet. * * The `Uint8Array` prototype remains unmodified. */ function Buffer (arg, encodingOrOffset, length) { // Common case. if (typeof arg === 'number') { if (typeof encodingOrOffset === 'string') { throw new TypeError( 'The "string" argument must be of type string. Received type number' ) } return allocUnsafe(arg) } return from(arg, encodingOrOffset, length) } // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 if (typeof Symbol !== 'undefined' && Symbol.species != null && Buffer[Symbol.species] === Buffer) { Object.defineProperty(Buffer, Symbol.species, { value: null, configurable: true, enumerable: false, writable: false }) } Buffer.poolSize = 8192 // not used by this implementation function from (value, encodingOrOffset, length) { if (typeof value === 'string') { return fromString(value, encodingOrOffset) } if (ArrayBuffer.isView(value)) { return fromArrayLike(value) } if (value == null) { throw TypeError( 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + 'or Array-like Object. Received type ' + (typeof value) ) } if (isInstance(value, ArrayBuffer) || (value && isInstance(value.buffer, ArrayBuffer))) { return fromArrayBuffer(value, encodingOrOffset, length) } if (typeof value === 'number') { throw new TypeError( 'The "value" argument must not be of type number. Received type number' ) } var valueOf = value.valueOf && value.valueOf() if (valueOf != null && valueOf !== value) { return Buffer.from(valueOf, encodingOrOffset, length) } var b = fromObject(value) if (b) return b if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null && typeof value[Symbol.toPrimitive] === 'function') { return Buffer.from( value[Symbol.toPrimitive]('string'), encodingOrOffset, length ) } throw new TypeError( 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + 'or Array-like Object. Received type ' + (typeof value) ) } /** * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError * if value is a number. * Buffer.from(str[, encoding]) * Buffer.from(array) * Buffer.from(buffer) * Buffer.from(arrayBuffer[, byteOffset[, length]]) **/ Buffer.from = function (value, encodingOrOffset, length) { return from(value, encodingOrOffset, length) } // Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug: // https://github.com/feross/buffer/pull/148 Buffer.prototype.__proto__ = Uint8Array.prototype Buffer.__proto__ = Uint8Array function assertSize (size) { if (typeof size !== 'number') { throw new TypeError('"size" argument must be of type number') } else if (size < 0) { throw new RangeError('The value "' + size + '" is invalid for option "size"') } } function alloc (size, fill, encoding) { assertSize(size) if (size <= 0) { return createBuffer(size) } if (fill !== undefined) { // Only pay attention to encoding if it's a string. This // prevents accidentally sending in a number that would // be interpretted as a start offset. return typeof encoding === 'string' ? createBuffer(size).fill(fill, encoding) : createBuffer(size).fill(fill) } return createBuffer(size) } /** * Creates a new filled Buffer instance. * alloc(size[, fill[, encoding]]) **/ Buffer.alloc = function (size, fill, encoding) { return alloc(size, fill, encoding) } function allocUnsafe (size) { assertSize(size) return createBuffer(size < 0 ? 0 : checked(size) | 0) } /** * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. * */ Buffer.allocUnsafe = function (size) { return allocUnsafe(size) } /** * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. */ Buffer.allocUnsafeSlow = function (size) { return allocUnsafe(size) } function fromString (string, encoding) { if (typeof encoding !== 'string' || encoding === '') { encoding = 'utf8' } if (!Buffer.isEncoding(encoding)) { throw new TypeError('Unknown encoding: ' + encoding) } var length = byteLength(string, encoding) | 0 var buf = createBuffer(length) var actual = buf.write(string, encoding) if (actual !== length) { // Writing a hex string, for example, that contains invalid characters will // cause everything after the first invalid character to be ignored. (e.g. // 'abxxcd' will be treated as 'ab') buf = buf.slice(0, actual) } return buf } function fromArrayLike (array) { var length = array.length < 0 ? 0 : checked(array.length) | 0 var buf = createBuffer(length) for (var i = 0; i < length; i += 1) { buf[i] = array[i] & 255 } return buf } function fromArrayBuffer (array, byteOffset, length) { if (byteOffset < 0 || array.byteLength < byteOffset) { throw new RangeError('"offset" is outside of buffer bounds') } if (array.byteLength < byteOffset + (length || 0)) { throw new RangeError('"length" is outside of buffer bounds') } var buf if (byteOffset === undefined && length === undefined) { buf = new Uint8Array(array) } else if (length === undefined) { buf = new Uint8Array(array, byteOffset) } else { buf = new Uint8Array(array, byteOffset, length) } // Return an augmented `Uint8Array` instance buf.__proto__ = Buffer.prototype return buf } function fromObject (obj) { if (Buffer.isBuffer(obj)) { var len = checked(obj.length) | 0 var buf = createBuffer(len) if (buf.length === 0) { return buf } obj.copy(buf, 0, 0, len) return buf } if (obj.length !== undefined) { if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) { return createBuffer(0) } return fromArrayLike(obj) } if (obj.type === 'Buffer' && Array.isArray(obj.data)) { return fromArrayLike(obj.data) } } function checked (length) { // Note: cannot use `length < K_MAX_LENGTH` here because that fails when // length is NaN (which is otherwise coerced to zero.) if (length >= K_MAX_LENGTH) { throw new RangeError('Attempt to allocate Buffer larger than maximum ' + 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes') } return length | 0 } function SlowBuffer (length) { if (+length != length) { // eslint-disable-line eqeqeq length = 0 } return Buffer.alloc(+length) } Buffer.isBuffer = function isBuffer (b) { return b != null && b._isBuffer === true && b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false } Buffer.compare = function compare (a, b) { if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength) if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength) if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { throw new TypeError( 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array' ) } if (a === b) return 0 var x = a.length var y = b.length for (var i = 0, len = Math.min(x, y); i < len; ++i) { if (a[i] !== b[i]) { x = a[i] y = b[i] break } } if (x < y) return -1 if (y < x) return 1 return 0 } Buffer.isEncoding = function isEncoding (encoding) { switch (String(encoding).toLowerCase()) { case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'latin1': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return true default: return false } } Buffer.concat = function concat (list, length) { if (!Array.isArray(list)) { throw new TypeError('"list" argument must be an Array of Buffers') } if (list.length === 0) { return Buffer.alloc(0) } var i if (length === undefined) { length = 0 for (i = 0; i < list.length; ++i) { length += list[i].length } } var buffer = Buffer.allocUnsafe(length) var pos = 0 for (i = 0; i < list.length; ++i) { var buf = list[i] if (isInstance(buf, Uint8Array)) { buf = Buffer.from(buf) } if (!Buffer.isBuffer(buf)) { throw new TypeError('"list" argument must be an Array of Buffers') } buf.copy(buffer, pos) pos += buf.length } return buffer } function byteLength (string, encoding) { if (Buffer.isBuffer(string)) { return string.length } if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) { return string.byteLength } if (typeof string !== 'string') { throw new TypeError( 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' + 'Received type ' + typeof string ) } var len = string.length var mustMatch = (arguments.length > 2 && arguments[2] === true) if (!mustMatch && len === 0) return 0 // Use a for loop to avoid recursion var loweredCase = false for (;;) { switch (encoding) { case 'ascii': case 'latin1': case 'binary': return len case 'utf8': case 'utf-8': return utf8ToBytes(string).length case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return len * 2 case 'hex': return len >>> 1 case 'base64': return base64ToBytes(string).length default: if (loweredCase) { return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8 } encoding = ('' + encoding).toLowerCase() loweredCase = true } } } Buffer.byteLength = byteLength function slowToString (encoding, start, end) { var loweredCase = false // No need to verify that "this.length <= MAX_UINT32" since it's a read-only // property of a typed array. // This behaves neither like String nor Uint8Array in that we set start/end // to their upper/lower bounds if the value passed is out of range. // undefined is handled specially as per ECMA-262 6th Edition, // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. if (start === undefined || start < 0) { start = 0 } // Return early if start > this.length. Done here to prevent potential uint32 // coercion fail below. if (start > this.length) { return '' } if (end === undefined || end > this.length) { end = this.length } if (end <= 0) { return '' } // Force coersion to uint32. This will also coerce falsey/NaN values to 0. end >>>= 0 start >>>= 0 if (end <= start) { return '' } if (!encoding) encoding = 'utf8' while (true) { switch (encoding) { case 'hex': return hexSlice(this, start, end) case 'utf8': case 'utf-8': return utf8Slice(this, start, end) case 'ascii': return asciiSlice(this, start, end) case 'latin1': case 'binary': return latin1Slice(this, start, end) case 'base64': return base64Slice(this, start, end) case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return utf16leSlice(this, start, end) default: if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) encoding = (encoding + '').toLowerCase() loweredCase = true } } } // This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package) // to detect a Buffer instance. It's not possible to use `instanceof Buffer` // reliably in a browserify context because there could be multiple different // copies of the 'buffer' package in use. This method works even for Buffer // instances that were created from another copy of the `buffer` package. // See: https://github.com/feross/buffer/issues/154 Buffer.prototype._isBuffer = true function swap (b, n, m) { var i = b[n] b[n] = b[m] b[m] = i } Buffer.prototype.swap16 = function swap16 () { var len = this.length if (len % 2 !== 0) { throw new RangeError('Buffer size must be a multiple of 16-bits') } for (var i = 0; i < len; i += 2) { swap(this, i, i + 1) } return this } Buffer.prototype.swap32 = function swap32 () { var len = this.length if (len % 4 !== 0) { throw new RangeError('Buffer size must be a multiple of 32-bits') } for (var i = 0; i < len; i += 4) { swap(this, i, i + 3) swap(this, i + 1, i + 2) } return this } Buffer.prototype.swap64 = function swap64 () { var len = this.length if (len % 8 !== 0) { throw new RangeError('Buffer size must be a multiple of 64-bits') } for (var i = 0; i < len; i += 8) { swap(this, i, i + 7) swap(this, i + 1, i + 6) swap(this, i + 2, i + 5) swap(this, i + 3, i + 4) } return this } Buffer.prototype.toString = function toString () { var length = this.length if (length === 0) return '' if (arguments.length === 0) return utf8Slice(this, 0, length) return slowToString.apply(this, arguments) } Buffer.prototype.toLocaleString = Buffer.prototype.toString Buffer.prototype.equals = function equals (b) { if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') if (this === b) return true return Buffer.compare(this, b) === 0 } Buffer.prototype.inspect = function inspect () { var str = '' var max = exports.INSPECT_MAX_BYTES str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim() if (this.length > max) str += ' ... ' return '' } Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { if (isInstance(target, Uint8Array)) { target = Buffer.from(target, target.offset, target.byteLength) } if (!Buffer.isBuffer(target)) { throw new TypeError( 'The "target" argument must be one of type Buffer or Uint8Array. ' + 'Received type ' + (typeof target) ) } if (start === undefined) { start = 0 } if (end === undefined) { end = target ? target.length : 0 } if (thisStart === undefined) { thisStart = 0 } if (thisEnd === undefined) { thisEnd = this.length } if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { throw new RangeError('out of range index') } if (thisStart >= thisEnd && start >= end) { return 0 } if (thisStart >= thisEnd) { return -1 } if (start >= end) { return 1 } start >>>= 0 end >>>= 0 thisStart >>>= 0 thisEnd >>>= 0 if (this === target) return 0 var x = thisEnd - thisStart var y = end - start var len = Math.min(x, y) var thisCopy = this.slice(thisStart, thisEnd) var targetCopy = target.slice(start, end) for (var i = 0; i < len; ++i) { if (thisCopy[i] !== targetCopy[i]) { x = thisCopy[i] y = targetCopy[i] break } } if (x < y) return -1 if (y < x) return 1 return 0 } // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, // OR the last index of `val` in `buffer` at offset <= `byteOffset`. // // Arguments: // - buffer - a Buffer to search // - val - a string, Buffer, or number // - byteOffset - an index into `buffer`; will be clamped to an int32 // - encoding - an optional encoding, relevant is val is a string // - dir - true for indexOf, false for lastIndexOf function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { // Empty buffer means no match if (buffer.length === 0) return -1 // Normalize byteOffset if (typeof byteOffset === 'string') { encoding = byteOffset byteOffset = 0 } else if (byteOffset > 0x7fffffff) { byteOffset = 0x7fffffff } else if (byteOffset < -0x80000000) { byteOffset = -0x80000000 } byteOffset = +byteOffset // Coerce to Number. if (numberIsNaN(byteOffset)) { // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer byteOffset = dir ? 0 : (buffer.length - 1) } // Normalize byteOffset: negative offsets start from the end of the buffer if (byteOffset < 0) byteOffset = buffer.length + byteOffset if (byteOffset >= buffer.length) { if (dir) return -1 else byteOffset = buffer.length - 1 } else if (byteOffset < 0) { if (dir) byteOffset = 0 else return -1 } // Normalize val if (typeof val === 'string') { val = Buffer.from(val, encoding) } // Finally, search either indexOf (if dir is true) or lastIndexOf if (Buffer.isBuffer(val)) { // Special case: looking for empty string/buffer always fails if (val.length === 0) { return -1 } return arrayIndexOf(buffer, val, byteOffset, encoding, dir) } else if (typeof val === 'number') { val = val & 0xFF // Search for a byte value [0-255] if (typeof Uint8Array.prototype.indexOf === 'function') { if (dir) { return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) } else { return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) } } return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) } throw new TypeError('val must be string, number or Buffer') } function arrayIndexOf (arr, val, byteOffset, encoding, dir) { var indexSize = 1 var arrLength = arr.length var valLength = val.length if (encoding !== undefined) { encoding = String(encoding).toLowerCase() if (encoding === 'ucs2' || encoding === 'ucs-2' || encoding === 'utf16le' || encoding === 'utf-16le') { if (arr.length < 2 || val.length < 2) { return -1 } indexSize = 2 arrLength /= 2 valLength /= 2 byteOffset /= 2 } } function read (buf, i) { if (indexSize === 1) { return buf[i] } else { return buf.readUInt16BE(i * indexSize) } } var i if (dir) { var foundIndex = -1 for (i = byteOffset; i < arrLength; i++) { if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { if (foundIndex === -1) foundIndex = i if (i - foundIndex + 1 === valLength) return foundIndex * indexSize } else { if (foundIndex !== -1) i -= i - foundIndex foundIndex = -1 } } } else { if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength for (i = byteOffset; i >= 0; i--) { var found = true for (var j = 0; j < valLength; j++) { if (read(arr, i + j) !== read(val, j)) { found = false break } } if (found) return i } } return -1 } Buffer.prototype.includes = function includes (val, byteOffset, encoding) { return this.indexOf(val, byteOffset, encoding) !== -1 } Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { return bidirectionalIndexOf(this, val, byteOffset, encoding, true) } Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { return bidirectionalIndexOf(this, val, byteOffset, encoding, false) } function hexWrite (buf, string, offset, length) { offset = Number(offset) || 0 var remaining = buf.length - offset if (!length) { length = remaining } else { length = Number(length) if (length > remaining) { length = remaining } } var strLen = string.length if (length > strLen / 2) { length = strLen / 2 } for (var i = 0; i < length; ++i) { var parsed = parseInt(string.substr(i * 2, 2), 16) if (numberIsNaN(parsed)) return i buf[offset + i] = parsed } return i } function utf8Write (buf, string, offset, length) { return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) } function asciiWrite (buf, string, offset, length) { return blitBuffer(asciiToBytes(string), buf, offset, length) } function latin1Write (buf, string, offset, length) { return asciiWrite(buf, string, offset, length) } function base64Write (buf, string, offset, length) { return blitBuffer(base64ToBytes(string), buf, offset, length) } function ucs2Write (buf, string, offset, length) { return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) } Buffer.prototype.write = function write (string, offset, length, encoding) { // Buffer#write(string) if (offset === undefined) { encoding = 'utf8' length = this.length offset = 0 // Buffer#write(string, encoding) } else if (length === undefined && typeof offset === 'string') { encoding = offset length = this.length offset = 0 // Buffer#write(string, offset[, length][, encoding]) } else if (isFinite(offset)) { offset = offset >>> 0 if (isFinite(length)) { length = length >>> 0 if (encoding === undefined) encoding = 'utf8' } else { encoding = length length = undefined } } else { throw new Error( 'Buffer.write(string, encoding, offset[, length]) is no longer supported' ) } var remaining = this.length - offset if (length === undefined || length > remaining) length = remaining if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { throw new RangeError('Attempt to write outside buffer bounds') } if (!encoding) encoding = 'utf8' var loweredCase = false for (;;) { switch (encoding) { case 'hex': return hexWrite(this, string, offset, length) case 'utf8': case 'utf-8': return utf8Write(this, string, offset, length) case 'ascii': return asciiWrite(this, string, offset, length) case 'latin1': case 'binary': return latin1Write(this, string, offset, length) case 'base64': // Warning: maxLength not taken into account in base64Write return base64Write(this, string, offset, length) case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return ucs2Write(this, string, offset, length) default: if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) encoding = ('' + encoding).toLowerCase() loweredCase = true } } } Buffer.prototype.toJSON = function toJSON () { return { type: 'Buffer', data: Array.prototype.slice.call(this._arr || this, 0) } } function base64Slice (buf, start, end) { if (start === 0 && end === buf.length) { return base64.fromByteArray(buf) } else { return base64.fromByteArray(buf.slice(start, end)) } } function utf8Slice (buf, start, end) { end = Math.min(buf.length, end) var res = [] var i = start while (i < end) { var firstByte = buf[i] var codePoint = null var bytesPerSequence = (firstByte > 0xEF) ? 4 : (firstByte > 0xDF) ? 3 : (firstByte > 0xBF) ? 2 : 1 if (i + bytesPerSequence <= end) { var secondByte, thirdByte, fourthByte, tempCodePoint switch (bytesPerSequence) { case 1: if (firstByte < 0x80) { codePoint = firstByte } break case 2: secondByte = buf[i + 1] if ((secondByte & 0xC0) === 0x80) { tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) if (tempCodePoint > 0x7F) { codePoint = tempCodePoint } } break case 3: secondByte = buf[i + 1] thirdByte = buf[i + 2] if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { codePoint = tempCodePoint } } break case 4: secondByte = buf[i + 1] thirdByte = buf[i + 2] fourthByte = buf[i + 3] if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { codePoint = tempCodePoint } } } } if (codePoint === null) { // we did not generate a valid codePoint so insert a // replacement char (U+FFFD) and advance only 1 byte codePoint = 0xFFFD bytesPerSequence = 1 } else if (codePoint > 0xFFFF) { // encode to utf16 (surrogate pair dance) codePoint -= 0x10000 res.push(codePoint >>> 10 & 0x3FF | 0xD800) codePoint = 0xDC00 | codePoint & 0x3FF } res.push(codePoint) i += bytesPerSequence } return decodeCodePointsArray(res) } // Based on http://stackoverflow.com/a/22747272/680742, the browser with // the lowest limit is Chrome, with 0x10000 args. // We go 1 magnitude less, for safety var MAX_ARGUMENTS_LENGTH = 0x1000 function decodeCodePointsArray (codePoints) { var len = codePoints.length if (len <= MAX_ARGUMENTS_LENGTH) { return String.fromCharCode.apply(String, codePoints) // avoid extra slice() } // Decode in chunks to avoid "call stack size exceeded". var res = '' var i = 0 while (i < len) { res += String.fromCharCode.apply( String, codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) ) } return res } function asciiSlice (buf, start, end) { var ret = '' end = Math.min(buf.length, end) for (var i = start; i < end; ++i) { ret += String.fromCharCode(buf[i] & 0x7F) } return ret } function latin1Slice (buf, start, end) { var ret = '' end = Math.min(buf.length, end) for (var i = start; i < end; ++i) { ret += String.fromCharCode(buf[i]) } return ret } function hexSlice (buf, start, end) { var len = buf.length if (!start || start < 0) start = 0 if (!end || end < 0 || end > len) end = len var out = '' for (var i = start; i < end; ++i) { out += toHex(buf[i]) } return out } function utf16leSlice (buf, start, end) { var bytes = buf.slice(start, end) var res = '' for (var i = 0; i < bytes.length; i += 2) { res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256)) } return res } Buffer.prototype.slice = function slice (start, end) { var len = this.length start = ~~start end = end === undefined ? len : ~~end if (start < 0) { start += len if (start < 0) start = 0 } else if (start > len) { start = len } if (end < 0) { end += len if (end < 0) end = 0 } else if (end > len) { end = len } if (end < start) end = start var newBuf = this.subarray(start, end) // Return an augmented `Uint8Array` instance newBuf.__proto__ = Buffer.prototype return newBuf } /* * Need to make sure that buffer isn't trying to write out of bounds. */ function checkOffset (offset, ext, length) { if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') } Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { offset = offset >>> 0 byteLength = byteLength >>> 0 if (!noAssert) checkOffset(offset, byteLength, this.length) var val = this[offset] var mul = 1 var i = 0 while (++i < byteLength && (mul *= 0x100)) { val += this[offset + i] * mul } return val } Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { offset = offset >>> 0 byteLength = byteLength >>> 0 if (!noAssert) { checkOffset(offset, byteLength, this.length) } var val = this[offset + --byteLength] var mul = 1 while (byteLength > 0 && (mul *= 0x100)) { val += this[offset + --byteLength] * mul } return val } Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 1, this.length) return this[offset] } Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 2, this.length) return this[offset] | (this[offset + 1] << 8) } Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 2, this.length) return (this[offset] << 8) | this[offset + 1] } Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 4, this.length) return ((this[offset]) | (this[offset + 1] << 8) | (this[offset + 2] << 16)) + (this[offset + 3] * 0x1000000) } Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 4, this.length) return (this[offset] * 0x1000000) + ((this[offset + 1] << 16) | (this[offset + 2] << 8) | this[offset + 3]) } Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { offset = offset >>> 0 byteLength = byteLength >>> 0 if (!noAssert) checkOffset(offset, byteLength, this.length) var val = this[offset] var mul = 1 var i = 0 while (++i < byteLength && (mul *= 0x100)) { val += this[offset + i] * mul } mul *= 0x80 if (val >= mul) val -= Math.pow(2, 8 * byteLength) return val } Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { offset = offset >>> 0 byteLength = byteLength >>> 0 if (!noAssert) checkOffset(offset, byteLength, this.length) var i = byteLength var mul = 1 var val = this[offset + --i] while (i > 0 && (mul *= 0x100)) { val += this[offset + --i] * mul } mul *= 0x80 if (val >= mul) val -= Math.pow(2, 8 * byteLength) return val } Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 1, this.length) if (!(this[offset] & 0x80)) return (this[offset]) return ((0xff - this[offset] + 1) * -1) } Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 2, this.length) var val = this[offset] | (this[offset + 1] << 8) return (val & 0x8000) ? val | 0xFFFF0000 : val } Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 2, this.length) var val = this[offset + 1] | (this[offset] << 8) return (val & 0x8000) ? val | 0xFFFF0000 : val } Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 4, this.length) return (this[offset]) | (this[offset + 1] << 8) | (this[offset + 2] << 16) | (this[offset + 3] << 24) } Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 4, this.length) return (this[offset] << 24) | (this[offset + 1] << 16) | (this[offset + 2] << 8) | (this[offset + 3]) } Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 4, this.length) return ieee754.read(this, offset, true, 23, 4) } Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 4, this.length) return ieee754.read(this, offset, false, 23, 4) } Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 8, this.length) return ieee754.read(this, offset, true, 52, 8) } Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 8, this.length) return ieee754.read(this, offset, false, 52, 8) } function checkInt (buf, value, offset, ext, max, min) { if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') if (offset + ext > buf.length) throw new RangeError('Index out of range') } Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { value = +value offset = offset >>> 0 byteLength = byteLength >>> 0 if (!noAssert) { var maxBytes = Math.pow(2, 8 * byteLength) - 1 checkInt(this, value, offset, byteLength, maxBytes, 0) } var mul = 1 var i = 0 this[offset] = value & 0xFF while (++i < byteLength && (mul *= 0x100)) { this[offset + i] = (value / mul) & 0xFF } return offset + byteLength } Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { value = +value offset = offset >>> 0 byteLength = byteLength >>> 0 if (!noAssert) { var maxBytes = Math.pow(2, 8 * byteLength) - 1 checkInt(this, value, offset, byteLength, maxBytes, 0) } var i = byteLength - 1 var mul = 1 this[offset + i] = value & 0xFF while (--i >= 0 && (mul *= 0x100)) { this[offset + i] = (value / mul) & 0xFF } return offset + byteLength } Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) this[offset] = (value & 0xff) return offset + 1 } Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) this[offset] = (value & 0xff) this[offset + 1] = (value >>> 8) return offset + 2 } Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) this[offset] = (value >>> 8) this[offset + 1] = (value & 0xff) return offset + 2 } Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) this[offset + 3] = (value >>> 24) this[offset + 2] = (value >>> 16) this[offset + 1] = (value >>> 8) this[offset] = (value & 0xff) return offset + 4 } Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) this[offset] = (value >>> 24) this[offset + 1] = (value >>> 16) this[offset + 2] = (value >>> 8) this[offset + 3] = (value & 0xff) return offset + 4 } Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) { var limit = Math.pow(2, (8 * byteLength) - 1) checkInt(this, value, offset, byteLength, limit - 1, -limit) } var i = 0 var mul = 1 var sub = 0 this[offset] = value & 0xFF while (++i < byteLength && (mul *= 0x100)) { if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { sub = 1 } this[offset + i] = ((value / mul) >> 0) - sub & 0xFF } return offset + byteLength } Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) { var limit = Math.pow(2, (8 * byteLength) - 1) checkInt(this, value, offset, byteLength, limit - 1, -limit) } var i = byteLength - 1 var mul = 1 var sub = 0 this[offset + i] = value & 0xFF while (--i >= 0 && (mul *= 0x100)) { if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { sub = 1 } this[offset + i] = ((value / mul) >> 0) - sub & 0xFF } return offset + byteLength } Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) if (value < 0) value = 0xff + value + 1 this[offset] = (value & 0xff) return offset + 1 } Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) this[offset] = (value & 0xff) this[offset + 1] = (value >>> 8) return offset + 2 } Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) this[offset] = (value >>> 8) this[offset + 1] = (value & 0xff) return offset + 2 } Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) this[offset] = (value & 0xff) this[offset + 1] = (value >>> 8) this[offset + 2] = (value >>> 16) this[offset + 3] = (value >>> 24) return offset + 4 } Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) if (value < 0) value = 0xffffffff + value + 1 this[offset] = (value >>> 24) this[offset + 1] = (value >>> 16) this[offset + 2] = (value >>> 8) this[offset + 3] = (value & 0xff) return offset + 4 } function checkIEEE754 (buf, value, offset, ext, max, min) { if (offset + ext > buf.length) throw new RangeError('Index out of range') if (offset < 0) throw new RangeError('Index out of range') } function writeFloat (buf, value, offset, littleEndian, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) { checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) } ieee754.write(buf, value, offset, littleEndian, 23, 4) return offset + 4 } Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { return writeFloat(this, value, offset, true, noAssert) } Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { return writeFloat(this, value, offset, false, noAssert) } function writeDouble (buf, value, offset, littleEndian, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) { checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) } ieee754.write(buf, value, offset, littleEndian, 52, 8) return offset + 8 } Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { return writeDouble(this, value, offset, true, noAssert) } Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { return writeDouble(this, value, offset, false, noAssert) } // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) Buffer.prototype.copy = function copy (target, targetStart, start, end) { if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer') if (!start) start = 0 if (!end && end !== 0) end = this.length if (targetStart >= target.length) targetStart = target.length if (!targetStart) targetStart = 0 if (end > 0 && end < start) end = start // Copy 0 bytes; we're done if (end === start) return 0 if (target.length === 0 || this.length === 0) return 0 // Fatal error conditions if (targetStart < 0) { throw new RangeError('targetStart out of bounds') } if (start < 0 || start >= this.length) throw new RangeError('Index out of range') if (end < 0) throw new RangeError('sourceEnd out of bounds') // Are we oob? if (end > this.length) end = this.length if (target.length - targetStart < end - start) { end = target.length - targetStart + start } var len = end - start if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') { // Use built-in when available, missing from IE11 this.copyWithin(targetStart, start, end) } else if (this === target && start < targetStart && targetStart < end) { // descending copy from end for (var i = len - 1; i >= 0; --i) { target[i + targetStart] = this[i + start] } } else { Uint8Array.prototype.set.call( target, this.subarray(start, end), targetStart ) } return len } // Usage: // buffer.fill(number[, offset[, end]]) // buffer.fill(buffer[, offset[, end]]) // buffer.fill(string[, offset[, end]][, encoding]) Buffer.prototype.fill = function fill (val, start, end, encoding) { // Handle string cases: if (typeof val === 'string') { if (typeof start === 'string') { encoding = start start = 0 end = this.length } else if (typeof end === 'string') { encoding = end end = this.length } if (encoding !== undefined && typeof encoding !== 'string') { throw new TypeError('encoding must be a string') } if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { throw new TypeError('Unknown encoding: ' + encoding) } if (val.length === 1) { var code = val.charCodeAt(0) if ((encoding === 'utf8' && code < 128) || encoding === 'latin1') { // Fast path: If `val` fits into a single byte, use that numeric value. val = code } } } else if (typeof val === 'number') { val = val & 255 } // Invalid ranges are not set to a default, so can range check early. if (start < 0 || this.length < start || this.length < end) { throw new RangeError('Out of range index') } if (end <= start) { return this } start = start >>> 0 end = end === undefined ? this.length : end >>> 0 if (!val) val = 0 var i if (typeof val === 'number') { for (i = start; i < end; ++i) { this[i] = val } } else { var bytes = Buffer.isBuffer(val) ? val : Buffer.from(val, encoding) var len = bytes.length if (len === 0) { throw new TypeError('The value "' + val + '" is invalid for argument "value"') } for (i = 0; i < end - start; ++i) { this[i + start] = bytes[i % len] } } return this } // HELPER FUNCTIONS // ================ var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g function base64clean (str) { // Node takes equal signs as end of the Base64 encoding str = str.split('=')[0] // Node strips out invalid characters like \n and \t from the string, base64-js does not str = str.trim().replace(INVALID_BASE64_RE, '') // Node converts strings with length < 2 to '' if (str.length < 2) return '' // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not while (str.length % 4 !== 0) { str = str + '=' } return str } function toHex (n) { if (n < 16) return '0' + n.toString(16) return n.toString(16) } function utf8ToBytes (string, units) { units = units || Infinity var codePoint var length = string.length var leadSurrogate = null var bytes = [] for (var i = 0; i < length; ++i) { codePoint = string.charCodeAt(i) // is surrogate component if (codePoint > 0xD7FF && codePoint < 0xE000) { // last char was a lead if (!leadSurrogate) { // no lead yet if (codePoint > 0xDBFF) { // unexpected trail if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) continue } else if (i + 1 === length) { // unpaired lead if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) continue } // valid lead leadSurrogate = codePoint continue } // 2 leads in a row if (codePoint < 0xDC00) { if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) leadSurrogate = codePoint continue } // valid surrogate pair codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 } else if (leadSurrogate) { // valid bmp char, but last char was a lead if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) } leadSurrogate = null // encode utf8 if (codePoint < 0x80) { if ((units -= 1) < 0) break bytes.push(codePoint) } else if (codePoint < 0x800) { if ((units -= 2) < 0) break bytes.push( codePoint >> 0x6 | 0xC0, codePoint & 0x3F | 0x80 ) } else if (codePoint < 0x10000) { if ((units -= 3) < 0) break bytes.push( codePoint >> 0xC | 0xE0, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80 ) } else if (codePoint < 0x110000) { if ((units -= 4) < 0) break bytes.push( codePoint >> 0x12 | 0xF0, codePoint >> 0xC & 0x3F | 0x80, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80 ) } else { throw new Error('Invalid code point') } } return bytes } function asciiToBytes (str) { var byteArray = [] for (var i = 0; i < str.length; ++i) { // Node's code seems to be doing this and not & 0x7F.. byteArray.push(str.charCodeAt(i) & 0xFF) } return byteArray } function utf16leToBytes (str, units) { var c, hi, lo var byteArray = [] for (var i = 0; i < str.length; ++i) { if ((units -= 2) < 0) break c = str.charCodeAt(i) hi = c >> 8 lo = c % 256 byteArray.push(lo) byteArray.push(hi) } return byteArray } function base64ToBytes (str) { return base64.toByteArray(base64clean(str)) } function blitBuffer (src, dst, offset, length) { for (var i = 0; i < length; ++i) { if ((i + offset >= dst.length) || (i >= src.length)) break dst[i + offset] = src[i] } return i } // ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass // the `instanceof` check but they should be treated as of that type. // See: https://github.com/feross/buffer/issues/166 function isInstance (obj, type) { return obj instanceof type || (obj != null && obj.constructor != null && obj.constructor.name != null && obj.constructor.name === type.name) } function numberIsNaN (obj) { // For IE11 support return obj !== obj // eslint-disable-line no-self-compare } },{"base64-js":10,"ieee754":16}],15:[function(require,module,exports){ (function (Buffer){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // NOTE: These type checking functions intentionally don't use `instanceof` // because it is fragile and can be easily faked with `Object.create()`. function isArray(arg) { if (Array.isArray) { return Array.isArray(arg); } return objectToString(arg) === '[object Array]'; } exports.isArray = isArray; function isBoolean(arg) { return typeof arg === 'boolean'; } exports.isBoolean = isBoolean; function isNull(arg) { return arg === null; } exports.isNull = isNull; function isNullOrUndefined(arg) { return arg == null; } exports.isNullOrUndefined = isNullOrUndefined; function isNumber(arg) { return typeof arg === 'number'; } exports.isNumber = isNumber; function isString(arg) { return typeof arg === 'string'; } exports.isString = isString; function isSymbol(arg) { return typeof arg === 'symbol'; } exports.isSymbol = isSymbol; function isUndefined(arg) { return arg === void 0; } exports.isUndefined = isUndefined; function isRegExp(re) { return objectToString(re) === '[object RegExp]'; } exports.isRegExp = isRegExp; function isObject(arg) { return typeof arg === 'object' && arg !== null; } exports.isObject = isObject; function isDate(d) { return objectToString(d) === '[object Date]'; } exports.isDate = isDate; function isError(e) { return (objectToString(e) === '[object Error]' || e instanceof Error); } exports.isError = isError; function isFunction(arg) { return typeof arg === 'function'; } exports.isFunction = isFunction; function isPrimitive(arg) { return arg === null || typeof arg === 'boolean' || typeof arg === 'number' || typeof arg === 'string' || typeof arg === 'symbol' || // ES6 symbol typeof arg === 'undefined'; } exports.isPrimitive = isPrimitive; exports.isBuffer = Buffer.isBuffer; function objectToString(o) { return Object.prototype.toString.call(o); } }).call(this,{"isBuffer":require("../../is-buffer/index.js")}) },{"../../is-buffer/index.js":18}],16:[function(require,module,exports){ exports.read = function (buffer, offset, isLE, mLen, nBytes) { var e, m var eLen = (nBytes * 8) - mLen - 1 var eMax = (1 << eLen) - 1 var eBias = eMax >> 1 var nBits = -7 var i = isLE ? (nBytes - 1) : 0 var d = isLE ? -1 : 1 var s = buffer[offset + i] i += d e = s & ((1 << (-nBits)) - 1) s >>= (-nBits) nBits += eLen for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {} m = e & ((1 << (-nBits)) - 1) e >>= (-nBits) nBits += mLen for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {} if (e === 0) { e = 1 - eBias } else if (e === eMax) { return m ? NaN : ((s ? -1 : 1) * Infinity) } else { m = m + Math.pow(2, mLen) e = e - eBias } return (s ? -1 : 1) * m * Math.pow(2, e - mLen) } exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { var e, m, c var eLen = (nBytes * 8) - mLen - 1 var eMax = (1 << eLen) - 1 var eBias = eMax >> 1 var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) var i = isLE ? 0 : (nBytes - 1) var d = isLE ? 1 : -1 var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 value = Math.abs(value) if (isNaN(value) || value === Infinity) { m = isNaN(value) ? 1 : 0 e = eMax } else { e = Math.floor(Math.log(value) / Math.LN2) if (value * (c = Math.pow(2, -e)) < 1) { e-- c *= 2 } if (e + eBias >= 1) { value += rt / c } else { value += rt * Math.pow(2, 1 - eBias) } if (value * c >= 2) { e++ c /= 2 } if (e + eBias >= eMax) { m = 0 e = eMax } else if (e + eBias >= 1) { m = ((value * c) - 1) * Math.pow(2, mLen) e = e + eBias } else { m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) e = 0 } } for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} e = (e << mLen) | m eLen += mLen for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} buffer[offset + i - d] |= s * 128 } },{}],17:[function(require,module,exports){ if (typeof Object.create === 'function') { // implementation from standard node.js 'util' module module.exports = function inherits(ctor, superCtor) { ctor.super_ = superCtor ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true } }); }; } else { // old school shim for old browsers module.exports = function inherits(ctor, superCtor) { ctor.super_ = superCtor var TempCtor = function () {} TempCtor.prototype = superCtor.prototype ctor.prototype = new TempCtor() ctor.prototype.constructor = ctor } } },{}],18:[function(require,module,exports){ /*! * Determine if an object is a Buffer * * @author Feross Aboukhadijeh * @license MIT */ // The _isBuffer check is for Safari 5-7 support, because it's missing // Object.prototype.constructor. Remove this eventually module.exports = function (obj) { return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer) } function isBuffer (obj) { return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) } // For Node v0.10 support. Remove this eventually. function isSlowBuffer (obj) { return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0)) } },{}],19:[function(require,module,exports){ var toString = {}.toString; module.exports = Array.isArray || function (arr) { return toString.call(arr) == '[object Array]'; }; },{}],20:[function(require,module,exports){ (function (process){ 'use strict'; if (!process.version || process.version.indexOf('v0.') === 0 || process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) { module.exports = { nextTick: nextTick }; } else { module.exports = process } function nextTick(fn, arg1, arg2, arg3) { if (typeof fn !== 'function') { throw new TypeError('"callback" argument must be a function'); } var len = arguments.length; var args, i; switch (len) { case 0: case 1: return process.nextTick(fn); case 2: return process.nextTick(function afterTickOne() { fn.call(null, arg1); }); case 3: return process.nextTick(function afterTickTwo() { fn.call(null, arg1, arg2); }); case 4: return process.nextTick(function afterTickThree() { fn.call(null, arg1, arg2, arg3); }); default: args = new Array(len - 1); i = 0; while (i < args.length) { args[i++] = arguments[i]; } return process.nextTick(function afterTick() { fn.apply(null, args); }); } } }).call(this,require('_process')) },{"_process":21}],21:[function(require,module,exports){ // shim for using process in browser var process = module.exports = {}; // cached from whatever global is present so that test runners that stub it // don't break things. But we need to wrap it in a try catch in case it is // wrapped in strict mode code which doesn't define any globals. It's inside a // function because try/catches deoptimize in certain engines. var cachedSetTimeout; var cachedClearTimeout; function defaultSetTimout() { throw new Error('setTimeout has not been defined'); } function defaultClearTimeout () { throw new Error('clearTimeout has not been defined'); } (function () { try { if (typeof setTimeout === 'function') { cachedSetTimeout = setTimeout; } else { cachedSetTimeout = defaultSetTimout; } } catch (e) { cachedSetTimeout = defaultSetTimout; } try { if (typeof clearTimeout === 'function') { cachedClearTimeout = clearTimeout; } else { cachedClearTimeout = defaultClearTimeout; } } catch (e) { cachedClearTimeout = defaultClearTimeout; } } ()) function runTimeout(fun) { if (cachedSetTimeout === setTimeout) { //normal enviroments in sane situations return setTimeout(fun, 0); } // if setTimeout wasn't available but was latter defined if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { cachedSetTimeout = setTimeout; return setTimeout(fun, 0); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedSetTimeout(fun, 0); } catch(e){ try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedSetTimeout.call(null, fun, 0); } catch(e){ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error return cachedSetTimeout.call(this, fun, 0); } } } function runClearTimeout(marker) { if (cachedClearTimeout === clearTimeout) { //normal enviroments in sane situations return clearTimeout(marker); } // if clearTimeout wasn't available but was latter defined if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { cachedClearTimeout = clearTimeout; return clearTimeout(marker); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedClearTimeout(marker); } catch (e){ try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedClearTimeout.call(null, marker); } catch (e){ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. // Some versions of I.E. have different rules for clearTimeout vs setTimeout return cachedClearTimeout.call(this, marker); } } } var queue = []; var draining = false; var currentQueue; var queueIndex = -1; function cleanUpNextTick() { if (!draining || !currentQueue) { return; } draining = false; if (currentQueue.length) { queue = currentQueue.concat(queue); } else { queueIndex = -1; } if (queue.length) { drainQueue(); } } function drainQueue() { if (draining) { return; } var timeout = runTimeout(cleanUpNextTick); draining = true; var len = queue.length; while(len) { currentQueue = queue; queue = []; while (++queueIndex < len) { if (currentQueue) { currentQueue[queueIndex].run(); } } queueIndex = -1; len = queue.length; } currentQueue = null; draining = false; runClearTimeout(timeout); } process.nextTick = function (fun) { var args = new Array(arguments.length - 1); if (arguments.length > 1) { for (var i = 1; i < arguments.length; i++) { args[i - 1] = arguments[i]; } } queue.push(new Item(fun, args)); if (queue.length === 1 && !draining) { runTimeout(drainQueue); } }; // v8 likes predictible objects function Item(fun, array) { this.fun = fun; this.array = array; } Item.prototype.run = function () { this.fun.apply(null, this.array); }; process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; process.version = ''; // empty string to avoid regexp issues process.versions = {}; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.prependListener = noop; process.prependOnceListener = noop; process.listeners = function (name) { return [] } process.binding = function (name) { throw new Error('process.binding is not supported'); }; process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; process.umask = function() { return 0; }; },{}],22:[function(require,module,exports){ module.exports = require('./lib/_stream_duplex.js'); },{"./lib/_stream_duplex.js":23}],23:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // a duplex stream is just a stream that is both readable and writable. // Since JS doesn't have multiple prototypal inheritance, this class // prototypally inherits from Readable, and then parasitically from // Writable. 'use strict'; /**/ var pna = require('process-nextick-args'); /**/ /**/ var objectKeys = Object.keys || function (obj) { var keys = []; for (var key in obj) { keys.push(key); }return keys; }; /**/ module.exports = Duplex; /**/ var util = require('core-util-is'); util.inherits = require('inherits'); /**/ var Readable = require('./_stream_readable'); var Writable = require('./_stream_writable'); util.inherits(Duplex, Readable); var keys = objectKeys(Writable.prototype); for (var v = 0; v < keys.length; v++) { var method = keys[v]; if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; } function Duplex(options) { if (!(this instanceof Duplex)) return new Duplex(options); Readable.call(this, options); Writable.call(this, options); if (options && options.readable === false) this.readable = false; if (options && options.writable === false) this.writable = false; this.allowHalfOpen = true; if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; this.once('end', onend); } // the no-half-open enforcer function onend() { // if we allow half-open state, or if the writable side ended, // then we're ok. if (this.allowHalfOpen || this._writableState.ended) return; // no more data can be written. // But allow more writes to happen in this tick. pna.nextTick(onEndNT, this); } function onEndNT(self) { self.end(); } Object.defineProperty(Duplex.prototype, 'destroyed', { get: function () { if (this._readableState === undefined || this._writableState === undefined) { return false; } return this._readableState.destroyed && this._writableState.destroyed; }, set: function (value) { // we ignore the value if the stream // has not been initialized yet if (this._readableState === undefined || this._writableState === undefined) { return; } // backward compatibility, the user is explicitly // managing destroyed this._readableState.destroyed = value; this._writableState.destroyed = value; } }); Duplex.prototype._destroy = function (err, cb) { this.push(null); this.end(); pna.nextTick(cb, err); }; function forEach(xs, f) { for (var i = 0, l = xs.length; i < l; i++) { f(xs[i], i); } } },{"./_stream_readable":25,"./_stream_writable":27,"core-util-is":15,"inherits":17,"process-nextick-args":20}],24:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // a passthrough stream. // basically just the most minimal sort of Transform stream. // Every written chunk gets output as-is. 'use strict'; module.exports = PassThrough; var Transform = require('./_stream_transform'); /**/ var util = require('core-util-is'); util.inherits = require('inherits'); /**/ util.inherits(PassThrough, Transform); function PassThrough(options) { if (!(this instanceof PassThrough)) return new PassThrough(options); Transform.call(this, options); } PassThrough.prototype._transform = function (chunk, encoding, cb) { cb(null, chunk); }; },{"./_stream_transform":26,"core-util-is":15,"inherits":17}],25:[function(require,module,exports){ (function (process,global){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. 'use strict'; /**/ var pna = require('process-nextick-args'); /**/ module.exports = Readable; /**/ var isArray = require('isarray'); /**/ /**/ var Duplex; /**/ Readable.ReadableState = ReadableState; /**/ var EE = require('events').EventEmitter; var EElistenerCount = function (emitter, type) { return emitter.listeners(type).length; }; /**/ /**/ var Stream = require('./internal/streams/stream'); /**/ /**/ var Buffer = require('safe-buffer').Buffer; var OurUint8Array = global.Uint8Array || function () {}; function _uint8ArrayToBuffer(chunk) { return Buffer.from(chunk); } function _isUint8Array(obj) { return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; } /**/ /**/ var util = require('core-util-is'); util.inherits = require('inherits'); /**/ /**/ var debugUtil = require('util'); var debug = void 0; if (debugUtil && debugUtil.debuglog) { debug = debugUtil.debuglog('stream'); } else { debug = function () {}; } /**/ var BufferList = require('./internal/streams/BufferList'); var destroyImpl = require('./internal/streams/destroy'); var StringDecoder; util.inherits(Readable, Stream); var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; function prependListener(emitter, event, fn) { // Sadly this is not cacheable as some libraries bundle their own // event emitter implementation with them. if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); // This is a hack to make sure that our error handler is attached before any // userland ones. NEVER DO THIS. This is here only because this code needs // to continue to work with older versions of Node.js that do not include // the prependListener() method. The goal is to eventually remove this hack. if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; } function ReadableState(options, stream) { Duplex = Duplex || require('./_stream_duplex'); options = options || {}; // Duplex streams are both readable and writable, but share // the same options object. // However, some cases require setting options to different // values for the readable and the writable sides of the duplex stream. // These options can be provided separately as readableXXX and writableXXX. var isDuplex = stream instanceof Duplex; // object stream flag. Used to make read(n) ignore n and to // make all the buffer merging and length checks go away this.objectMode = !!options.objectMode; if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; // the point at which it stops calling _read() to fill the buffer // Note: 0 is a valid value, means "don't call _read preemptively ever" var hwm = options.highWaterMark; var readableHwm = options.readableHighWaterMark; var defaultHwm = this.objectMode ? 16 : 16 * 1024; if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm; // cast to ints. this.highWaterMark = Math.floor(this.highWaterMark); // A linked list is used to store data chunks instead of an array because the // linked list can remove elements from the beginning faster than // array.shift() this.buffer = new BufferList(); this.length = 0; this.pipes = null; this.pipesCount = 0; this.flowing = null; this.ended = false; this.endEmitted = false; this.reading = false; // a flag to be able to tell if the event 'readable'/'data' is emitted // immediately, or on a later tick. We set this to true at first, because // any actions that shouldn't happen until "later" should generally also // not happen before the first read call. this.sync = true; // whenever we return null, then we set a flag to say // that we're awaiting a 'readable' event emission. this.needReadable = false; this.emittedReadable = false; this.readableListening = false; this.resumeScheduled = false; // has it been destroyed this.destroyed = false; // Crypto is kind of old and crusty. Historically, its default string // encoding is 'binary' so we have to make this configurable. // Everything else in the universe uses 'utf8', though. this.defaultEncoding = options.defaultEncoding || 'utf8'; // the number of writers that are awaiting a drain event in .pipe()s this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled this.readingMore = false; this.decoder = null; this.encoding = null; if (options.encoding) { if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; this.decoder = new StringDecoder(options.encoding); this.encoding = options.encoding; } } function Readable(options) { Duplex = Duplex || require('./_stream_duplex'); if (!(this instanceof Readable)) return new Readable(options); this._readableState = new ReadableState(options, this); // legacy this.readable = true; if (options) { if (typeof options.read === 'function') this._read = options.read; if (typeof options.destroy === 'function') this._destroy = options.destroy; } Stream.call(this); } Object.defineProperty(Readable.prototype, 'destroyed', { get: function () { if (this._readableState === undefined) { return false; } return this._readableState.destroyed; }, set: function (value) { // we ignore the value if the stream // has not been initialized yet if (!this._readableState) { return; } // backward compatibility, the user is explicitly // managing destroyed this._readableState.destroyed = value; } }); Readable.prototype.destroy = destroyImpl.destroy; Readable.prototype._undestroy = destroyImpl.undestroy; Readable.prototype._destroy = function (err, cb) { this.push(null); cb(err); }; // Manually shove something into the read() buffer. // This returns true if the highWaterMark has not been hit yet, // similar to how Writable.write() returns true if you should // write() some more. Readable.prototype.push = function (chunk, encoding) { var state = this._readableState; var skipChunkCheck; if (!state.objectMode) { if (typeof chunk === 'string') { encoding = encoding || state.defaultEncoding; if (encoding !== state.encoding) { chunk = Buffer.from(chunk, encoding); encoding = ''; } skipChunkCheck = true; } } else { skipChunkCheck = true; } return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); }; // Unshift should *always* be something directly out of read() Readable.prototype.unshift = function (chunk) { return readableAddChunk(this, chunk, null, true, false); }; function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { var state = stream._readableState; if (chunk === null) { state.reading = false; onEofChunk(stream, state); } else { var er; if (!skipChunkCheck) er = chunkInvalid(state, chunk); if (er) { stream.emit('error', er); } else if (state.objectMode || chunk && chunk.length > 0) { if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) { chunk = _uint8ArrayToBuffer(chunk); } if (addToFront) { if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true); } else if (state.ended) { stream.emit('error', new Error('stream.push() after EOF')); } else { state.reading = false; if (state.decoder && !encoding) { chunk = state.decoder.write(chunk); if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state); } else { addChunk(stream, state, chunk, false); } } } else if (!addToFront) { state.reading = false; } } return needMoreData(state); } function addChunk(stream, state, chunk, addToFront) { if (state.flowing && state.length === 0 && !state.sync) { stream.emit('data', chunk); stream.read(0); } else { // update the buffer info. state.length += state.objectMode ? 1 : chunk.length; if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); if (state.needReadable) emitReadable(stream); } maybeReadMore(stream, state); } function chunkInvalid(state, chunk) { var er; if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { er = new TypeError('Invalid non-string/buffer chunk'); } return er; } // if it's past the high water mark, we can push in some more. // Also, if we have no data yet, we can stand some // more bytes. This is to work around cases where hwm=0, // such as the repl. Also, if the push() triggered a // readable event, and the user called read(largeNumber) such that // needReadable was set, then we ought to push more, so that another // 'readable' event will be triggered. function needMoreData(state) { return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); } Readable.prototype.isPaused = function () { return this._readableState.flowing === false; }; // backwards compatibility. Readable.prototype.setEncoding = function (enc) { if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; this._readableState.decoder = new StringDecoder(enc); this._readableState.encoding = enc; return this; }; // Don't raise the hwm > 8MB var MAX_HWM = 0x800000; function computeNewHighWaterMark(n) { if (n >= MAX_HWM) { n = MAX_HWM; } else { // Get the next highest power of 2 to prevent increasing hwm excessively in // tiny amounts n--; n |= n >>> 1; n |= n >>> 2; n |= n >>> 4; n |= n >>> 8; n |= n >>> 16; n++; } return n; } // This function is designed to be inlinable, so please take care when making // changes to the function body. function howMuchToRead(n, state) { if (n <= 0 || state.length === 0 && state.ended) return 0; if (state.objectMode) return 1; if (n !== n) { // Only flow one buffer at a time if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; } // If we're asking for more than the current hwm, then raise the hwm. if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); if (n <= state.length) return n; // Don't have enough if (!state.ended) { state.needReadable = true; return 0; } return state.length; } // you can override either this method, or the async _read(n) below. Readable.prototype.read = function (n) { debug('read', n); n = parseInt(n, 10); var state = this._readableState; var nOrig = n; if (n !== 0) state.emittedReadable = false; // if we're doing read(0) to trigger a readable event, but we // already have a bunch of data in the buffer, then just trigger // the 'readable' event and move on. if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { debug('read: emitReadable', state.length, state.ended); if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); return null; } n = howMuchToRead(n, state); // if we've ended, and we're now clear, then finish it up. if (n === 0 && state.ended) { if (state.length === 0) endReadable(this); return null; } // All the actual chunk generation logic needs to be // *below* the call to _read. The reason is that in certain // synthetic stream cases, such as passthrough streams, _read // may be a completely synchronous operation which may change // the state of the read buffer, providing enough data when // before there was *not* enough. // // So, the steps are: // 1. Figure out what the state of things will be after we do // a read from the buffer. // // 2. If that resulting state will trigger a _read, then call _read. // Note that this may be asynchronous, or synchronous. Yes, it is // deeply ugly to write APIs this way, but that still doesn't mean // that the Readable class should behave improperly, as streams are // designed to be sync/async agnostic. // Take note if the _read call is sync or async (ie, if the read call // has returned yet), so that we know whether or not it's safe to emit // 'readable' etc. // // 3. Actually pull the requested chunks out of the buffer and return. // if we need a readable event, then we need to do some reading. var doRead = state.needReadable; debug('need readable', doRead); // if we currently have less than the highWaterMark, then also read some if (state.length === 0 || state.length - n < state.highWaterMark) { doRead = true; debug('length less than watermark', doRead); } // however, if we've ended, then there's no point, and if we're already // reading, then it's unnecessary. if (state.ended || state.reading) { doRead = false; debug('reading or ended', doRead); } else if (doRead) { debug('do read'); state.reading = true; state.sync = true; // if the length is currently zero, then we *need* a readable event. if (state.length === 0) state.needReadable = true; // call internal read method this._read(state.highWaterMark); state.sync = false; // If _read pushed data synchronously, then `reading` will be false, // and we need to re-evaluate how much data we can return to the user. if (!state.reading) n = howMuchToRead(nOrig, state); } var ret; if (n > 0) ret = fromList(n, state);else ret = null; if (ret === null) { state.needReadable = true; n = 0; } else { state.length -= n; } if (state.length === 0) { // If we have nothing in the buffer, then we want to know // as soon as we *do* get something into the buffer. if (!state.ended) state.needReadable = true; // If we tried to read() past the EOF, then emit end on the next tick. if (nOrig !== n && state.ended) endReadable(this); } if (ret !== null) this.emit('data', ret); return ret; }; function onEofChunk(stream, state) { if (state.ended) return; if (state.decoder) { var chunk = state.decoder.end(); if (chunk && chunk.length) { state.buffer.push(chunk); state.length += state.objectMode ? 1 : chunk.length; } } state.ended = true; // emit 'readable' now to make sure it gets picked up. emitReadable(stream); } // Don't emit readable right away in sync mode, because this can trigger // another read() call => stack overflow. This way, it might trigger // a nextTick recursion warning, but that's not so bad. function emitReadable(stream) { var state = stream._readableState; state.needReadable = false; if (!state.emittedReadable) { debug('emitReadable', state.flowing); state.emittedReadable = true; if (state.sync) pna.nextTick(emitReadable_, stream);else emitReadable_(stream); } } function emitReadable_(stream) { debug('emit readable'); stream.emit('readable'); flow(stream); } // at this point, the user has presumably seen the 'readable' event, // and called read() to consume some data. that may have triggered // in turn another _read(n) call, in which case reading = true if // it's in progress. // However, if we're not ended, or reading, and the length < hwm, // then go ahead and try to read some more preemptively. function maybeReadMore(stream, state) { if (!state.readingMore) { state.readingMore = true; pna.nextTick(maybeReadMore_, stream, state); } } function maybeReadMore_(stream, state) { var len = state.length; while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { debug('maybeReadMore read 0'); stream.read(0); if (len === state.length) // didn't get any data, stop spinning. break;else len = state.length; } state.readingMore = false; } // abstract method. to be overridden in specific implementation classes. // call cb(er, data) where data is <= n in length. // for virtual (non-string, non-buffer) streams, "length" is somewhat // arbitrary, and perhaps not very meaningful. Readable.prototype._read = function (n) { this.emit('error', new Error('_read() is not implemented')); }; Readable.prototype.pipe = function (dest, pipeOpts) { var src = this; var state = this._readableState; switch (state.pipesCount) { case 0: state.pipes = dest; break; case 1: state.pipes = [state.pipes, dest]; break; default: state.pipes.push(dest); break; } state.pipesCount += 1; debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; var endFn = doEnd ? onend : unpipe; if (state.endEmitted) pna.nextTick(endFn);else src.once('end', endFn); dest.on('unpipe', onunpipe); function onunpipe(readable, unpipeInfo) { debug('onunpipe'); if (readable === src) { if (unpipeInfo && unpipeInfo.hasUnpiped === false) { unpipeInfo.hasUnpiped = true; cleanup(); } } } function onend() { debug('onend'); dest.end(); } // when the dest drains, it reduces the awaitDrain counter // on the source. This would be more elegant with a .once() // handler in flow(), but adding and removing repeatedly is // too slow. var ondrain = pipeOnDrain(src); dest.on('drain', ondrain); var cleanedUp = false; function cleanup() { debug('cleanup'); // cleanup event handlers once the pipe is broken dest.removeListener('close', onclose); dest.removeListener('finish', onfinish); dest.removeListener('drain', ondrain); dest.removeListener('error', onerror); dest.removeListener('unpipe', onunpipe); src.removeListener('end', onend); src.removeListener('end', unpipe); src.removeListener('data', ondata); cleanedUp = true; // if the reader is waiting for a drain event from this // specific writer, then it would cause it to never start // flowing again. // So, if this is awaiting a drain, then we just call it now. // If we don't know, then assume that we are waiting for one. if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); } // If the user pushes more data while we're writing to dest then we'll end up // in ondata again. However, we only want to increase awaitDrain once because // dest will only emit one 'drain' event for the multiple writes. // => Introduce a guard on increasing awaitDrain. var increasedAwaitDrain = false; src.on('data', ondata); function ondata(chunk) { debug('ondata'); increasedAwaitDrain = false; var ret = dest.write(chunk); if (false === ret && !increasedAwaitDrain) { // If the user unpiped during `dest.write()`, it is possible // to get stuck in a permanently paused state if that write // also returned false. // => Check whether `dest` is still a piping destination. if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { debug('false write response, pause', src._readableState.awaitDrain); src._readableState.awaitDrain++; increasedAwaitDrain = true; } src.pause(); } } // if the dest has an error, then stop piping into it. // however, don't suppress the throwing behavior for this. function onerror(er) { debug('onerror', er); unpipe(); dest.removeListener('error', onerror); if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er); } // Make sure our error handler is attached before userland ones. prependListener(dest, 'error', onerror); // Both close and finish should trigger unpipe, but only once. function onclose() { dest.removeListener('finish', onfinish); unpipe(); } dest.once('close', onclose); function onfinish() { debug('onfinish'); dest.removeListener('close', onclose); unpipe(); } dest.once('finish', onfinish); function unpipe() { debug('unpipe'); src.unpipe(dest); } // tell the dest that it's being piped to dest.emit('pipe', src); // start the flow if it hasn't been started already. if (!state.flowing) { debug('pipe resume'); src.resume(); } return dest; }; function pipeOnDrain(src) { return function () { var state = src._readableState; debug('pipeOnDrain', state.awaitDrain); if (state.awaitDrain) state.awaitDrain--; if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { state.flowing = true; flow(src); } }; } Readable.prototype.unpipe = function (dest) { var state = this._readableState; var unpipeInfo = { hasUnpiped: false }; // if we're not piping anywhere, then do nothing. if (state.pipesCount === 0) return this; // just one destination. most common case. if (state.pipesCount === 1) { // passed in one, but it's not the right one. if (dest && dest !== state.pipes) return this; if (!dest) dest = state.pipes; // got a match. state.pipes = null; state.pipesCount = 0; state.flowing = false; if (dest) dest.emit('unpipe', this, unpipeInfo); return this; } // slow case. multiple pipe destinations. if (!dest) { // remove all. var dests = state.pipes; var len = state.pipesCount; state.pipes = null; state.pipesCount = 0; state.flowing = false; for (var i = 0; i < len; i++) { dests[i].emit('unpipe', this, unpipeInfo); }return this; } // try to find the right one. var index = indexOf(state.pipes, dest); if (index === -1) return this; state.pipes.splice(index, 1); state.pipesCount -= 1; if (state.pipesCount === 1) state.pipes = state.pipes[0]; dest.emit('unpipe', this, unpipeInfo); return this; }; // set up data events if they are asked for // Ensure readable listeners eventually get something Readable.prototype.on = function (ev, fn) { var res = Stream.prototype.on.call(this, ev, fn); if (ev === 'data') { // Start flowing on next tick if stream isn't explicitly paused if (this._readableState.flowing !== false) this.resume(); } else if (ev === 'readable') { var state = this._readableState; if (!state.endEmitted && !state.readableListening) { state.readableListening = state.needReadable = true; state.emittedReadable = false; if (!state.reading) { pna.nextTick(nReadingNextTick, this); } else if (state.length) { emitReadable(this); } } } return res; }; Readable.prototype.addListener = Readable.prototype.on; function nReadingNextTick(self) { debug('readable nexttick read 0'); self.read(0); } // pause() and resume() are remnants of the legacy readable stream API // If the user uses them, then switch into old mode. Readable.prototype.resume = function () { var state = this._readableState; if (!state.flowing) { debug('resume'); state.flowing = true; resume(this, state); } return this; }; function resume(stream, state) { if (!state.resumeScheduled) { state.resumeScheduled = true; pna.nextTick(resume_, stream, state); } } function resume_(stream, state) { if (!state.reading) { debug('resume read 0'); stream.read(0); } state.resumeScheduled = false; state.awaitDrain = 0; stream.emit('resume'); flow(stream); if (state.flowing && !state.reading) stream.read(0); } Readable.prototype.pause = function () { debug('call pause flowing=%j', this._readableState.flowing); if (false !== this._readableState.flowing) { debug('pause'); this._readableState.flowing = false; this.emit('pause'); } return this; }; function flow(stream) { var state = stream._readableState; debug('flow', state.flowing); while (state.flowing && stream.read() !== null) {} } // wrap an old-style stream as the async data source. // This is *not* part of the readable stream interface. // It is an ugly unfortunate mess of history. Readable.prototype.wrap = function (stream) { var _this = this; var state = this._readableState; var paused = false; stream.on('end', function () { debug('wrapped end'); if (state.decoder && !state.ended) { var chunk = state.decoder.end(); if (chunk && chunk.length) _this.push(chunk); } _this.push(null); }); stream.on('data', function (chunk) { debug('wrapped data'); if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; var ret = _this.push(chunk); if (!ret) { paused = true; stream.pause(); } }); // proxy all the other methods. // important when wrapping filters and duplexes. for (var i in stream) { if (this[i] === undefined && typeof stream[i] === 'function') { this[i] = function (method) { return function () { return stream[method].apply(stream, arguments); }; }(i); } } // proxy certain important events. for (var n = 0; n < kProxyEvents.length; n++) { stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); } // when we try to consume some more bytes, simply unpause the // underlying stream. this._read = function (n) { debug('wrapped _read', n); if (paused) { paused = false; stream.resume(); } }; return this; }; // exposed for testing purposes only. Readable._fromList = fromList; // Pluck off n bytes from an array of buffers. // Length is the combined lengths of all the buffers in the list. // This function is designed to be inlinable, so please take care when making // changes to the function body. function fromList(n, state) { // nothing buffered if (state.length === 0) return null; var ret; if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { // read it all, truncate the list if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); state.buffer.clear(); } else { // read part of list ret = fromListPartial(n, state.buffer, state.decoder); } return ret; } // Extracts only enough buffered data to satisfy the amount requested. // This function is designed to be inlinable, so please take care when making // changes to the function body. function fromListPartial(n, list, hasStrings) { var ret; if (n < list.head.data.length) { // slice is the same for buffers and strings ret = list.head.data.slice(0, n); list.head.data = list.head.data.slice(n); } else if (n === list.head.data.length) { // first chunk is a perfect match ret = list.shift(); } else { // result spans more than one buffer ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); } return ret; } // Copies a specified amount of characters from the list of buffered data // chunks. // This function is designed to be inlinable, so please take care when making // changes to the function body. function copyFromBufferString(n, list) { var p = list.head; var c = 1; var ret = p.data; n -= ret.length; while (p = p.next) { var str = p.data; var nb = n > str.length ? str.length : n; if (nb === str.length) ret += str;else ret += str.slice(0, n); n -= nb; if (n === 0) { if (nb === str.length) { ++c; if (p.next) list.head = p.next;else list.head = list.tail = null; } else { list.head = p; p.data = str.slice(nb); } break; } ++c; } list.length -= c; return ret; } // Copies a specified amount of bytes from the list of buffered data chunks. // This function is designed to be inlinable, so please take care when making // changes to the function body. function copyFromBuffer(n, list) { var ret = Buffer.allocUnsafe(n); var p = list.head; var c = 1; p.data.copy(ret); n -= p.data.length; while (p = p.next) { var buf = p.data; var nb = n > buf.length ? buf.length : n; buf.copy(ret, ret.length - n, 0, nb); n -= nb; if (n === 0) { if (nb === buf.length) { ++c; if (p.next) list.head = p.next;else list.head = list.tail = null; } else { list.head = p; p.data = buf.slice(nb); } break; } ++c; } list.length -= c; return ret; } function endReadable(stream) { var state = stream._readableState; // If we get here before consuming all the bytes, then that is a // bug in node. Should never happen. if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); if (!state.endEmitted) { state.ended = true; pna.nextTick(endReadableNT, state, stream); } } function endReadableNT(state, stream) { // Check that we didn't get one last unshift. if (!state.endEmitted && state.length === 0) { state.endEmitted = true; stream.readable = false; stream.emit('end'); } } function forEach(xs, f) { for (var i = 0, l = xs.length; i < l; i++) { f(xs[i], i); } } function indexOf(xs, x) { for (var i = 0, l = xs.length; i < l; i++) { if (xs[i] === x) return i; } return -1; } }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./_stream_duplex":23,"./internal/streams/BufferList":28,"./internal/streams/destroy":29,"./internal/streams/stream":30,"_process":21,"core-util-is":15,"events":12,"inherits":17,"isarray":19,"process-nextick-args":20,"safe-buffer":36,"string_decoder/":31,"util":11}],26:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // a transform stream is a readable/writable stream where you do // something with the data. Sometimes it's called a "filter", // but that's not a great name for it, since that implies a thing where // some bits pass through, and others are simply ignored. (That would // be a valid example of a transform, of course.) // // While the output is causally related to the input, it's not a // necessarily symmetric or synchronous transformation. For example, // a zlib stream might take multiple plain-text writes(), and then // emit a single compressed chunk some time in the future. // // Here's how this works: // // The Transform stream has all the aspects of the readable and writable // stream classes. When you write(chunk), that calls _write(chunk,cb) // internally, and returns false if there's a lot of pending writes // buffered up. When you call read(), that calls _read(n) until // there's enough pending readable data buffered up. // // In a transform stream, the written data is placed in a buffer. When // _read(n) is called, it transforms the queued up data, calling the // buffered _write cb's as it consumes chunks. If consuming a single // written chunk would result in multiple output chunks, then the first // outputted bit calls the readcb, and subsequent chunks just go into // the read buffer, and will cause it to emit 'readable' if necessary. // // This way, back-pressure is actually determined by the reading side, // since _read has to be called to start processing a new chunk. However, // a pathological inflate type of transform can cause excessive buffering // here. For example, imagine a stream where every byte of input is // interpreted as an integer from 0-255, and then results in that many // bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in // 1kb of data being output. In this case, you could write a very small // amount of input, and end up with a very large amount of output. In // such a pathological inflating mechanism, there'd be no way to tell // the system to stop doing the transform. A single 4MB write could // cause the system to run out of memory. // // However, even in such a pathological case, only a single written chunk // would be consumed, and then the rest would wait (un-transformed) until // the results of the previous transformed chunk were consumed. 'use strict'; module.exports = Transform; var Duplex = require('./_stream_duplex'); /**/ var util = require('core-util-is'); util.inherits = require('inherits'); /**/ util.inherits(Transform, Duplex); function afterTransform(er, data) { var ts = this._transformState; ts.transforming = false; var cb = ts.writecb; if (!cb) { return this.emit('error', new Error('write callback called multiple times')); } ts.writechunk = null; ts.writecb = null; if (data != null) // single equals check for both `null` and `undefined` this.push(data); cb(er); var rs = this._readableState; rs.reading = false; if (rs.needReadable || rs.length < rs.highWaterMark) { this._read(rs.highWaterMark); } } function Transform(options) { if (!(this instanceof Transform)) return new Transform(options); Duplex.call(this, options); this._transformState = { afterTransform: afterTransform.bind(this), needTransform: false, transforming: false, writecb: null, writechunk: null, writeencoding: null }; // start out asking for a readable event once data is transformed. this._readableState.needReadable = true; // we have implemented the _read method, and done the other things // that Readable wants before the first _read call, so unset the // sync guard flag. this._readableState.sync = false; if (options) { if (typeof options.transform === 'function') this._transform = options.transform; if (typeof options.flush === 'function') this._flush = options.flush; } // When the writable side finishes, then flush out anything remaining. this.on('prefinish', prefinish); } function prefinish() { var _this = this; if (typeof this._flush === 'function') { this._flush(function (er, data) { done(_this, er, data); }); } else { done(this, null, null); } } Transform.prototype.push = function (chunk, encoding) { this._transformState.needTransform = false; return Duplex.prototype.push.call(this, chunk, encoding); }; // This is the part where you do stuff! // override this function in implementation classes. // 'chunk' is an input chunk. // // Call `push(newChunk)` to pass along transformed output // to the readable side. You may call 'push' zero or more times. // // Call `cb(err)` when you are done with this chunk. If you pass // an error, then that'll put the hurt on the whole operation. If you // never call cb(), then you'll never get another chunk. Transform.prototype._transform = function (chunk, encoding, cb) { throw new Error('_transform() is not implemented'); }; Transform.prototype._write = function (chunk, encoding, cb) { var ts = this._transformState; ts.writecb = cb; ts.writechunk = chunk; ts.writeencoding = encoding; if (!ts.transforming) { var rs = this._readableState; if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); } }; // Doesn't matter what the args are here. // _transform does all the work. // That we got here means that the readable side wants more data. Transform.prototype._read = function (n) { var ts = this._transformState; if (ts.writechunk !== null && ts.writecb && !ts.transforming) { ts.transforming = true; this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); } else { // mark that we need a transform, so that any data that comes in // will get processed, now that we've asked for it. ts.needTransform = true; } }; Transform.prototype._destroy = function (err, cb) { var _this2 = this; Duplex.prototype._destroy.call(this, err, function (err2) { cb(err2); _this2.emit('close'); }); }; function done(stream, er, data) { if (er) return stream.emit('error', er); if (data != null) // single equals check for both `null` and `undefined` stream.push(data); // if there's nothing in the write buffer, then that means // that nothing more will ever be provided if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0'); if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming'); return stream.push(null); } },{"./_stream_duplex":23,"core-util-is":15,"inherits":17}],27:[function(require,module,exports){ (function (process,global){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // A bit simpler than readable streams. // Implement an async ._write(chunk, encoding, cb), and it'll handle all // the drain event emission and buffering. 'use strict'; /**/ var pna = require('process-nextick-args'); /**/ module.exports = Writable; /* */ function WriteReq(chunk, encoding, cb) { this.chunk = chunk; this.encoding = encoding; this.callback = cb; this.next = null; } // It seems a linked list but it is not // there will be only 2 of these for each stream function CorkedRequest(state) { var _this = this; this.next = null; this.entry = null; this.finish = function () { onCorkedFinish(_this, state); }; } /* */ /**/ var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick; /**/ /**/ var Duplex; /**/ Writable.WritableState = WritableState; /**/ var util = require('core-util-is'); util.inherits = require('inherits'); /**/ /**/ var internalUtil = { deprecate: require('util-deprecate') }; /**/ /**/ var Stream = require('./internal/streams/stream'); /**/ /**/ var Buffer = require('safe-buffer').Buffer; var OurUint8Array = global.Uint8Array || function () {}; function _uint8ArrayToBuffer(chunk) { return Buffer.from(chunk); } function _isUint8Array(obj) { return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; } /**/ var destroyImpl = require('./internal/streams/destroy'); util.inherits(Writable, Stream); function nop() {} function WritableState(options, stream) { Duplex = Duplex || require('./_stream_duplex'); options = options || {}; // Duplex streams are both readable and writable, but share // the same options object. // However, some cases require setting options to different // values for the readable and the writable sides of the duplex stream. // These options can be provided separately as readableXXX and writableXXX. var isDuplex = stream instanceof Duplex; // object stream flag to indicate whether or not this stream // contains buffers or objects. this.objectMode = !!options.objectMode; if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // the point at which write() starts returning false // Note: 0 is a valid value, means that we always return false if // the entire buffer is not flushed immediately on write() var hwm = options.highWaterMark; var writableHwm = options.writableHighWaterMark; var defaultHwm = this.objectMode ? 16 : 16 * 1024; if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm; // cast to ints. this.highWaterMark = Math.floor(this.highWaterMark); // if _final has been called this.finalCalled = false; // drain event flag. this.needDrain = false; // at the start of calling end() this.ending = false; // when end() has been called, and returned this.ended = false; // when 'finish' is emitted this.finished = false; // has it been destroyed this.destroyed = false; // should we decode strings into buffers before passing to _write? // this is here so that some node-core streams can optimize string // handling at a lower level. var noDecode = options.decodeStrings === false; this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string // encoding is 'binary' so we have to make this configurable. // Everything else in the universe uses 'utf8', though. this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurement // of how much we're waiting to get pushed to some underlying // socket or file. this.length = 0; // a flag to see when we're in the middle of a write. this.writing = false; // when true all writes will be buffered until .uncork() call this.corked = 0; // a flag to be able to tell if the onwrite cb is called immediately, // or on a later tick. We set this to true at first, because any // actions that shouldn't happen until "later" should generally also // not happen before the first write call. this.sync = true; // a flag to know if we're processing previously buffered items, which // may call the _write() callback in the same tick, so that we don't // end up in an overlapped onwrite situation. this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb) this.onwrite = function (er) { onwrite(stream, er); }; // the callback that the user supplies to write(chunk,encoding,cb) this.writecb = null; // the amount that is being written when _write is called. this.writelen = 0; this.bufferedRequest = null; this.lastBufferedRequest = null; // number of pending user-supplied write callbacks // this must be 0 before 'finish' can be emitted this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs // This is relevant for synchronous Transform streams this.prefinished = false; // True if the error was already emitted and should not be thrown again this.errorEmitted = false; // count buffered requests this.bufferedRequestCount = 0; // allocate the first CorkedRequest, there is always // one allocated and free to use, and we maintain at most two this.corkedRequestsFree = new CorkedRequest(this); } WritableState.prototype.getBuffer = function getBuffer() { var current = this.bufferedRequest; var out = []; while (current) { out.push(current); current = current.next; } return out; }; (function () { try { Object.defineProperty(WritableState.prototype, 'buffer', { get: internalUtil.deprecate(function () { return this.getBuffer(); }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') }); } catch (_) {} })(); // Test _writableState for inheritance to account for Duplex streams, // whose prototype chain only points to Readable. var realHasInstance; if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { realHasInstance = Function.prototype[Symbol.hasInstance]; Object.defineProperty(Writable, Symbol.hasInstance, { value: function (object) { if (realHasInstance.call(this, object)) return true; if (this !== Writable) return false; return object && object._writableState instanceof WritableState; } }); } else { realHasInstance = function (object) { return object instanceof this; }; } function Writable(options) { Duplex = Duplex || require('./_stream_duplex'); // Writable ctor is applied to Duplexes, too. // `realHasInstance` is necessary because using plain `instanceof` // would return false, as no `_writableState` property is attached. // Trying to use the custom `instanceof` for Writable here will also break the // Node.js LazyTransform implementation, which has a non-trivial getter for // `_writableState` that would lead to infinite recursion. if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) { return new Writable(options); } this._writableState = new WritableState(options, this); // legacy. this.writable = true; if (options) { if (typeof options.write === 'function') this._write = options.write; if (typeof options.writev === 'function') this._writev = options.writev; if (typeof options.destroy === 'function') this._destroy = options.destroy; if (typeof options.final === 'function') this._final = options.final; } Stream.call(this); } // Otherwise people can pipe Writable streams, which is just wrong. Writable.prototype.pipe = function () { this.emit('error', new Error('Cannot pipe, not readable')); }; function writeAfterEnd(stream, cb) { var er = new Error('write after end'); // TODO: defer error events consistently everywhere, not just the cb stream.emit('error', er); pna.nextTick(cb, er); } // Checks that a user-supplied chunk is valid, especially for the particular // mode the stream is in. Currently this means that `null` is never accepted // and undefined/non-string values are only allowed in object mode. function validChunk(stream, state, chunk, cb) { var valid = true; var er = false; if (chunk === null) { er = new TypeError('May not write null values to stream'); } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { er = new TypeError('Invalid non-string/buffer chunk'); } if (er) { stream.emit('error', er); pna.nextTick(cb, er); valid = false; } return valid; } Writable.prototype.write = function (chunk, encoding, cb) { var state = this._writableState; var ret = false; var isBuf = !state.objectMode && _isUint8Array(chunk); if (isBuf && !Buffer.isBuffer(chunk)) { chunk = _uint8ArrayToBuffer(chunk); } if (typeof encoding === 'function') { cb = encoding; encoding = null; } if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; if (typeof cb !== 'function') cb = nop; if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { state.pendingcb++; ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); } return ret; }; Writable.prototype.cork = function () { var state = this._writableState; state.corked++; }; Writable.prototype.uncork = function () { var state = this._writableState; if (state.corked) { state.corked--; if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); } }; Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { // node::ParseEncoding() requires lower case. if (typeof encoding === 'string') encoding = encoding.toLowerCase(); if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding); this._writableState.defaultEncoding = encoding; return this; }; function decodeChunk(state, chunk, encoding) { if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { chunk = Buffer.from(chunk, encoding); } return chunk; } // if we're already writing something, then just put this // in the queue, and wait our turn. Otherwise, call _write // If we return false, then we need a drain event, so set that flag. function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { if (!isBuf) { var newChunk = decodeChunk(state, chunk, encoding); if (chunk !== newChunk) { isBuf = true; encoding = 'buffer'; chunk = newChunk; } } var len = state.objectMode ? 1 : chunk.length; state.length += len; var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false. if (!ret) state.needDrain = true; if (state.writing || state.corked) { var last = state.lastBufferedRequest; state.lastBufferedRequest = { chunk: chunk, encoding: encoding, isBuf: isBuf, callback: cb, next: null }; if (last) { last.next = state.lastBufferedRequest; } else { state.bufferedRequest = state.lastBufferedRequest; } state.bufferedRequestCount += 1; } else { doWrite(stream, state, false, len, chunk, encoding, cb); } return ret; } function doWrite(stream, state, writev, len, chunk, encoding, cb) { state.writelen = len; state.writecb = cb; state.writing = true; state.sync = true; if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); state.sync = false; } function onwriteError(stream, state, sync, er, cb) { --state.pendingcb; if (sync) { // defer the callback if we are being called synchronously // to avoid piling up things on the stack pna.nextTick(cb, er); // this can emit finish, and it will always happen // after error pna.nextTick(finishMaybe, stream, state); stream._writableState.errorEmitted = true; stream.emit('error', er); } else { // the caller expect this to happen before if // it is async cb(er); stream._writableState.errorEmitted = true; stream.emit('error', er); // this can emit finish, but finish must // always follow error finishMaybe(stream, state); } } function onwriteStateUpdate(state) { state.writing = false; state.writecb = null; state.length -= state.writelen; state.writelen = 0; } function onwrite(stream, er) { var state = stream._writableState; var sync = state.sync; var cb = state.writecb; onwriteStateUpdate(state); if (er) onwriteError(stream, state, sync, er, cb);else { // Check if we're actually ready to finish, but don't emit yet var finished = needFinish(state); if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { clearBuffer(stream, state); } if (sync) { /**/ asyncWrite(afterWrite, stream, state, finished, cb); /**/ } else { afterWrite(stream, state, finished, cb); } } } function afterWrite(stream, state, finished, cb) { if (!finished) onwriteDrain(stream, state); state.pendingcb--; cb(); finishMaybe(stream, state); } // Must force callback to be called on nextTick, so that we don't // emit 'drain' before the write() consumer gets the 'false' return // value, and has a chance to attach a 'drain' listener. function onwriteDrain(stream, state) { if (state.length === 0 && state.needDrain) { state.needDrain = false; stream.emit('drain'); } } // if there's something in the buffer waiting, then process it function clearBuffer(stream, state) { state.bufferProcessing = true; var entry = state.bufferedRequest; if (stream._writev && entry && entry.next) { // Fast case, write everything using _writev() var l = state.bufferedRequestCount; var buffer = new Array(l); var holder = state.corkedRequestsFree; holder.entry = entry; var count = 0; var allBuffers = true; while (entry) { buffer[count] = entry; if (!entry.isBuf) allBuffers = false; entry = entry.next; count += 1; } buffer.allBuffers = allBuffers; doWrite(stream, state, true, state.length, buffer, '', holder.finish); // doWrite is almost always async, defer these to save a bit of time // as the hot path ends with doWrite state.pendingcb++; state.lastBufferedRequest = null; if (holder.next) { state.corkedRequestsFree = holder.next; holder.next = null; } else { state.corkedRequestsFree = new CorkedRequest(state); } state.bufferedRequestCount = 0; } else { // Slow case, write chunks one-by-one while (entry) { var chunk = entry.chunk; var encoding = entry.encoding; var cb = entry.callback; var len = state.objectMode ? 1 : chunk.length; doWrite(stream, state, false, len, chunk, encoding, cb); entry = entry.next; state.bufferedRequestCount--; // if we didn't call the onwrite immediately, then // it means that we need to wait until it does. // also, that means that the chunk and cb are currently // being processed, so move the buffer counter past them. if (state.writing) { break; } } if (entry === null) state.lastBufferedRequest = null; } state.bufferedRequest = entry; state.bufferProcessing = false; } Writable.prototype._write = function (chunk, encoding, cb) { cb(new Error('_write() is not implemented')); }; Writable.prototype._writev = null; Writable.prototype.end = function (chunk, encoding, cb) { var state = this._writableState; if (typeof chunk === 'function') { cb = chunk; chunk = null; encoding = null; } else if (typeof encoding === 'function') { cb = encoding; encoding = null; } if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks if (state.corked) { state.corked = 1; this.uncork(); } // ignore unnecessary end() calls. if (!state.ending && !state.finished) endWritable(this, state, cb); }; function needFinish(state) { return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; } function callFinal(stream, state) { stream._final(function (err) { state.pendingcb--; if (err) { stream.emit('error', err); } state.prefinished = true; stream.emit('prefinish'); finishMaybe(stream, state); }); } function prefinish(stream, state) { if (!state.prefinished && !state.finalCalled) { if (typeof stream._final === 'function') { state.pendingcb++; state.finalCalled = true; pna.nextTick(callFinal, stream, state); } else { state.prefinished = true; stream.emit('prefinish'); } } } function finishMaybe(stream, state) { var need = needFinish(state); if (need) { prefinish(stream, state); if (state.pendingcb === 0) { state.finished = true; stream.emit('finish'); } } return need; } function endWritable(stream, state, cb) { state.ending = true; finishMaybe(stream, state); if (cb) { if (state.finished) pna.nextTick(cb);else stream.once('finish', cb); } state.ended = true; stream.writable = false; } function onCorkedFinish(corkReq, state, err) { var entry = corkReq.entry; corkReq.entry = null; while (entry) { var cb = entry.callback; state.pendingcb--; cb(err); entry = entry.next; } if (state.corkedRequestsFree) { state.corkedRequestsFree.next = corkReq; } else { state.corkedRequestsFree = corkReq; } } Object.defineProperty(Writable.prototype, 'destroyed', { get: function () { if (this._writableState === undefined) { return false; } return this._writableState.destroyed; }, set: function (value) { // we ignore the value if the stream // has not been initialized yet if (!this._writableState) { return; } // backward compatibility, the user is explicitly // managing destroyed this._writableState.destroyed = value; } }); Writable.prototype.destroy = destroyImpl.destroy; Writable.prototype._undestroy = destroyImpl.undestroy; Writable.prototype._destroy = function (err, cb) { this.end(); cb(err); }; }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./_stream_duplex":23,"./internal/streams/destroy":29,"./internal/streams/stream":30,"_process":21,"core-util-is":15,"inherits":17,"process-nextick-args":20,"safe-buffer":36,"util-deprecate":38}],28:[function(require,module,exports){ 'use strict'; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var Buffer = require('safe-buffer').Buffer; var util = require('util'); function copyBuffer(src, target, offset) { src.copy(target, offset); } module.exports = function () { function BufferList() { _classCallCheck(this, BufferList); this.head = null; this.tail = null; this.length = 0; } BufferList.prototype.push = function push(v) { var entry = { data: v, next: null }; if (this.length > 0) this.tail.next = entry;else this.head = entry; this.tail = entry; ++this.length; }; BufferList.prototype.unshift = function unshift(v) { var entry = { data: v, next: this.head }; if (this.length === 0) this.tail = entry; this.head = entry; ++this.length; }; BufferList.prototype.shift = function shift() { if (this.length === 0) return; var ret = this.head.data; if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; --this.length; return ret; }; BufferList.prototype.clear = function clear() { this.head = this.tail = null; this.length = 0; }; BufferList.prototype.join = function join(s) { if (this.length === 0) return ''; var p = this.head; var ret = '' + p.data; while (p = p.next) { ret += s + p.data; }return ret; }; BufferList.prototype.concat = function concat(n) { if (this.length === 0) return Buffer.alloc(0); if (this.length === 1) return this.head.data; var ret = Buffer.allocUnsafe(n >>> 0); var p = this.head; var i = 0; while (p) { copyBuffer(p.data, ret, i); i += p.data.length; p = p.next; } return ret; }; return BufferList; }(); if (util && util.inspect && util.inspect.custom) { module.exports.prototype[util.inspect.custom] = function () { var obj = util.inspect({ length: this.length }); return this.constructor.name + ' ' + obj; }; } },{"safe-buffer":36,"util":11}],29:[function(require,module,exports){ 'use strict'; /**/ var pna = require('process-nextick-args'); /**/ // undocumented cb() API, needed for core, not for public API function destroy(err, cb) { var _this = this; var readableDestroyed = this._readableState && this._readableState.destroyed; var writableDestroyed = this._writableState && this._writableState.destroyed; if (readableDestroyed || writableDestroyed) { if (cb) { cb(err); } else if (err && (!this._writableState || !this._writableState.errorEmitted)) { pna.nextTick(emitErrorNT, this, err); } return this; } // we set destroyed to true before firing error callbacks in order // to make it re-entrance safe in case destroy() is called within callbacks if (this._readableState) { this._readableState.destroyed = true; } // if this is a duplex stream mark the writable part as destroyed as well if (this._writableState) { this._writableState.destroyed = true; } this._destroy(err || null, function (err) { if (!cb && err) { pna.nextTick(emitErrorNT, _this, err); if (_this._writableState) { _this._writableState.errorEmitted = true; } } else if (cb) { cb(err); } }); return this; } function undestroy() { if (this._readableState) { this._readableState.destroyed = false; this._readableState.reading = false; this._readableState.ended = false; this._readableState.endEmitted = false; } if (this._writableState) { this._writableState.destroyed = false; this._writableState.ended = false; this._writableState.ending = false; this._writableState.finished = false; this._writableState.errorEmitted = false; } } function emitErrorNT(self, err) { self.emit('error', err); } module.exports = { destroy: destroy, undestroy: undestroy }; },{"process-nextick-args":20}],30:[function(require,module,exports){ module.exports = require('events').EventEmitter; },{"events":12}],31:[function(require,module,exports){ 'use strict'; var Buffer = require('safe-buffer').Buffer; var isEncoding = Buffer.isEncoding || function (encoding) { encoding = '' + encoding; switch (encoding && encoding.toLowerCase()) { case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw': return true; default: return false; } }; function _normalizeEncoding(enc) { if (!enc) return 'utf8'; var retried; while (true) { switch (enc) { case 'utf8': case 'utf-8': return 'utf8'; case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return 'utf16le'; case 'latin1': case 'binary': return 'latin1'; case 'base64': case 'ascii': case 'hex': return enc; default: if (retried) return; // undefined enc = ('' + enc).toLowerCase(); retried = true; } } }; // Do not cache `Buffer.isEncoding` when checking encoding names as some // modules monkey-patch it to support additional encodings function normalizeEncoding(enc) { var nenc = _normalizeEncoding(enc); if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc); return nenc || enc; } // StringDecoder provides an interface for efficiently splitting a series of // buffers into a series of JS strings without breaking apart multi-byte // characters. exports.StringDecoder = StringDecoder; function StringDecoder(encoding) { this.encoding = normalizeEncoding(encoding); var nb; switch (this.encoding) { case 'utf16le': this.text = utf16Text; this.end = utf16End; nb = 4; break; case 'utf8': this.fillLast = utf8FillLast; nb = 4; break; case 'base64': this.text = base64Text; this.end = base64End; nb = 3; break; default: this.write = simpleWrite; this.end = simpleEnd; return; } this.lastNeed = 0; this.lastTotal = 0; this.lastChar = Buffer.allocUnsafe(nb); } StringDecoder.prototype.write = function (buf) { if (buf.length === 0) return ''; var r; var i; if (this.lastNeed) { r = this.fillLast(buf); if (r === undefined) return ''; i = this.lastNeed; this.lastNeed = 0; } else { i = 0; } if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i); return r || ''; }; StringDecoder.prototype.end = utf8End; // Returns only complete characters in a Buffer StringDecoder.prototype.text = utf8Text; // Attempts to complete a partial non-UTF-8 character using bytes from a Buffer StringDecoder.prototype.fillLast = function (buf) { if (this.lastNeed <= buf.length) { buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed); return this.lastChar.toString(this.encoding, 0, this.lastTotal); } buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length); this.lastNeed -= buf.length; }; // Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a // continuation byte. function utf8CheckByte(byte) { if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4; return -1; } // Checks at most 3 bytes at the end of a Buffer in order to detect an // incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4) // needed to complete the UTF-8 character (if applicable) are returned. function utf8CheckIncomplete(self, buf, i) { var j = buf.length - 1; if (j < i) return 0; var nb = utf8CheckByte(buf[j]); if (nb >= 0) { if (nb > 0) self.lastNeed = nb - 1; return nb; } if (--j < i) return 0; nb = utf8CheckByte(buf[j]); if (nb >= 0) { if (nb > 0) self.lastNeed = nb - 2; return nb; } if (--j < i) return 0; nb = utf8CheckByte(buf[j]); if (nb >= 0) { if (nb > 0) { if (nb === 2) nb = 0;else self.lastNeed = nb - 3; } return nb; } return 0; } // Validates as many continuation bytes for a multi-byte UTF-8 character as // needed or are available. If we see a non-continuation byte where we expect // one, we "replace" the validated continuation bytes we've seen so far with // UTF-8 replacement characters ('\ufffd'), to match v8's UTF-8 decoding // behavior. The continuation byte check is included three times in the case // where all of the continuation bytes for a character exist in the same buffer. // It is also done this way as a slight performance increase instead of using a // loop. function utf8CheckExtraBytes(self, buf, p) { if ((buf[0] & 0xC0) !== 0x80) { self.lastNeed = 0; return '\ufffd'.repeat(p); } if (self.lastNeed > 1 && buf.length > 1) { if ((buf[1] & 0xC0) !== 0x80) { self.lastNeed = 1; return '\ufffd'.repeat(p + 1); } if (self.lastNeed > 2 && buf.length > 2) { if ((buf[2] & 0xC0) !== 0x80) { self.lastNeed = 2; return '\ufffd'.repeat(p + 2); } } } } // Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer. function utf8FillLast(buf) { var p = this.lastTotal - this.lastNeed; var r = utf8CheckExtraBytes(this, buf, p); if (r !== undefined) return r; if (this.lastNeed <= buf.length) { buf.copy(this.lastChar, p, 0, this.lastNeed); return this.lastChar.toString(this.encoding, 0, this.lastTotal); } buf.copy(this.lastChar, p, 0, buf.length); this.lastNeed -= buf.length; } // Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a // partial character, the character's bytes are buffered until the required // number of bytes are available. function utf8Text(buf, i) { var total = utf8CheckIncomplete(this, buf, i); if (!this.lastNeed) return buf.toString('utf8', i); this.lastTotal = total; var end = buf.length - (total - this.lastNeed); buf.copy(this.lastChar, 0, end); return buf.toString('utf8', i, end); } // For UTF-8, a replacement character for each buffered byte of a (partial) // character needs to be added to the output. function utf8End(buf) { var r = buf && buf.length ? this.write(buf) : ''; if (this.lastNeed) return r + '\ufffd'.repeat(this.lastTotal - this.lastNeed); return r; } // UTF-16LE typically needs two bytes per character, but even if we have an even // number of bytes available, we need to check if we end on a leading/high // surrogate. In that case, we need to wait for the next two bytes in order to // decode the last character properly. function utf16Text(buf, i) { if ((buf.length - i) % 2 === 0) { var r = buf.toString('utf16le', i); if (r) { var c = r.charCodeAt(r.length - 1); if (c >= 0xD800 && c <= 0xDBFF) { this.lastNeed = 2; this.lastTotal = 4; this.lastChar[0] = buf[buf.length - 2]; this.lastChar[1] = buf[buf.length - 1]; return r.slice(0, -1); } } return r; } this.lastNeed = 1; this.lastTotal = 2; this.lastChar[0] = buf[buf.length - 1]; return buf.toString('utf16le', i, buf.length - 1); } // For UTF-16LE we do not explicitly append special replacement characters if we // end on a partial character, we simply let v8 handle that. function utf16End(buf) { var r = buf && buf.length ? this.write(buf) : ''; if (this.lastNeed) { var end = this.lastTotal - this.lastNeed; return r + this.lastChar.toString('utf16le', 0, end); } return r; } function base64Text(buf, i) { var n = (buf.length - i) % 3; if (n === 0) return buf.toString('base64', i); this.lastNeed = 3 - n; this.lastTotal = 3; if (n === 1) { this.lastChar[0] = buf[buf.length - 1]; } else { this.lastChar[0] = buf[buf.length - 2]; this.lastChar[1] = buf[buf.length - 1]; } return buf.toString('base64', i, buf.length - n); } function base64End(buf) { var r = buf && buf.length ? this.write(buf) : ''; if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed); return r; } // Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) function simpleWrite(buf) { return buf.toString(this.encoding); } function simpleEnd(buf) { return buf && buf.length ? this.write(buf) : ''; } },{"safe-buffer":36}],32:[function(require,module,exports){ module.exports = require('./readable').PassThrough },{"./readable":33}],33:[function(require,module,exports){ exports = module.exports = require('./lib/_stream_readable.js'); exports.Stream = exports; exports.Readable = exports; exports.Writable = require('./lib/_stream_writable.js'); exports.Duplex = require('./lib/_stream_duplex.js'); exports.Transform = require('./lib/_stream_transform.js'); exports.PassThrough = require('./lib/_stream_passthrough.js'); },{"./lib/_stream_duplex.js":23,"./lib/_stream_passthrough.js":24,"./lib/_stream_readable.js":25,"./lib/_stream_transform.js":26,"./lib/_stream_writable.js":27}],34:[function(require,module,exports){ module.exports = require('./readable').Transform },{"./readable":33}],35:[function(require,module,exports){ module.exports = require('./lib/_stream_writable.js'); },{"./lib/_stream_writable.js":27}],36:[function(require,module,exports){ /* eslint-disable node/no-deprecated-api */ var buffer = require('buffer') var Buffer = buffer.Buffer // alternative to using Object.keys for old browsers function copyProps (src, dst) { for (var key in src) { dst[key] = src[key] } } if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { module.exports = buffer } else { // Copy properties from require('buffer') copyProps(buffer, exports) exports.Buffer = SafeBuffer } function SafeBuffer (arg, encodingOrOffset, length) { return Buffer(arg, encodingOrOffset, length) } // Copy static methods from Buffer copyProps(Buffer, SafeBuffer) SafeBuffer.from = function (arg, encodingOrOffset, length) { if (typeof arg === 'number') { throw new TypeError('Argument must not be a number') } return Buffer(arg, encodingOrOffset, length) } SafeBuffer.alloc = function (size, fill, encoding) { if (typeof size !== 'number') { throw new TypeError('Argument must be a number') } var buf = Buffer(size) if (fill !== undefined) { if (typeof encoding === 'string') { buf.fill(fill, encoding) } else { buf.fill(fill) } } else { buf.fill(0) } return buf } SafeBuffer.allocUnsafe = function (size) { if (typeof size !== 'number') { throw new TypeError('Argument must be a number') } return Buffer(size) } SafeBuffer.allocUnsafeSlow = function (size) { if (typeof size !== 'number') { throw new TypeError('Argument must be a number') } return buffer.SlowBuffer(size) } },{"buffer":14}],37:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. module.exports = Stream; var EE = require('events').EventEmitter; var inherits = require('inherits'); inherits(Stream, EE); Stream.Readable = require('readable-stream/readable.js'); Stream.Writable = require('readable-stream/writable.js'); Stream.Duplex = require('readable-stream/duplex.js'); Stream.Transform = require('readable-stream/transform.js'); Stream.PassThrough = require('readable-stream/passthrough.js'); // Backwards-compat with node 0.4.x Stream.Stream = Stream; // old-style streams. Note that the pipe method (the only relevant // part of this class) is overridden in the Readable class. function Stream() { EE.call(this); } Stream.prototype.pipe = function(dest, options) { var source = this; function ondata(chunk) { if (dest.writable) { if (false === dest.write(chunk) && source.pause) { source.pause(); } } } source.on('data', ondata); function ondrain() { if (source.readable && source.resume) { source.resume(); } } dest.on('drain', ondrain); // If the 'end' option is not supplied, dest.end() will be called when // source gets the 'end' or 'close' events. Only dest.end() once. if (!dest._isStdio && (!options || options.end !== false)) { source.on('end', onend); source.on('close', onclose); } var didOnEnd = false; function onend() { if (didOnEnd) return; didOnEnd = true; dest.end(); } function onclose() { if (didOnEnd) return; didOnEnd = true; if (typeof dest.destroy === 'function') dest.destroy(); } // don't leave dangling pipes when there are errors. function onerror(er) { cleanup(); if (EE.listenerCount(this, 'error') === 0) { throw er; // Unhandled stream error in pipe. } } source.on('error', onerror); dest.on('error', onerror); // remove all the event listeners that were added. function cleanup() { source.removeListener('data', ondata); dest.removeListener('drain', ondrain); source.removeListener('end', onend); source.removeListener('close', onclose); source.removeListener('error', onerror); dest.removeListener('error', onerror); source.removeListener('end', cleanup); source.removeListener('close', cleanup); dest.removeListener('close', cleanup); } source.on('end', cleanup); source.on('close', cleanup); dest.on('close', cleanup); dest.emit('pipe', source); // Allow for unix-like usage: A.pipe(B).pipe(C) return dest; }; },{"events":12,"inherits":17,"readable-stream/duplex.js":22,"readable-stream/passthrough.js":32,"readable-stream/readable.js":33,"readable-stream/transform.js":34,"readable-stream/writable.js":35}],38:[function(require,module,exports){ (function (global){ /** * Module exports. */ module.exports = deprecate; /** * Mark that a method should not be used. * Returns a modified function which warns once by default. * * If `localStorage.noDeprecation = true` is set, then it is a no-op. * * If `localStorage.throwDeprecation = true` is set, then deprecated functions * will throw an Error when invoked. * * If `localStorage.traceDeprecation = true` is set, then deprecated functions * will invoke `console.trace()` instead of `console.error()`. * * @param {Function} fn - the function to deprecate * @param {String} msg - the string to print to the console when `fn` is invoked * @returns {Function} a new "deprecated" version of `fn` * @api public */ function deprecate (fn, msg) { if (config('noDeprecation')) { return fn; } var warned = false; function deprecated() { if (!warned) { if (config('throwDeprecation')) { throw new Error(msg); } else if (config('traceDeprecation')) { console.trace(msg); } else { console.warn(msg); } warned = true; } return fn.apply(this, arguments); } return deprecated; } /** * Checks `localStorage` for boolean values for the given `name`. * * @param {String} name * @returns {Boolean} * @api private */ function config (name) { // accessing global.localStorage can trigger a DOMException in sandboxed iframes try { if (!global.localStorage) return false; } catch (_) { return false; } var val = global.localStorage[name]; if (null == val) return false; return String(val).toLowerCase() === 'true'; } }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],39:[function(require,module,exports){ arguments[4][17][0].apply(exports,arguments) },{"dup":17}],40:[function(require,module,exports){ module.exports = function isBuffer(arg) { return arg && typeof arg === 'object' && typeof arg.copy === 'function' && typeof arg.fill === 'function' && typeof arg.readUInt8 === 'function'; } },{}],41:[function(require,module,exports){ (function (process,global){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var formatRegExp = /%[sdj%]/g; exports.format = function(f) { if (!isString(f)) { var objects = []; for (var i = 0; i < arguments.length; i++) { objects.push(inspect(arguments[i])); } return objects.join(' '); } var i = 1; var args = arguments; var len = args.length; var str = String(f).replace(formatRegExp, function(x) { if (x === '%%') return '%'; if (i >= len) return x; switch (x) { case '%s': return String(args[i++]); case '%d': return Number(args[i++]); case '%j': try { return JSON.stringify(args[i++]); } catch (_) { return '[Circular]'; } default: return x; } }); for (var x = args[i]; i < len; x = args[++i]) { if (isNull(x) || !isObject(x)) { str += ' ' + x; } else { str += ' ' + inspect(x); } } return str; }; // Mark that a method should not be used. // Returns a modified function which warns once by default. // If --no-deprecation is set, then it is a no-op. exports.deprecate = function(fn, msg) { // Allow for deprecating things in the process of starting up. if (isUndefined(global.process)) { return function() { return exports.deprecate(fn, msg).apply(this, arguments); }; } if (process.noDeprecation === true) { return fn; } var warned = false; function deprecated() { if (!warned) { if (process.throwDeprecation) { throw new Error(msg); } else if (process.traceDeprecation) { console.trace(msg); } else { console.error(msg); } warned = true; } return fn.apply(this, arguments); } return deprecated; }; var debugs = {}; var debugEnviron; exports.debuglog = function(set) { if (isUndefined(debugEnviron)) debugEnviron = process.env.NODE_DEBUG || ''; set = set.toUpperCase(); if (!debugs[set]) { if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { var pid = process.pid; debugs[set] = function() { var msg = exports.format.apply(exports, arguments); console.error('%s %d: %s', set, pid, msg); }; } else { debugs[set] = function() {}; } } return debugs[set]; }; /** * Echos the value of a value. Trys to print the value out * in the best way possible given the different types. * * @param {Object} obj The object to print out. * @param {Object} opts Optional options object that alters the output. */ /* legacy: obj, showHidden, depth, colors*/ function inspect(obj, opts) { // default options var ctx = { seen: [], stylize: stylizeNoColor }; // legacy... if (arguments.length >= 3) ctx.depth = arguments[2]; if (arguments.length >= 4) ctx.colors = arguments[3]; if (isBoolean(opts)) { // legacy... ctx.showHidden = opts; } else if (opts) { // got an "options" object exports._extend(ctx, opts); } // set default options if (isUndefined(ctx.showHidden)) ctx.showHidden = false; if (isUndefined(ctx.depth)) ctx.depth = 2; if (isUndefined(ctx.colors)) ctx.colors = false; if (isUndefined(ctx.customInspect)) ctx.customInspect = true; if (ctx.colors) ctx.stylize = stylizeWithColor; return formatValue(ctx, obj, ctx.depth); } exports.inspect = inspect; // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics inspect.colors = { 'bold' : [1, 22], 'italic' : [3, 23], 'underline' : [4, 24], 'inverse' : [7, 27], 'white' : [37, 39], 'grey' : [90, 39], 'black' : [30, 39], 'blue' : [34, 39], 'cyan' : [36, 39], 'green' : [32, 39], 'magenta' : [35, 39], 'red' : [31, 39], 'yellow' : [33, 39] }; // Don't use 'blue' not visible on cmd.exe inspect.styles = { 'special': 'cyan', 'number': 'yellow', 'boolean': 'yellow', 'undefined': 'grey', 'null': 'bold', 'string': 'green', 'date': 'magenta', // "name": intentionally not styling 'regexp': 'red' }; function stylizeWithColor(str, styleType) { var style = inspect.styles[styleType]; if (style) { return '\u001b[' + inspect.colors[style][0] + 'm' + str + '\u001b[' + inspect.colors[style][1] + 'm'; } else { return str; } } function stylizeNoColor(str, styleType) { return str; } function arrayToHash(array) { var hash = {}; array.forEach(function(val, idx) { hash[val] = true; }); return hash; } function formatValue(ctx, value, recurseTimes) { // Provide a hook for user-specified inspect functions. // Check that value is an object with an inspect function on it if (ctx.customInspect && value && isFunction(value.inspect) && // Filter out the util module, it's inspect function is special value.inspect !== exports.inspect && // Also filter out any prototype objects using the circular check. !(value.constructor && value.constructor.prototype === value)) { var ret = value.inspect(recurseTimes, ctx); if (!isString(ret)) { ret = formatValue(ctx, ret, recurseTimes); } return ret; } // Primitive types cannot have properties var primitive = formatPrimitive(ctx, value); if (primitive) { return primitive; } // Look up the keys of the object. var keys = Object.keys(value); var visibleKeys = arrayToHash(keys); if (ctx.showHidden) { keys = Object.getOwnPropertyNames(value); } // IE doesn't make error fields non-enumerable // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx if (isError(value) && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { return formatError(value); } // Some type of object without properties can be shortcutted. if (keys.length === 0) { if (isFunction(value)) { var name = value.name ? ': ' + value.name : ''; return ctx.stylize('[Function' + name + ']', 'special'); } if (isRegExp(value)) { return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); } if (isDate(value)) { return ctx.stylize(Date.prototype.toString.call(value), 'date'); } if (isError(value)) { return formatError(value); } } var base = '', array = false, braces = ['{', '}']; // Make Array say that they are Array if (isArray(value)) { array = true; braces = ['[', ']']; } // Make functions say that they are functions if (isFunction(value)) { var n = value.name ? ': ' + value.name : ''; base = ' [Function' + n + ']'; } // Make RegExps say that they are RegExps if (isRegExp(value)) { base = ' ' + RegExp.prototype.toString.call(value); } // Make dates with properties first say the date if (isDate(value)) { base = ' ' + Date.prototype.toUTCString.call(value); } // Make error with message first say the error if (isError(value)) { base = ' ' + formatError(value); } if (keys.length === 0 && (!array || value.length == 0)) { return braces[0] + base + braces[1]; } if (recurseTimes < 0) { if (isRegExp(value)) { return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); } else { return ctx.stylize('[Object]', 'special'); } } ctx.seen.push(value); var output; if (array) { output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); } else { output = keys.map(function(key) { return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); }); } ctx.seen.pop(); return reduceToSingleString(output, base, braces); } function formatPrimitive(ctx, value) { if (isUndefined(value)) return ctx.stylize('undefined', 'undefined'); if (isString(value)) { var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') .replace(/'/g, "\\'") .replace(/\\"/g, '"') + '\''; return ctx.stylize(simple, 'string'); } if (isNumber(value)) return ctx.stylize('' + value, 'number'); if (isBoolean(value)) return ctx.stylize('' + value, 'boolean'); // For some reason typeof null is "object", so special case here. if (isNull(value)) return ctx.stylize('null', 'null'); } function formatError(value) { return '[' + Error.prototype.toString.call(value) + ']'; } function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { var output = []; for (var i = 0, l = value.length; i < l; ++i) { if (hasOwnProperty(value, String(i))) { output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, String(i), true)); } else { output.push(''); } } keys.forEach(function(key) { if (!key.match(/^\d+$/)) { output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, key, true)); } }); return output; } function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { var name, str, desc; desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; if (desc.get) { if (desc.set) { str = ctx.stylize('[Getter/Setter]', 'special'); } else { str = ctx.stylize('[Getter]', 'special'); } } else { if (desc.set) { str = ctx.stylize('[Setter]', 'special'); } } if (!hasOwnProperty(visibleKeys, key)) { name = '[' + key + ']'; } if (!str) { if (ctx.seen.indexOf(desc.value) < 0) { if (isNull(recurseTimes)) { str = formatValue(ctx, desc.value, null); } else { str = formatValue(ctx, desc.value, recurseTimes - 1); } if (str.indexOf('\n') > -1) { if (array) { str = str.split('\n').map(function(line) { return ' ' + line; }).join('\n').substr(2); } else { str = '\n' + str.split('\n').map(function(line) { return ' ' + line; }).join('\n'); } } } else { str = ctx.stylize('[Circular]', 'special'); } } if (isUndefined(name)) { if (array && key.match(/^\d+$/)) { return str; } name = JSON.stringify('' + key); if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { name = name.substr(1, name.length - 2); name = ctx.stylize(name, 'name'); } else { name = name.replace(/'/g, "\\'") .replace(/\\"/g, '"') .replace(/(^"|"$)/g, "'"); name = ctx.stylize(name, 'string'); } } return name + ': ' + str; } function reduceToSingleString(output, base, braces) { var numLinesEst = 0; var length = output.reduce(function(prev, cur) { numLinesEst++; if (cur.indexOf('\n') >= 0) numLinesEst++; return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; }, 0); if (length > 60) { return braces[0] + (base === '' ? '' : base + '\n ') + ' ' + output.join(',\n ') + ' ' + braces[1]; } return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; } // NOTE: These type checking functions intentionally don't use `instanceof` // because it is fragile and can be easily faked with `Object.create()`. function isArray(ar) { return Array.isArray(ar); } exports.isArray = isArray; function isBoolean(arg) { return typeof arg === 'boolean'; } exports.isBoolean = isBoolean; function isNull(arg) { return arg === null; } exports.isNull = isNull; function isNullOrUndefined(arg) { return arg == null; } exports.isNullOrUndefined = isNullOrUndefined; function isNumber(arg) { return typeof arg === 'number'; } exports.isNumber = isNumber; function isString(arg) { return typeof arg === 'string'; } exports.isString = isString; function isSymbol(arg) { return typeof arg === 'symbol'; } exports.isSymbol = isSymbol; function isUndefined(arg) { return arg === void 0; } exports.isUndefined = isUndefined; function isRegExp(re) { return isObject(re) && objectToString(re) === '[object RegExp]'; } exports.isRegExp = isRegExp; function isObject(arg) { return typeof arg === 'object' && arg !== null; } exports.isObject = isObject; function isDate(d) { return isObject(d) && objectToString(d) === '[object Date]'; } exports.isDate = isDate; function isError(e) { return isObject(e) && (objectToString(e) === '[object Error]' || e instanceof Error); } exports.isError = isError; function isFunction(arg) { return typeof arg === 'function'; } exports.isFunction = isFunction; function isPrimitive(arg) { return arg === null || typeof arg === 'boolean' || typeof arg === 'number' || typeof arg === 'string' || typeof arg === 'symbol' || // ES6 symbol typeof arg === 'undefined'; } exports.isPrimitive = isPrimitive; exports.isBuffer = require('./support/isBuffer'); function objectToString(o) { return Object.prototype.toString.call(o); } function pad(n) { return n < 10 ? '0' + n.toString(10) : n.toString(10); } var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; // 26 Feb 16:19:34 function timestamp() { var d = new Date(); var time = [pad(d.getHours()), pad(d.getMinutes()), pad(d.getSeconds())].join(':'); return [d.getDate(), months[d.getMonth()], time].join(' '); } // log is just a thin wrapper to console.log that prepends a timestamp exports.log = function() { console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); }; /** * Inherit the prototype methods from one constructor into another. * * The Function.prototype.inherits from lang.js rewritten as a standalone * function (not on Function.prototype). NOTE: If this file is to be loaded * during bootstrapping this function needs to be rewritten using some native * functions as prototype setup using normal JavaScript does not work as * expected during bootstrapping (see mirror.js in r114903). * * @param {function} ctor Constructor function which needs to inherit the * prototype. * @param {function} superCtor Constructor function to inherit prototype from. */ exports.inherits = require('inherits'); exports._extend = function(origin, add) { // Don't do anything if add isn't an object if (!add || !isObject(add)) return origin; var keys = Object.keys(add); var i = keys.length; while (i--) { origin[keys[i]] = add[keys[i]]; } return origin; }; function hasOwnProperty(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); } }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./support/isBuffer":40,"_process":21,"inherits":39}]},{},[3])(3) });