diff --git a/Chapter03/Documentation/answers/speech_to_text_complete.js b/Chapter03/Documentation/answers/speech_to_text_complete.js
index f8d01a03..32fc46c2 100644
--- a/Chapter03/Documentation/answers/speech_to_text_complete.js
+++ b/Chapter03/Documentation/answers/speech_to_text_complete.js
@@ -18,6 +18,7 @@
var extend = require('extend');
var watson = require('watson-developer-cloud');
var vcapServices = require('vcap_services');
+var request = require('request');
// load in the environment data for our application
var config = require('../../env.json');
@@ -28,24 +29,21 @@ var config = require('../../env.json');
* @param {NodeJS Request Object} req - provides information about the inbound request
* @param {NodeJS Response Object} res - this is how we respond back to the browser
*/
-exports.token = function(req, res) {
- // the extend function adds additional information into our credentials from within the
- // Watson and Bluemix operating environment
- var sttConfig = extend(config.speech_to_text, vcapServices.getCredentials('speech_to_text'));
- // request authorization to access the service
- var sttAuthService = watson.authorization(sttConfig);
-
- // now that we're authenticated, get the token
- sttAuthService.getToken({
- url: sttConfig.url
- }, function(err, token) {
- if (err) {
- // send an error back if we cannot retrieve the token successfully
- console.log('Error retrieving token: ', err);
- res.status(500).send('Error retrieving token'+ReferenceError);
- return;
- }
- // if we're successful, then send the new token back to the browser
- res.send(token);
+exports.stt_token = function(req, res) {
+ var methodName = 'stt_token';
+ // The following three lines translate the curl request provided by IBM into a nodeJS request format so that the token can be retrieved by your server code.
+ var form = { grant_type: 'urn:ibm:params:oauth:grant-type:apikey', apikey: config.speech_to_text.apikey }
+ var headers = { 'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'application/json' };
+ var options = { url: 'https://iam.bluemix.net/identity/token', method: 'POST', form: form, headers: headers };
+
+ // get the new token
+ request(options, function (error, response, body)
+ {
+ if (!error && response.statusCode == 200)
+ // send the token back as the 'success' item in the returned json object
+ { res.send({success: JSON.parse(body).access_token}); }
+ else
+ // send the failure message back as the 'failed' item in the returned json object.
+ { console.log(methodName+' error: ', error); res.send({failed: error.message}) }
});
}
diff --git a/Chapter03/Documentation/answers/z2c-speech_complete.js b/Chapter03/Documentation/answers/z2c-speech_complete.js
index bfb34d40..ab85ef12 100644
--- a/Chapter03/Documentation/answers/z2c-speech_complete.js
+++ b/Chapter03/Documentation/answers/z2c-speech_complete.js
@@ -16,14 +16,26 @@
/*
** z2c-speech.js
*/
+
+var stt_token;
/**
* initPage is called by the browser once all files have loaded from the server.
* This is specified in the index.html file via the
statement
*/
function initPage ()
{
+ var methodName = 'initPage';
// define the variables we need to access the microphone and stop icons in the web page
var _mic = $('#microphone'); var _stop = $("#stop");
+ $.when($.get('/api/speech-to-text/token')).done(
+ function(_token)
+ { if (_token.success != 'undefined')
+ {stt_token = _token.success; console.log(methodName+' stt_token request succeeded.');}
+ else
+ {stt_token = null; console.log(methodName+' token request failed with: ',_token.failed);}
+ }
+ );
+
// start things off by enabling the microphone button and disabling the stop recording button
_mic.addClass("mic_enabled");
_stop.addClass("mic_disabled");
@@ -31,7 +43,6 @@ function initPage ()
// Identify what to do when the microphone button has been clicked
_mic.on("click", function ()
{
- var _className = this.className;
// if the microphone button is enabled, then do the following.
// otherwise, ignore the mouse button click
if(this.className == "mic_enabled")
@@ -50,18 +61,15 @@ function initPage ()
// I'll leave it to you to make this change, it's pretty simple
// and will make your app run more smoothly
//
- $.when($.get('/api/speech-to-text/token')).done(
- function (token) {
- // the stream is what comes in from the microphone
- stream = WatsonSpeech.SpeechToText.recognizeMicrophone({
- // it needs the token received from the server
- token: token,
- // and the outputElement is the html element defined with an id="speech" statement
- outputElement: '#speech' // CSS selector or DOM Element
- });
- // if there's an error in this process, log it to the browser console.
- stream.on('error', function(err) { console.log(err); });
+ // the stream is what comes in from the microphone
+ stream = WatsonSpeech.SpeechToText.recognizeMicrophone({
+ // it needs the token received from the server
+ access_token: stt_token,
+ // and the outputElement is the html element defined with an id="speech" statement
+ outputElement: '#speech' // CSS selector or DOM Element
});
+ // if there's an error in this process, log it to the browser console.
+ stream.on('error', function(err) { console.log(err); });
}
});
diff --git a/Chapter03/HTML/js/watson-speech.js b/Chapter03/HTML/js/watson-speech.js
index deab240a..680d93b2 100755
--- a/Chapter03/HTML/js/watson-speech.js
+++ b/Chapter03/HTML/js/watson-speech.js
@@ -1,172 +1,84 @@
-(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.WatsonSpeech = f()}})(function(){var define,module,exports;return (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 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
- placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0
-
- // base64 is 4/3 + up to two characters of the original data
- 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, j = 0; i < l; i += 4, j += 3) {
- 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) + (uint8[i + 1] << 8) + (uint8[i + 2])
- 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('')
-}
-
-},{}],3:[function(require,module,exports){
-
-},{}],4:[function(require,module,exports){
-(function (global){
-/*!
+(function webpackUniversalModuleDefinition(root, factory) {
+ if(typeof exports === 'object' && typeof module === 'object')
+ module.exports = factory();
+ else if(typeof define === 'function' && define.amd)
+ define([], factory);
+ else if(typeof exports === 'object')
+ exports["WatsonSpeech"] = factory();
+ else
+ root["WatsonSpeech"] = factory();
+})(typeof self !== 'undefined' ? self : this, function() {
+return /******/ (function(modules) { // webpackBootstrap
+/******/ // The module cache
+/******/ var installedModules = {};
+/******/
+/******/ // The require function
+/******/ function __webpack_require__(moduleId) {
+/******/
+/******/ // Check if module is in cache
+/******/ if(installedModules[moduleId]) {
+/******/ return installedModules[moduleId].exports;
+/******/ }
+/******/ // Create a new module (and put it into the cache)
+/******/ var module = installedModules[moduleId] = {
+/******/ i: moduleId,
+/******/ l: false,
+/******/ exports: {}
+/******/ };
+/******/
+/******/ // Execute the module function
+/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
+/******/
+/******/ // Flag the module as loaded
+/******/ module.l = true;
+/******/
+/******/ // Return the exports of the module
+/******/ return module.exports;
+/******/ }
+/******/
+/******/
+/******/ // expose the modules object (__webpack_modules__)
+/******/ __webpack_require__.m = modules;
+/******/
+/******/ // expose the module cache
+/******/ __webpack_require__.c = installedModules;
+/******/
+/******/ // define getter function for harmony exports
+/******/ __webpack_require__.d = function(exports, name, getter) {
+/******/ if(!__webpack_require__.o(exports, name)) {
+/******/ Object.defineProperty(exports, name, {
+/******/ configurable: false,
+/******/ enumerable: true,
+/******/ get: getter
+/******/ });
+/******/ }
+/******/ };
+/******/
+/******/ // getDefaultExport function for compatibility with non-harmony modules
+/******/ __webpack_require__.n = function(module) {
+/******/ var getter = module && module.__esModule ?
+/******/ function getDefault() { return module['default']; } :
+/******/ function getModuleExports() { return module; };
+/******/ __webpack_require__.d(getter, 'a', getter);
+/******/ return getter;
+/******/ };
+/******/
+/******/ // Object.prototype.hasOwnProperty.call
+/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
+/******/
+/******/ // __webpack_public_path__
+/******/ __webpack_require__.p = "";
+/******/
+/******/ // Load entry module and return exports
+/******/ return __webpack_require__(__webpack_require__.s = 37);
+/******/ })
+/************************************************************************/
+/******/ ([
+/* 0 */
+/***/ (function(module, exports, __webpack_require__) {
+
+"use strict";
+/* WEBPACK VAR INJECTION */(function(global) {/*!
* The buffer module from node.js, for the browser.
*
* @author Feross Aboukhadijeh
@@ -174,18 +86,15 @@ function fromByteArray (uint8) {
*/
/* eslint-disable no-proto */
-'use strict'
-var base64 = require('base64-js')
-var ieee754 = require('ieee754')
-var isArray = require('isarray')
+
+var base64 = __webpack_require__(39)
+var ieee754 = __webpack_require__(40)
+var isArray = __webpack_require__(23)
exports.Buffer = Buffer
exports.SlowBuffer = SlowBuffer
exports.INSPECT_MAX_BYTES = 50
-Buffer.poolSize = 8192 // not used by this implementation
-
-var rootParent = {}
/**
* If `Buffer.TYPED_ARRAY_SUPPORT`:
@@ -215,10 +124,15 @@ Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined
? global.TYPED_ARRAY_SUPPORT
: typedArraySupport()
+/*
+ * Export kMaxLength after typed array support is determined.
+ */
+exports.kMaxLength = kMaxLength()
+
function typedArraySupport () {
try {
var arr = new Uint8Array(1)
- arr.foo = function () { return 42 }
+ arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }}
return arr.foo() === 42 && // typed array instances can be augmented
typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`
arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`
@@ -233,6 +147,25 @@ function kMaxLength () {
: 0x3fffffff
}
+function createBuffer (that, length) {
+ if (kMaxLength() < length) {
+ throw new RangeError('Invalid typed array length')
+ }
+ if (Buffer.TYPED_ARRAY_SUPPORT) {
+ // Return an augmented `Uint8Array` instance, for best performance
+ that = new Uint8Array(length)
+ that.__proto__ = Buffer.prototype
+ } else {
+ // Fallback: Return an object instance of the Buffer class
+ if (that === null) {
+ that = new Buffer(length)
+ }
+ that.length = length
+ }
+
+ return that
+}
+
/**
* The Buffer constructor returns instances of `Uint8Array` that have their
* prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
@@ -242,187 +175,224 @@ function kMaxLength () {
*
* The `Uint8Array` prototype remains unmodified.
*/
-function Buffer (arg) {
- if (!(this instanceof Buffer)) {
- // Avoid going through an ArgumentsAdaptorTrampoline in the common case.
- if (arguments.length > 1) return new Buffer(arg, arguments[1])
- return new Buffer(arg)
- }
- if (!Buffer.TYPED_ARRAY_SUPPORT) {
- this.length = 0
- this.parent = undefined
+function Buffer (arg, encodingOrOffset, length) {
+ if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) {
+ return new Buffer(arg, encodingOrOffset, length)
}
// Common case.
if (typeof arg === 'number') {
- return fromNumber(this, arg)
- }
-
- // Slightly less common case.
- if (typeof arg === 'string') {
- return fromString(this, arg, arguments.length > 1 ? arguments[1] : 'utf8')
+ if (typeof encodingOrOffset === 'string') {
+ throw new Error(
+ 'If encoding is specified then the first argument must be a string'
+ )
+ }
+ return allocUnsafe(this, arg)
}
-
- // Unusual.
- return fromObject(this, arg)
+ return from(this, arg, encodingOrOffset, length)
}
+Buffer.poolSize = 8192 // not used by this implementation
+
// TODO: Legacy, not needed anymore. Remove in next major version.
Buffer._augment = function (arr) {
arr.__proto__ = Buffer.prototype
return arr
}
-function fromNumber (that, length) {
- that = allocate(that, length < 0 ? 0 : checked(length) | 0)
- if (!Buffer.TYPED_ARRAY_SUPPORT) {
- for (var i = 0; i < length; i++) {
- that[i] = 0
- }
+function from (that, value, encodingOrOffset, length) {
+ if (typeof value === 'number') {
+ throw new TypeError('"value" argument must not be a number')
}
- return that
-}
-function fromString (that, string, encoding) {
- if (typeof encoding !== 'string' || encoding === '') encoding = 'utf8'
+ if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {
+ return fromArrayBuffer(that, value, encodingOrOffset, length)
+ }
- // Assumption: byteLength() return value is always < kMaxLength.
- var length = byteLength(string, encoding) | 0
- that = allocate(that, length)
+ if (typeof value === 'string') {
+ return fromString(that, value, encodingOrOffset)
+ }
- that.write(string, encoding)
- return that
+ return fromObject(that, value)
}
-function fromObject (that, object) {
- if (Buffer.isBuffer(object)) return fromBuffer(that, object)
-
- if (isArray(object)) return fromArray(that, object)
+/**
+ * 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(null, value, encodingOrOffset, length)
+}
- if (object == null) {
- throw new TypeError('must start with number, buffer, array or string')
+if (Buffer.TYPED_ARRAY_SUPPORT) {
+ Buffer.prototype.__proto__ = Uint8Array.prototype
+ Buffer.__proto__ = Uint8Array
+ if (typeof Symbol !== 'undefined' && Symbol.species &&
+ Buffer[Symbol.species] === Buffer) {
+ // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
+ Object.defineProperty(Buffer, Symbol.species, {
+ value: null,
+ configurable: true
+ })
}
+}
- if (typeof ArrayBuffer !== 'undefined') {
- if (object.buffer instanceof ArrayBuffer) {
- return fromTypedArray(that, object)
- }
- if (object instanceof ArrayBuffer) {
- return fromArrayBuffer(that, object)
- }
+function assertSize (size) {
+ if (typeof size !== 'number') {
+ throw new TypeError('"size" argument must be a number')
+ } else if (size < 0) {
+ throw new RangeError('"size" argument must not be negative')
}
+}
- if (object.length) return fromArrayLike(that, object)
+function alloc (that, size, fill, encoding) {
+ assertSize(size)
+ if (size <= 0) {
+ return createBuffer(that, 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(that, size).fill(fill, encoding)
+ : createBuffer(that, size).fill(fill)
+ }
+ return createBuffer(that, size)
+}
- return fromJsonObject(that, object)
+/**
+ * Creates a new filled Buffer instance.
+ * alloc(size[, fill[, encoding]])
+ **/
+Buffer.alloc = function (size, fill, encoding) {
+ return alloc(null, size, fill, encoding)
}
-function fromBuffer (that, buffer) {
- var length = checked(buffer.length) | 0
- that = allocate(that, length)
- buffer.copy(that, 0, 0, length)
+function allocUnsafe (that, size) {
+ assertSize(size)
+ that = createBuffer(that, size < 0 ? 0 : checked(size) | 0)
+ if (!Buffer.TYPED_ARRAY_SUPPORT) {
+ for (var i = 0; i < size; ++i) {
+ that[i] = 0
+ }
+ }
return that
}
-function fromArray (that, array) {
- var length = checked(array.length) | 0
- that = allocate(that, length)
- for (var i = 0; i < length; i += 1) {
- that[i] = array[i] & 255
+/**
+ * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
+ * */
+Buffer.allocUnsafe = function (size) {
+ return allocUnsafe(null, size)
+}
+/**
+ * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
+ */
+Buffer.allocUnsafeSlow = function (size) {
+ return allocUnsafe(null, size)
+}
+
+function fromString (that, string, encoding) {
+ if (typeof encoding !== 'string' || encoding === '') {
+ encoding = 'utf8'
+ }
+
+ if (!Buffer.isEncoding(encoding)) {
+ throw new TypeError('"encoding" must be a valid string encoding')
+ }
+
+ var length = byteLength(string, encoding) | 0
+ that = createBuffer(that, length)
+
+ var actual = that.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')
+ that = that.slice(0, actual)
}
+
return that
}
-// Duplicate of fromArray() to keep fromArray() monomorphic.
-function fromTypedArray (that, array) {
- var length = checked(array.length) | 0
- that = allocate(that, length)
- // Truncating the elements is probably not what people expect from typed
- // arrays with BYTES_PER_ELEMENT > 1 but it's compatible with the behavior
- // of the old Buffer constructor.
+function fromArrayLike (that, array) {
+ var length = array.length < 0 ? 0 : checked(array.length) | 0
+ that = createBuffer(that, length)
for (var i = 0; i < length; i += 1) {
that[i] = array[i] & 255
}
return that
}
-function fromArrayBuffer (that, array) {
+function fromArrayBuffer (that, array, byteOffset, length) {
array.byteLength // this throws if `array` is not a valid ArrayBuffer
+ if (byteOffset < 0 || array.byteLength < byteOffset) {
+ throw new RangeError('\'offset\' is out of bounds')
+ }
+
+ if (array.byteLength < byteOffset + (length || 0)) {
+ throw new RangeError('\'length\' is out of bounds')
+ }
+
+ if (byteOffset === undefined && length === undefined) {
+ array = new Uint8Array(array)
+ } else if (length === undefined) {
+ array = new Uint8Array(array, byteOffset)
+ } else {
+ array = new Uint8Array(array, byteOffset, length)
+ }
+
if (Buffer.TYPED_ARRAY_SUPPORT) {
// Return an augmented `Uint8Array` instance, for best performance
- that = new Uint8Array(array)
+ that = array
that.__proto__ = Buffer.prototype
} else {
// Fallback: Return an object instance of the Buffer class
- that = fromTypedArray(that, new Uint8Array(array))
+ that = fromArrayLike(that, array)
}
return that
}
-function fromArrayLike (that, array) {
- var length = checked(array.length) | 0
- that = allocate(that, length)
- for (var i = 0; i < length; i += 1) {
- that[i] = array[i] & 255
- }
- return that
-}
+function fromObject (that, obj) {
+ if (Buffer.isBuffer(obj)) {
+ var len = checked(obj.length) | 0
+ that = createBuffer(that, len)
-// Deserialize { type: 'Buffer', data: [1,2,3,...] } into a Buffer object.
-// Returns a zero-length buffer for inputs that don't conform to the spec.
-function fromJsonObject (that, object) {
- var array
- var length = 0
+ if (that.length === 0) {
+ return that
+ }
- if (object.type === 'Buffer' && isArray(object.data)) {
- array = object.data
- length = checked(array.length) | 0
+ obj.copy(that, 0, 0, len)
+ return that
}
- that = allocate(that, length)
- for (var i = 0; i < length; i += 1) {
- that[i] = array[i] & 255
+ if (obj) {
+ if ((typeof ArrayBuffer !== 'undefined' &&
+ obj.buffer instanceof ArrayBuffer) || 'length' in obj) {
+ if (typeof obj.length !== 'number' || isnan(obj.length)) {
+ return createBuffer(that, 0)
+ }
+ return fromArrayLike(that, obj)
+ }
+
+ if (obj.type === 'Buffer' && isArray(obj.data)) {
+ return fromArrayLike(that, obj.data)
+ }
}
- return that
-}
-
-if (Buffer.TYPED_ARRAY_SUPPORT) {
- Buffer.prototype.__proto__ = Uint8Array.prototype
- Buffer.__proto__ = Uint8Array
- if (typeof Symbol !== 'undefined' && Symbol.species &&
- Buffer[Symbol.species] === Buffer) {
- // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
- Object.defineProperty(Buffer, Symbol.species, {
- value: null,
- configurable: true
- })
- }
-} else {
- // pre-set for values that may exist in the future
- Buffer.prototype.length = undefined
- Buffer.prototype.parent = undefined
-}
-
-function allocate (that, length) {
- if (Buffer.TYPED_ARRAY_SUPPORT) {
- // Return an augmented `Uint8Array` instance, for best performance
- that = new Uint8Array(length)
- that.__proto__ = Buffer.prototype
- } else {
- // Fallback: Return an object instance of the Buffer class
- that.length = length
- }
-
- var fromPool = length !== 0 && length <= Buffer.poolSize >>> 1
- if (fromPool) that.parent = rootParent
-
- return that
+
+ throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')
}
function checked (length) {
- // Note: cannot use `length < kMaxLength` here because that fails when
+ // Note: cannot use `length < kMaxLength()` here because that fails when
// length is NaN (which is otherwise coerced to zero.)
if (length >= kMaxLength()) {
throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
@@ -431,12 +401,11 @@ function checked (length) {
return length | 0
}
-function SlowBuffer (subject, encoding) {
- if (!(this instanceof SlowBuffer)) return new SlowBuffer(subject, encoding)
-
- var buf = new Buffer(subject, encoding)
- delete buf.parent
- return buf
+function SlowBuffer (length) {
+ if (+length != length) { // eslint-disable-line eqeqeq
+ length = 0
+ }
+ return Buffer.alloc(+length)
}
Buffer.isBuffer = function isBuffer (b) {
@@ -472,9 +441,9 @@ Buffer.isEncoding = function isEncoding (encoding) {
case 'utf8':
case 'utf-8':
case 'ascii':
+ case 'latin1':
case 'binary':
case 'base64':
- case 'raw':
case 'ucs2':
case 'ucs-2':
case 'utf16le':
@@ -486,32 +455,46 @@ Buffer.isEncoding = function isEncoding (encoding) {
}
Buffer.concat = function concat (list, length) {
- if (!isArray(list)) throw new TypeError('list argument must be an Array of Buffers.')
+ if (!isArray(list)) {
+ throw new TypeError('"list" argument must be an Array of Buffers')
+ }
if (list.length === 0) {
- return new Buffer(0)
+ return Buffer.alloc(0)
}
var i
if (length === undefined) {
length = 0
- for (i = 0; i < list.length; i++) {
+ for (i = 0; i < list.length; ++i) {
length += list[i].length
}
}
- var buf = new Buffer(length)
+ var buffer = Buffer.allocUnsafe(length)
var pos = 0
- for (i = 0; i < list.length; i++) {
- var item = list[i]
- item.copy(buf, pos)
- pos += item.length
+ for (i = 0; i < list.length; ++i) {
+ var buf = list[i]
+ if (!Buffer.isBuffer(buf)) {
+ throw new TypeError('"list" argument must be an Array of Buffers')
+ }
+ buf.copy(buffer, pos)
+ pos += buf.length
}
- return buf
+ return buffer
}
function byteLength (string, encoding) {
- if (typeof string !== 'string') string = '' + string
+ if (Buffer.isBuffer(string)) {
+ return string.length
+ }
+ if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' &&
+ (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {
+ return string.byteLength
+ }
+ if (typeof string !== 'string') {
+ string = '' + string
+ }
var len = string.length
if (len === 0) return 0
@@ -521,13 +504,12 @@ function byteLength (string, encoding) {
for (;;) {
switch (encoding) {
case 'ascii':
+ case 'latin1':
case 'binary':
- // Deprecated
- case 'raw':
- case 'raws':
return len
case 'utf8':
case 'utf-8':
+ case undefined:
return utf8ToBytes(string).length
case 'ucs2':
case 'ucs-2':
@@ -550,13 +532,39 @@ Buffer.byteLength = byteLength
function slowToString (encoding, start, end) {
var loweredCase = false
- start = start | 0
- end = end === undefined || end === Infinity ? this.length : end | 0
+ // 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'
- if (start < 0) start = 0
- if (end > this.length) end = this.length
- if (end <= start) return ''
while (true) {
switch (encoding) {
@@ -570,8 +578,9 @@ function slowToString (encoding, start, end) {
case 'ascii':
return asciiSlice(this, start, end)
+ case 'latin1':
case 'binary':
- return binarySlice(this, start, end)
+ return latin1Slice(this, start, end)
case 'base64':
return base64Slice(this, start, end)
@@ -594,6 +603,49 @@ function slowToString (encoding, start, end) {
// Buffer instances.
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 | 0
if (length === 0) return ''
@@ -617,50 +669,197 @@ Buffer.prototype.inspect = function inspect () {
return ''
}
-Buffer.prototype.compare = function compare (b) {
- if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
- return Buffer.compare(this, b)
-}
+Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
+ if (!Buffer.isBuffer(target)) {
+ throw new TypeError('Argument must be a Buffer')
+ }
+
+ 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)
-Buffer.prototype.indexOf = function indexOf (val, byteOffset) {
- if (byteOffset > 0x7fffffff) byteOffset = 0x7fffffff
- else if (byteOffset < -0x80000000) byteOffset = -0x80000000
- byteOffset >>= 0
+ var thisCopy = this.slice(thisStart, thisEnd)
+ var targetCopy = target.slice(start, end)
- if (this.length === 0) return -1
- if (byteOffset >= this.length) return -1
+ for (var i = 0; i < len; ++i) {
+ if (thisCopy[i] !== targetCopy[i]) {
+ x = thisCopy[i]
+ y = targetCopy[i]
+ break
+ }
+ }
- // Negative offsets start from the end of the buffer
- if (byteOffset < 0) byteOffset = Math.max(this.length + byteOffset, 0)
+ 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 (isNaN(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') {
- if (val.length === 0) return -1 // special case: looking for empty string always fails
- return String.prototype.indexOf.call(this, val, byteOffset)
+ val = Buffer.from(val, encoding)
}
+
+ // Finally, search either indexOf (if dir is true) or lastIndexOf
if (Buffer.isBuffer(val)) {
- return arrayIndexOf(this, val, byteOffset)
+ // 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 (Buffer.TYPED_ARRAY_SUPPORT &&
+ 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)
}
- if (typeof val === 'number') {
- if (Buffer.TYPED_ARRAY_SUPPORT && Uint8Array.prototype.indexOf === 'function') {
- return Uint8Array.prototype.indexOf.call(this, val, byteOffset)
+
+ 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
}
- return arrayIndexOf(this, [ val ], byteOffset)
}
- function arrayIndexOf (arr, val, byteOffset) {
+ function read (buf, i) {
+ if (indexSize === 1) {
+ return buf[i]
+ } else {
+ return buf.readUInt16BE(i * indexSize)
+ }
+ }
+
+ var i
+ if (dir) {
var foundIndex = -1
- for (var i = 0; byteOffset + i < arr.length; i++) {
- if (arr[byteOffset + i] === val[foundIndex === -1 ? 0 : i - foundIndex]) {
+ 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 === val.length) return byteOffset + foundIndex
+ if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
} else {
+ if (foundIndex !== -1) i -= i - foundIndex
foundIndex = -1
}
}
- return -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
+ }
}
- throw new TypeError('val must be string, number or Buffer')
+ 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) {
@@ -677,14 +876,14 @@ function hexWrite (buf, string, offset, length) {
// must be an even number of digits
var strLen = string.length
- if (strLen % 2 !== 0) throw new Error('Invalid hex string')
+ if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')
if (length > strLen / 2) {
length = strLen / 2
}
- for (var i = 0; i < length; i++) {
+ for (var i = 0; i < length; ++i) {
var parsed = parseInt(string.substr(i * 2, 2), 16)
- if (isNaN(parsed)) throw new Error('Invalid hex string')
+ if (isNaN(parsed)) return i
buf[offset + i] = parsed
}
return i
@@ -698,7 +897,7 @@ function asciiWrite (buf, string, offset, length) {
return blitBuffer(asciiToBytes(string), buf, offset, length)
}
-function binaryWrite (buf, string, offset, length) {
+function latin1Write (buf, string, offset, length) {
return asciiWrite(buf, string, offset, length)
}
@@ -733,17 +932,16 @@ Buffer.prototype.write = function write (string, offset, length, encoding) {
}
// legacy write(string, encoding, offset, length) - remove in v0.13
} else {
- var swap = encoding
- encoding = offset
- offset = length | 0
- length = swap
+ 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')
+ throw new RangeError('Attempt to write outside buffer bounds')
}
if (!encoding) encoding = 'utf8'
@@ -761,8 +959,9 @@ Buffer.prototype.write = function write (string, offset, length, encoding) {
case 'ascii':
return asciiWrite(this, string, offset, length)
+ case 'latin1':
case 'binary':
- return binaryWrite(this, string, offset, length)
+ return latin1Write(this, string, offset, length)
case 'base64':
// Warning: maxLength not taken into account in base64Write
@@ -897,17 +1096,17 @@ function asciiSlice (buf, start, end) {
var ret = ''
end = Math.min(buf.length, end)
- for (var i = start; i < end; i++) {
+ for (var i = start; i < end; ++i) {
ret += String.fromCharCode(buf[i] & 0x7F)
}
return ret
}
-function binarySlice (buf, start, end) {
+function latin1Slice (buf, start, end) {
var ret = ''
end = Math.min(buf.length, end)
- for (var i = start; i < end; i++) {
+ for (var i = start; i < end; ++i) {
ret += String.fromCharCode(buf[i])
}
return ret
@@ -920,7 +1119,7 @@ function hexSlice (buf, start, end) {
if (!end || end < 0 || end > len) end = len
var out = ''
- for (var i = start; i < end; i++) {
+ for (var i = start; i < end; ++i) {
out += toHex(buf[i])
}
return out
@@ -963,13 +1162,11 @@ Buffer.prototype.slice = function slice (start, end) {
} else {
var sliceLen = end - start
newBuf = new Buffer(sliceLen, undefined)
- for (var i = 0; i < sliceLen; i++) {
+ for (var i = 0; i < sliceLen; ++i) {
newBuf[i] = this[i + start]
}
}
- if (newBuf.length) newBuf.parent = this.parent || this
-
return newBuf
}
@@ -1138,16 +1335,19 @@ Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
}
function checkInt (buf, value, offset, ext, max, min) {
- if (!Buffer.isBuffer(buf)) throw new TypeError('buffer must be a Buffer instance')
- if (value > max || value < min) throw new RangeError('value is out of bounds')
- if (offset + ext > buf.length) throw new RangeError('index out of range')
+ 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) checkInt(this, value, offset, byteLength, Math.pow(2, 8 * 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
@@ -1163,7 +1363,10 @@ Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength,
value = +value
offset = offset | 0
byteLength = byteLength | 0
- if (!noAssert) checkInt(this, value, offset, byteLength, Math.pow(2, 8 * 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
@@ -1186,7 +1389,7 @@ Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
function objectWriteUInt16 (buf, value, offset, littleEndian) {
if (value < 0) value = 0xffff + value + 1
- for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; i++) {
+ for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) {
buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
(littleEndian ? i : 1 - i) * 8
}
@@ -1220,7 +1423,7 @@ Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert
function objectWriteUInt32 (buf, value, offset, littleEndian) {
if (value < 0) value = 0xffffffff + value + 1
- for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; i++) {
+ for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) {
buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff
}
}
@@ -1266,9 +1469,12 @@ Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, no
var i = 0
var mul = 1
- var sub = value < 0 ? 1 : 0
+ 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
}
@@ -1286,9 +1492,12 @@ Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, no
var i = byteLength - 1
var mul = 1
- var sub = value < 0 ? 1 : 0
+ 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
}
@@ -1363,8 +1572,8 @@ Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert)
}
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')
+ 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) {
@@ -1429,12 +1638,12 @@ Buffer.prototype.copy = function copy (target, targetStart, start, end) {
if (this === target && start < targetStart && targetStart < end) {
// descending copy from end
- for (i = len - 1; i >= 0; i--) {
+ for (i = len - 1; i >= 0; --i) {
target[i + targetStart] = this[i + start]
}
} else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
// ascending copy from start
- for (i = 0; i < len; i++) {
+ for (i = 0; i < len; ++i) {
target[i + targetStart] = this[i + start]
}
} else {
@@ -1448,31 +1657,63 @@ Buffer.prototype.copy = function copy (target, targetStart, start, end) {
return len
}
-// fill(value, start=0, end=buffer.length)
-Buffer.prototype.fill = function fill (value, start, end) {
- if (!value) value = 0
- if (!start) start = 0
- if (!end) end = this.length
+// 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 (val.length === 1) {
+ var code = val.charCodeAt(0)
+ if (code < 256) {
+ val = code
+ }
+ }
+ 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)
+ }
+ } else if (typeof val === 'number') {
+ val = val & 255
+ }
- if (end < start) throw new RangeError('end < start')
+ // 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
+ }
- // Fill 0 bytes; we're done
- if (end === start) return
- if (this.length === 0) return
+ start = start >>> 0
+ end = end === undefined ? this.length : end >>> 0
- if (start < 0 || start >= this.length) throw new RangeError('start out of bounds')
- if (end < 0 || end > this.length) throw new RangeError('end out of bounds')
+ if (!val) val = 0
var i
- if (typeof value === 'number') {
- for (i = start; i < end; i++) {
- this[i] = value
+ if (typeof val === 'number') {
+ for (i = start; i < end; ++i) {
+ this[i] = val
}
} else {
- var bytes = utf8ToBytes(value.toString())
+ var bytes = Buffer.isBuffer(val)
+ ? val
+ : utf8ToBytes(new Buffer(val, encoding).toString())
var len = bytes.length
- for (i = start; i < end; i++) {
- this[i] = bytes[i % len]
+ for (i = 0; i < end - start; ++i) {
+ this[i + start] = bytes[i % len]
}
}
@@ -1513,7 +1754,7 @@ function utf8ToBytes (string, units) {
var leadSurrogate = null
var bytes = []
- for (var i = 0; i < length; i++) {
+ for (var i = 0; i < length; ++i) {
codePoint = string.charCodeAt(i)
// is surrogate component
@@ -1588,7 +1829,7 @@ function utf8ToBytes (string, units) {
function asciiToBytes (str) {
var byteArray = []
- for (var i = 0; i < str.length; i++) {
+ 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)
}
@@ -1598,7 +1839,7 @@ function asciiToBytes (str) {
function utf16leToBytes (str, units) {
var c, hi, lo
var byteArray = []
- for (var i = 0; i < str.length; i++) {
+ for (var i = 0; i < str.length; ++i) {
if ((units -= 2) < 0) break
c = str.charCodeAt(i)
@@ -1616,315 +1857,376 @@ function base64ToBytes (str) {
}
function blitBuffer (src, dst, offset, length) {
- for (var i = 0; i < length; i++) {
+ for (var i = 0; i < length; ++i) {
if ((i + offset >= dst.length) || (i >= src.length)) break
dst[i + offset] = src[i]
}
return i
}
-}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
+function isnan (val) {
+ return val !== val // eslint-disable-line no-self-compare
+}
-},{"base64-js":2,"ieee754":11,"isarray":5}],5:[function(require,module,exports){
-var toString = {}.toString;
+/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(5)))
-module.exports = Array.isArray || function (arr) {
- return toString.call(arr) == '[object Array]';
-};
+/***/ }),
+/* 1 */
+/***/ (function(module, exports, __webpack_require__) {
-},{}],6:[function(require,module,exports){
-(function (Buffer){
-var clone = (function() {
-'use strict';
+// 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.
-/**
- * Clones (copies) an Object using deep copying.
- *
- * This function supports circular references by default, but if you are certain
- * there are no circular references in your object, you can save some CPU time
- * by calling clone(obj, false).
- *
- * Caution: if `circular` is false and `parent` contains circular references,
- * your program may enter an infinite loop and crash.
- *
- * @param `parent` - the object to be cloned
- * @param `circular` - set to true if the object to be cloned may contain
- * circular references. (optional - true by default)
- * @param `depth` - set to a number if the object is only to be cloned to
- * a particular depth. (optional - defaults to Infinity)
- * @param `prototype` - sets the prototype to be used when cloning an object.
- * (optional - defaults to parent prototype).
-*/
-function clone(parent, circular, depth, prototype) {
- var filter;
- if (typeof circular === 'object') {
- depth = circular.depth;
- prototype = circular.prototype;
- filter = circular.filter;
- circular = circular.circular
- }
- // maintain two arrays for circular references, where corresponding parents
- // and children have the same index
- var allParents = [];
- var allChildren = [];
+module.exports = Stream;
- var useBuffer = typeof Buffer != 'undefined';
+var EE = __webpack_require__(11).EventEmitter;
+var inherits = __webpack_require__(2);
- if (typeof circular == 'undefined')
- circular = true;
+inherits(Stream, EE);
+Stream.Readable = __webpack_require__(7);
+Stream.Writable = __webpack_require__(49);
+Stream.Duplex = __webpack_require__(50);
+Stream.Transform = __webpack_require__(51);
+Stream.PassThrough = __webpack_require__(52);
- if (typeof depth == 'undefined')
- depth = Infinity;
+// Backwards-compat with node 0.4.x
+Stream.Stream = Stream;
- // recurse this function so we don't reset allParents and allChildren
- function _clone(parent, depth) {
- // cloning null always returns null
- if (parent === null)
- return null;
- if (depth == 0)
- return parent;
- var child;
- var proto;
- if (typeof parent != 'object') {
- return parent;
- }
+// old-style streams. Note that the pipe method (the only relevant
+// part of this class) is overridden in the Readable class.
- if (clone.__isArray(parent)) {
- child = [];
- } else if (clone.__isRegExp(parent)) {
- child = new RegExp(parent.source, __getRegExpFlags(parent));
- if (parent.lastIndex) child.lastIndex = parent.lastIndex;
- } else if (clone.__isDate(parent)) {
- child = new Date(parent.getTime());
- } else if (useBuffer && Buffer.isBuffer(parent)) {
- child = new Buffer(parent.length);
- parent.copy(child);
- return child;
- } else {
- if (typeof prototype == 'undefined') {
- proto = Object.getPrototypeOf(parent);
- child = Object.create(proto);
- }
- else {
- child = Object.create(prototype);
- proto = prototype;
- }
- }
+function Stream() {
+ EE.call(this);
+}
- if (circular) {
- var index = allParents.indexOf(parent);
+Stream.prototype.pipe = function(dest, options) {
+ var source = this;
- if (index != -1) {
- return allChildren[index];
+ function ondata(chunk) {
+ if (dest.writable) {
+ if (false === dest.write(chunk) && source.pause) {
+ source.pause();
}
- allParents.push(parent);
- allChildren.push(child);
}
+ }
- for (var i in parent) {
- var attrs;
- if (proto) {
- attrs = Object.getOwnPropertyDescriptor(proto, i);
- }
+ source.on('data', ondata);
- if (attrs && attrs.set == null) {
- continue;
- }
- child[i] = _clone(parent[i], depth - 1);
+ function ondrain() {
+ if (source.readable && source.resume) {
+ source.resume();
}
-
- return child;
}
- return _clone(parent, depth);
-}
-
-/**
- * Simple flat clone using prototype, accepts only objects, usefull for property
- * override on FLAT configuration object (no nested props).
- *
- * USE WITH CAUTION! This may not behave as you wish if you do not know how this
- * works.
- */
-clone.clonePrototype = function clonePrototype(parent) {
- if (parent === null)
- return null;
+ dest.on('drain', ondrain);
- var c = function () {};
- c.prototype = parent;
- return new c();
-};
+ // 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);
+ }
-// private utility functions
+ var didOnEnd = false;
+ function onend() {
+ if (didOnEnd) return;
+ didOnEnd = true;
-function __objToStr(o) {
- return Object.prototype.toString.call(o);
-};
-clone.__objToStr = __objToStr;
+ dest.end();
+ }
-function __isDate(o) {
- return typeof o === 'object' && __objToStr(o) === '[object Date]';
-};
-clone.__isDate = __isDate;
-function __isArray(o) {
- return typeof o === 'object' && __objToStr(o) === '[object Array]';
-};
-clone.__isArray = __isArray;
+ function onclose() {
+ if (didOnEnd) return;
+ didOnEnd = true;
-function __isRegExp(o) {
- return typeof o === 'object' && __objToStr(o) === '[object RegExp]';
-};
-clone.__isRegExp = __isRegExp;
+ if (typeof dest.destroy === 'function') dest.destroy();
+ }
-function __getRegExpFlags(re) {
- var flags = '';
- if (re.global) flags += 'g';
- if (re.ignoreCase) flags += 'i';
- if (re.multiline) flags += 'm';
- return flags;
-};
-clone.__getRegExpFlags = __getRegExpFlags;
+ // 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.
+ }
+ }
-return clone;
-})();
+ source.on('error', onerror);
+ dest.on('error', onerror);
-if (typeof module === 'object' && module.exports) {
- module.exports = clone;
-}
+ // remove all the event listeners that were added.
+ function cleanup() {
+ source.removeListener('data', ondata);
+ dest.removeListener('drain', ondrain);
-}).call(this,require("buffer").Buffer)
+ source.removeListener('end', onend);
+ source.removeListener('close', onclose);
-},{"buffer":4}],7:[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.
+ source.removeListener('error', onerror);
+ dest.removeListener('error', onerror);
-// NOTE: These type checking functions intentionally don't use `instanceof`
-// because it is fragile and can be easily faked with `Object.create()`.
+ source.removeListener('end', cleanup);
+ source.removeListener('close', cleanup);
-function isArray(arg) {
- if (Array.isArray) {
- return Array.isArray(arg);
+ dest.removeListener('close', cleanup);
}
- return objectToString(arg) === '[object Array]';
-}
-exports.isArray = isArray;
-function isBoolean(arg) {
- return typeof arg === 'boolean';
-}
-exports.isBoolean = isBoolean;
+ source.on('end', cleanup);
+ source.on('close', cleanup);
-function isNull(arg) {
- return arg === null;
-}
-exports.isNull = isNull;
+ dest.on('close', cleanup);
-function isNullOrUndefined(arg) {
- return arg == null;
-}
-exports.isNullOrUndefined = isNullOrUndefined;
+ dest.emit('pipe', source);
-function isNumber(arg) {
- return typeof arg === 'number';
-}
-exports.isNumber = isNumber;
+ // Allow for unix-like usage: A.pipe(B).pipe(C)
+ return dest;
+};
-function isString(arg) {
- return typeof arg === 'string';
-}
-exports.isString = isString;
-function isSymbol(arg) {
- return typeof arg === 'symbol';
-}
-exports.isSymbol = isSymbol;
+/***/ }),
+/* 2 */
+/***/ (function(module, exports) {
-function isUndefined(arg) {
- return arg === void 0;
+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
+ }
}
-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;
+/***/ }),
+/* 3 */
+/***/ (function(module, exports) {
-function isDate(d) {
- return objectToString(d) === '[object Date]';
-}
-exports.isDate = isDate;
+// shim for using process in browser
+var process = module.exports = {};
-function isError(e) {
- return (objectToString(e) === '[object Error]' || e instanceof Error);
-}
-exports.isError = isError;
+// 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.
-function isFunction(arg) {
- return typeof arg === 'function';
-}
-exports.isFunction = isFunction;
+var cachedSetTimeout;
+var cachedClearTimeout;
-function isPrimitive(arg) {
- return arg === null ||
- typeof arg === 'boolean' ||
- typeof arg === 'number' ||
- typeof arg === 'string' ||
- typeof arg === 'symbol' || // ES6 symbol
- typeof arg === 'undefined';
+function defaultSetTimout() {
+ throw new Error('setTimeout has not been defined');
}
-exports.isPrimitive = isPrimitive;
+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);
+ }
+ }
-exports.isBuffer = Buffer.isBuffer;
-function objectToString(o) {
- return Object.prototype.toString.call(o);
}
+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);
+ }
+ }
-}).call(this,{"isBuffer":require("../../is-buffer/index.js")})
-},{"../../is-buffer/index.js":13}],8:[function(require,module,exports){
-var clone = require('clone');
-module.exports = function(options, defaults) {
- options = options || {};
+}
+var queue = [];
+var draining = false;
+var currentQueue;
+var queueIndex = -1;
- Object.keys(defaults).forEach(function(key) {
- if (typeof options[key] === 'undefined') {
- options[key] = clone(defaults[key]);
- }
- });
+function cleanUpNextTick() {
+ if (!draining || !currentQueue) {
+ return;
+ }
+ draining = false;
+ if (currentQueue.length) {
+ queue = currentQueue.concat(queue);
+ } else {
+ queueIndex = -1;
+ }
+ if (queue.length) {
+ drainQueue();
+ }
+}
- return options;
+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);
+ }
};
-},{"clone":6}],9:[function(require,module,exports){
-// Copyright Joyent, Inc. and other Node contributors.
+
+// 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; };
+
+
+/***/ }),
+/* 4 */
+/***/ (function(module, exports, __webpack_require__) {
+
+/* WEBPACK VAR INJECTION */(function(global, process) {// 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
@@ -1945,5846 +2247,9753 @@ module.exports = function(options, defaults) {
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
-function EventEmitter() {
- this._events = this._events || {};
- 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.
-EventEmitter.defaultMaxListeners = 10;
-
-// 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(n) {
- if (!isNumber(n) || n < 0 || isNaN(n))
- throw TypeError('n must be a positive number');
- this._maxListeners = n;
- return this;
-};
-
-EventEmitter.prototype.emit = function(type) {
- var er, handler, len, args, i, listeners;
-
- if (!this._events)
- this._events = {};
-
- // If there is no 'error' event listener then throw.
- if (type === 'error') {
- if (!this._events.error ||
- (isObject(this._events.error) && !this._events.error.length)) {
- er = arguments[1];
- if (er instanceof Error) {
- throw er; // Unhandled 'error' event
- }
- throw TypeError('Uncaught, unspecified "error" event.');
+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(' ');
}
- handler = this._events[type];
-
- if (isUndefined(handler))
- return false;
-
- if (isFunction(handler)) {
- switch (arguments.length) {
- // fast cases
- case 1:
- handler.call(this);
- break;
- case 2:
- handler.call(this, arguments[1]);
- break;
- case 3:
- handler.call(this, arguments[1], arguments[2]);
- break;
- // slower
+ 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:
- args = Array.prototype.slice.call(arguments, 1);
- handler.apply(this, args);
+ return x;
+ }
+ });
+ for (var x = args[i]; i < len; x = args[++i]) {
+ if (isNull(x) || !isObject(x)) {
+ str += ' ' + x;
+ } else {
+ str += ' ' + inspect(x);
}
- } else if (isObject(handler)) {
- args = Array.prototype.slice.call(arguments, 1);
- listeners = handler.slice();
- len = listeners.length;
- for (i = 0; i < len; i++)
- listeners[i].apply(this, args);
}
-
- return true;
+ return str;
};
-EventEmitter.prototype.addListener = function(type, listener) {
- var m;
-
- if (!isFunction(listener))
- throw TypeError('listener must be a function');
-
- if (!this._events)
- this._events = {};
-
- // To avoid recursion in the case that type === "newListener"! Before
- // adding it to the listeners, first emit "newListener".
- if (this._events.newListener)
- this.emit('newListener', type,
- isFunction(listener.listener) ?
- listener.listener : listener);
- if (!this._events[type])
- // Optimize the case of one listener. Don't need the extra array object.
- this._events[type] = listener;
- else if (isObject(this._events[type]))
- // If we've already got an array, just append.
- this._events[type].push(listener);
- else
- // Adding the second element, need to change to array.
- this._events[type] = [this._events[type], listener];
+// 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);
+ };
+ }
- // Check for listener leak
- if (isObject(this._events[type]) && !this._events[type].warned) {
- if (!isUndefined(this._maxListeners)) {
- m = this._maxListeners;
- } else {
- m = EventEmitter.defaultMaxListeners;
- }
+ if (process.noDeprecation === true) {
+ return fn;
+ }
- if (m && m > 0 && this._events[type].length > m) {
- this._events[type].warned = true;
- console.error('(node) warning: possible EventEmitter memory ' +
- 'leak detected. %d listeners added. ' +
- 'Use emitter.setMaxListeners() to increase limit.',
- this._events[type].length);
- if (typeof console.trace === 'function') {
- // not supported in IE 10
- console.trace();
+ 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 this;
+ return deprecated;
};
-EventEmitter.prototype.on = EventEmitter.prototype.addListener;
-
-EventEmitter.prototype.once = function(type, listener) {
- if (!isFunction(listener))
- throw TypeError('listener must be a function');
- var fired = false;
+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];
+};
- function g() {
- this.removeListener(type, g);
- if (!fired) {
- fired = true;
- listener.apply(this, arguments);
- }
+/**
+ * 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;
- g.listener = listener;
- this.on(type, g);
- return this;
+// 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]
};
-// emits a 'removeListener' event iff the listener was removed
-EventEmitter.prototype.removeListener = function(type, listener) {
- var list, position, length, i;
+// 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'
+};
- if (!isFunction(listener))
- throw TypeError('listener must be a function');
- if (!this._events || !this._events[type])
- return this;
+function stylizeWithColor(str, styleType) {
+ var style = inspect.styles[styleType];
- list = this._events[type];
- length = list.length;
- position = -1;
+ if (style) {
+ return '\u001b[' + inspect.colors[style][0] + 'm' + str +
+ '\u001b[' + inspect.colors[style][1] + 'm';
+ } else {
+ return str;
+ }
+}
- if (list === listener ||
- (isFunction(list.listener) && list.listener === listener)) {
- delete this._events[type];
- if (this._events.removeListener)
- this.emit('removeListener', type, listener);
- } else if (isObject(list)) {
- for (i = length; i-- > 0;) {
- if (list[i] === listener ||
- (list[i].listener && list[i].listener === listener)) {
- position = i;
- break;
- }
- }
+function stylizeNoColor(str, styleType) {
+ return str;
+}
- if (position < 0)
- return this;
- if (list.length === 1) {
- list.length = 0;
- delete this._events[type];
- } else {
- list.splice(position, 1);
- }
+function arrayToHash(array) {
+ var hash = {};
- if (this._events.removeListener)
- this.emit('removeListener', type, listener);
+ 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;
}
- return this;
-};
+ // Primitive types cannot have properties
+ var primitive = formatPrimitive(ctx, value);
+ if (primitive) {
+ return primitive;
+ }
-EventEmitter.prototype.removeAllListeners = function(type) {
- var key, listeners;
+ // Look up the keys of the object.
+ var keys = Object.keys(value);
+ var visibleKeys = arrayToHash(keys);
- if (!this._events)
- return this;
+ if (ctx.showHidden) {
+ keys = Object.getOwnPropertyNames(value);
+ }
- // not listening for removeListener, no need to emit
- if (!this._events.removeListener) {
- if (arguments.length === 0)
- this._events = {};
- else if (this._events[type])
- delete this._events[type];
- return this;
+ // 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);
}
- // emit removeListener for all listeners on all events
- if (arguments.length === 0) {
- for (key in this._events) {
- if (key === 'removeListener') continue;
- this.removeAllListeners(key);
+ // 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);
}
- this.removeAllListeners('removeListener');
- this._events = {};
- return this;
}
- listeners = this._events[type];
+ var base = '', array = false, braces = ['{', '}'];
- if (isFunction(listeners)) {
- this.removeListener(type, listeners);
- } else if (listeners) {
- // LIFO order
- while (listeners.length)
- this.removeListener(type, listeners[listeners.length - 1]);
+ // Make Array say that they are Array
+ if (isArray(value)) {
+ array = true;
+ braces = ['[', ']'];
}
- delete this._events[type];
-
- return this;
-};
-EventEmitter.prototype.listeners = function(type) {
- var ret;
- if (!this._events || !this._events[type])
- ret = [];
- else if (isFunction(this._events[type]))
- ret = [this._events[type]];
- else
- ret = this._events[type].slice();
- return ret;
-};
+ // Make functions say that they are functions
+ if (isFunction(value)) {
+ var n = value.name ? ': ' + value.name : '';
+ base = ' [Function' + n + ']';
+ }
-EventEmitter.prototype.listenerCount = function(type) {
- if (this._events) {
- var evlistener = this._events[type];
+ // Make RegExps say that they are RegExps
+ if (isRegExp(value)) {
+ base = ' ' + RegExp.prototype.toString.call(value);
+ }
- if (isFunction(evlistener))
- return 1;
- else if (evlistener)
- return evlistener.length;
+ // Make dates with properties first say the date
+ if (isDate(value)) {
+ base = ' ' + Date.prototype.toUTCString.call(value);
}
- return 0;
-};
-EventEmitter.listenerCount = function(emitter, type) {
- return emitter.listenerCount(type);
-};
-
-function isFunction(arg) {
- return typeof arg === 'function';
-}
-
-function isNumber(arg) {
- return typeof arg === 'number';
-}
-
-function isObject(arg) {
- return typeof arg === 'object' && arg !== null;
-}
-
-function isUndefined(arg) {
- return arg === void 0;
-}
-
-},{}],10:[function(require,module,exports){
-// loosely based on example code at https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia
-(function (root) {
- 'use strict';
-
- /**
- * Error thrown when any required feature is missing (Promises, navigator, getUserMedia)
- * @constructor
- */
- function NotSupportedError() {
- this.name = 'NotSupportedError';
- this.message = 'getUserMedia is not implemented in this browser';
+ // Make error with message first say the error
+ if (isError(value)) {
+ base = ' ' + formatError(value);
}
- NotSupportedError.prototype = Error.prototype;
-
- /**
- * Fake Promise instance that behaves like a Promise except that it always rejects with a NotSupportedError.
- * Used for situations where there is no global Promise constructor.
- *
- * The message will report that the getUserMedia API is not available.
- * This is technically true because every browser that supports getUserMedia also supports promises.
- **
- * @see http://caniuse.com/#feat=stream
- * @see http://caniuse.com/#feat=promises
- * @constructor
- */
- function FakePromise() {
- // make it chainable like a real promise
- this.then = function() {
- return this;
- };
- // but always reject with an error
- var err = new NotSupportedError();
- this.catch = function(cb) {
- setTimeout(function () {
- cb(err);
- });
- }
+ if (keys.length === 0 && (!array || value.length == 0)) {
+ return braces[0] + base + braces[1];
}
- /**
- * Wrapper for navigator.mediaDevices.getUserMedia.
- * Always returns a Promise or Promise-like object, even in environments without a global Promise constructor
- *
- * @stream https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia
- *
- * @param {Object} constraints - must include one or both of audio/video along with optional details for video
- * @param {Boolean} [constraints.audio] - include audio data in the stream
- * @param {Boolean|Object} [constraints.video] - include video data in the stream. May be a boolean or an object with additional constraints, see
- * @returns {Promise} a promise that resolves to a MediaStream object
- */
- function getUserMedia(constraints) {
- // ensure that Promises are supported and we have a navigator object
- if (typeof Promise === 'undefined') {
- return new FakePromise();
- }
-
- // Try the more modern, promise-based MediaDevices API first
- //https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia
- if(navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
- return navigator.mediaDevices.getUserMedia(constraints);
+ if (recurseTimes < 0) {
+ if (isRegExp(value)) {
+ return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
+ } else {
+ return ctx.stylize('[Object]', 'special');
}
-
- // fall back to the older method second, wrap it in a promise.
- return new Promise(function(resolve, reject) {
- // if navigator doesn't exist, then we can't use the getUserMedia API. (And probably aren't even in a browser.)
- // assuming it does, try getUserMedia and then all of the prefixed versions
- var gum = navigator && navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
- if (!gum) {
- return reject(new NotSupportedError())
- }
- gum.call(navigator, constraints, resolve, reject);
- });
}
- getUserMedia.NotSupportedError = NotSupportedError;
+ ctx.seen.push(value);
- // UMD, loosely based on https://github.com/umdjs/umd/blob/master/templates/returnExportsGlobal.js
- if (typeof define === 'function' && define.amd) {
- // AMD. Register as an anonymous module.
- define([], function () {
- return getUserMedia;
- });
- } else if (typeof module === 'object' && module.exports) {
- // Node. Does not work with strict CommonJS, but
- // only CommonJS-like enviroments that support module.exports,
- // like Node.
- module.exports = getUserMedia;
+ var output;
+ if (array) {
+ output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
} else {
- // Browser globals
- // pollyfill the MediaDevices API if it does not exist.
- root.nagivator.mediaDevices = root.navigator.mediaDevices || {};
- root.nagivator.mediaDevices.getUserMedia = root.nagivator.mediaDevices.getUserMedia || getUserMedia;
+ output = keys.map(function(key) {
+ return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
+ });
}
-}(this));
-},{}],11:[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
+ ctx.seen.pop();
- e = s & ((1 << (-nBits)) - 1)
- s >>= (-nBits)
- nBits += eLen
- for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
+ return reduceToSingleString(output, base, braces);
+}
- 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
+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');
}
- return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
+ 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');
}
-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)
+function formatError(value) {
+ return '[' + Error.prototype.toString.call(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
+
+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 {
- value += rt * Math.pow(2, 1 - eBias)
+ output.push('');
}
- if (value * c >= 2) {
- e++
- c /= 2
+ }
+ keys.forEach(function(key) {
+ if (!key.match(/^\d+$/)) {
+ output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
+ key, true));
}
+ });
+ return output;
+}
- if (e + eBias >= eMax) {
- m = 0
- e = eMax
- } else if (e + eBias >= 1) {
- m = (value * c - 1) * Math.pow(2, mLen)
- e = e + eBias
+
+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 {
- m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
- e = 0
+ str = ctx.stylize('[Getter]', 'special');
+ }
+ } else {
+ if (desc.set) {
+ str = ctx.stylize('[Setter]', 'special');
}
}
-
- 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
-}
-
-},{}],12:[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
+ 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');
+ }
}
-}
-
-},{}],13:[function(require,module,exports){
-/**
- * Determine if an object is Buffer
- *
- * Author: Feross Aboukhadijeh
- * License: MIT
- *
- * `npm install is-buffer`
- */
-module.exports = function (obj) {
- return !!(obj != null &&
- (obj._isBuffer || // For Safari 5-7 (missing Object.prototype.constructor)
- (obj.constructor &&
- typeof obj.constructor.isBuffer === 'function' &&
- obj.constructor.isBuffer(obj))
- ))
+ return name + ': ' + str;
}
-},{}],14:[function(require,module,exports){
-module.exports = Array.isArray || function (arr) {
- return Object.prototype.toString.call(arr) == '[object Array]';
-};
-
-},{}],15:[function(require,module,exports){
-/*!
- * isobject
- *
- * Copyright (c) 2014-2015, Jon Schlinkert.
- * Licensed under the MIT License.
- */
-
-'use strict';
-
-var isArray = require('isarray');
-
-module.exports = function isObject(o) {
- return o != null && typeof o === 'object' && !isArray(o);
-};
-
-},{"isarray":14}],16:[function(require,module,exports){
-(function (process,Buffer){
-'use strict';
-var Readable = require('stream').Readable;
-var util = require('util');
-
-/**
- * Turns a MediaStream object (from getUserMedia) into a Node.js Readable stream and optionally converts the audio to Buffers
- *
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Navigator/getUserMedia
- *
- * @param {MediaStream} stream https://developer.mozilla.org/en-US/docs/Web/API/MediaStream
- * @param {Object} [opts] options
- * @param {Boolean} [opts.objectMode=false] Puts the stream into ObjectMode where it emits AudioBuffers instead of Buffers - see https://developer.mozilla.org/en-US/docs/Web/API/AudioBuffer
- * @param {Number|null} [opts.bufferSize=null] https://developer.mozilla.org/en-US/docs/Web/API/AudioContext/createScriptProcessor
- * @constructor
- */
-function MicrophoneStream(stream, opts) {
- // "It is recommended for authors to not specify this buffer size and allow the implementation to pick a good
- // buffer size to balance between latency and audio quality."
- // https://developer.mozilla.org/en-US/docs/Web/API/AudioContext/createScriptProcessor
- // however, webkitAudioContext (safari) requires it to be set'
- // Possible values: null, 256, 512, 1024, 2048, 4096, 8192, 16384
- var bufferSize = (typeof window.AudioContext === 'undefined' ? 4096 : null);
- opts = opts || {};
- bufferSize = opts.bufferSize || bufferSize;
+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);
- // We can only emit one channel's worth of audio, so only one input. (Who has multiple microphones anyways?)
- var inputChannels = 1;
+ if (length > 60) {
+ return braces[0] +
+ (base === '' ? '' : base + '\n ') +
+ ' ' +
+ output.join(',\n ') +
+ ' ' +
+ braces[1];
+ }
- // we shouldn't need any output channels (going back to the browser), but chrome is buggy and won't give us any audio without one
- var outputChannels = 1;
+ return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
+}
- Readable.call(this, opts);
- var self = this;
- var recording = true;
+// 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;
- /**
- * Convert and emit the raw audio data
- * @see https://developer.mozilla.org/en-US/docs/Web/API/ScriptProcessorNode/onaudioprocess
- * @param {AudioProcessingEvent} e https://developer.mozilla.org/en-US/docs/Web/API/AudioProcessingEvent
- */
- function recorderProcess(e) {
- // onaudioprocess can be called at least once after we've stopped
- if (recording) {
- self.push(opts.objectMode ? e.inputBuffer : new Buffer(e.inputBuffer.getChannelData(0)));
- }
- }
+function isBoolean(arg) {
+ return typeof arg === 'boolean';
+}
+exports.isBoolean = isBoolean;
- var AudioContext = window.AudioContext || window.webkitAudioContext;
- var context = new AudioContext();
- var audioInput = context.createMediaStreamSource(stream);
- var recorder = context.createScriptProcessor(bufferSize, inputChannels, outputChannels);
+function isNull(arg) {
+ return arg === null;
+}
+exports.isNull = isNull;
- recorder.onaudioprocess = recorderProcess;
+function isNullOrUndefined(arg) {
+ return arg == null;
+}
+exports.isNullOrUndefined = isNullOrUndefined;
- audioInput.connect(recorder);
+function isNumber(arg) {
+ return typeof arg === 'number';
+}
+exports.isNumber = isNumber;
- // other half of workaround for chrome bugs
- recorder.connect(context.destination);
+function isString(arg) {
+ return typeof arg === 'string';
+}
+exports.isString = isString;
- this.stop = function() {
- try {
- stream.getTracks()[0].stop();
- } catch (ex) {
- // This fails in some older versions of chrome. Nothing we can do about it.
- }
- recorder.disconnect();
- audioInput.disconnect();
- try {
- context.close();
- } catch (ex) {
- // this can also fail in older versions of chrome
- }
- recording = false;
- self.push(null);
- self.emit('close');
- };
+function isSymbol(arg) {
+ return typeof arg === 'symbol';
+}
+exports.isSymbol = isSymbol;
- process.nextTick(function() {
- self.emit('format', {
- channels: 1,
- bitDepth: 32,
- sampleRate: context.sampleRate,
- signed: true,
- float: true
- });
- });
+function isUndefined(arg) {
+ return arg === void 0;
}
-util.inherits(MicrophoneStream, Readable);
+exports.isUndefined = isUndefined;
-MicrophoneStream.prototype._read = function(/* bytes */) {
- // no-op, (flow-control doesn't really work on sound)
-};
+function isRegExp(re) {
+ return isObject(re) && objectToString(re) === '[object RegExp]';
+}
+exports.isRegExp = isRegExp;
-/**
- * Converts a Buffer back into the raw Float32Array format that browsers use.
- * Note: this is just a new DataView for the same underlying buffer -
- * the actual audio data is not copied or changed here.
- *
- * @param {Buffer} chunk node-style buffer of audio data from a 'data' event or read() call
- * @return {Float32Array} raw 32-bit float data view of audio data
- */
-MicrophoneStream.toRaw = function toFloat32(chunk) {
- return new Float32Array(chunk.buffer);
-};
+function isObject(arg) {
+ return typeof arg === 'object' && arg !== null;
+}
+exports.isObject = isObject;
-module.exports = MicrophoneStream;
+function isDate(d) {
+ return isObject(d) && objectToString(d) === '[object Date]';
+}
+exports.isDate = isDate;
-}).call(this,require('_process'),require("buffer").Buffer)
+function isError(e) {
+ return isObject(e) &&
+ (objectToString(e) === '[object Error]' || e instanceof Error);
+}
+exports.isError = isError;
-},{"_process":26,"buffer":4,"stream":39,"util":43}],17:[function(require,module,exports){
-'use strict';
+function isFunction(arg) {
+ return typeof arg === 'function';
+}
+exports.isFunction = isFunction;
-var keys = require('object-keys');
+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;
-module.exports = function hasSymbols() {
- if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; }
- if (typeof Symbol.iterator === 'symbol') { return true; }
+exports.isBuffer = __webpack_require__(53);
- var obj = {};
- var sym = Symbol('test');
- if (typeof sym === 'string') { return false; }
+function objectToString(o) {
+ return Object.prototype.toString.call(o);
+}
- // temp disabled per https://github.com/ljharb/object.assign/issues/17
- // if (sym instanceof Symbol) { return false; }
- // temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4
- // if (!(Object(sym) instanceof Symbol)) { return false; }
- var symVal = 42;
- obj[sym] = symVal;
- for (sym in obj) { return false; }
- if (keys(obj).length !== 0) { return false; }
- if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; }
+function pad(n) {
+ return n < 10 ? '0' + n.toString(10) : n.toString(10);
+}
- if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; }
- var syms = Object.getOwnPropertySymbols(obj);
- if (syms.length !== 1 || syms[0] !== sym) { return false; }
+var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
+ 'Oct', 'Nov', 'Dec'];
- if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; }
+// 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(' ');
+}
- if (typeof Object.getOwnPropertyDescriptor === 'function') {
- var descriptor = Object.getOwnPropertyDescriptor(obj, sym);
- if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; }
- }
- return true;
+// 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));
};
-},{"object-keys":21}],18:[function(require,module,exports){
-'use strict';
-// modified from https://github.com/es-shims/es6-shim
-var keys = require('object-keys');
-var bind = require('function-bind');
-var canBeObject = function (obj) {
- return typeof obj !== 'undefined' && obj !== null;
-};
-var hasSymbols = require('./hasSymbols')();
-var toObject = Object;
-var push = bind.call(Function.call, Array.prototype.push);
-var propIsEnumerable = bind.call(Function.call, Object.prototype.propertyIsEnumerable);
+/**
+ * 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 = __webpack_require__(54);
-module.exports = function assign(target, source1) {
- if (!canBeObject(target)) { throw new TypeError('target must be an object'); }
- var objTarget = toObject(target);
- var s, source, i, props, syms, value, key;
- for (s = 1; s < arguments.length; ++s) {
- source = toObject(arguments[s]);
- props = keys(source);
- if (hasSymbols && Object.getOwnPropertySymbols) {
- syms = Object.getOwnPropertySymbols(source);
- for (i = 0; i < syms.length; ++i) {
- key = syms[i];
- if (propIsEnumerable(source, key)) {
- push(props, key);
- }
- }
- }
- for (i = 0; i < props.length; ++i) {
- key = props[i];
- value = source[key];
- if (propIsEnumerable(source, key)) {
- objTarget[key] = value;
- }
- }
- }
- return objTarget;
+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;
};
-},{"./hasSymbols":17,"function-bind":20,"object-keys":21}],19:[function(require,module,exports){
-var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible ';
-var slice = Array.prototype.slice;
-var toStr = Object.prototype.toString;
-var funcType = '[object Function]';
+function hasOwnProperty(obj, prop) {
+ return Object.prototype.hasOwnProperty.call(obj, prop);
+}
-module.exports = function bind(that) {
- var target = this;
- if (typeof target !== 'function' || toStr.call(target) !== funcType) {
- throw new TypeError(ERROR_MESSAGE + target);
- }
- var args = slice.call(arguments, 1);
+/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(5), __webpack_require__(3)))
- var bound;
- var binder = function () {
- if (this instanceof bound) {
- var result = target.apply(
- this,
- args.concat(slice.call(arguments))
- );
- if (Object(result) === result) {
- return result;
- }
- return this;
- } else {
- return target.apply(
- that,
- args.concat(slice.call(arguments))
- );
- }
- };
+/***/ }),
+/* 5 */
+/***/ (function(module, exports) {
- var boundLength = Math.max(0, target.length - args.length);
- var boundArgs = [];
- for (var i = 0; i < boundLength; i++) {
- boundArgs.push('$' + i);
- }
+var g;
- bound = Function('binder', 'return function (' + boundArgs.join(',') + '){ return binder.apply(this,arguments); }')(binder);
+// This works in non-strict mode
+g = (function() {
+ return this;
+})();
- if (target.prototype) {
- var Empty = function Empty() {};
- Empty.prototype = target.prototype;
- bound.prototype = new Empty();
- Empty.prototype = null;
- }
+try {
+ // This works if eval is allowed (see CSP)
+ g = g || Function("return this")() || (1,eval)("this");
+} catch(e) {
+ // This works if the window reference is available
+ if(typeof window === "object")
+ g = window;
+}
- return bound;
-};
+// g can still be undefined, but nothing to do about it...
+// We return undefined, instead of nothing here, so it's
+// easier to handle this case. if(!global) { ...}
-},{}],20:[function(require,module,exports){
-var implementation = require('./implementation');
+module.exports = g;
-module.exports = Function.prototype.bind || implementation;
-},{"./implementation":19}],21:[function(require,module,exports){
-'use strict';
+/***/ }),
+/* 6 */
+/***/ (function(module, exports, __webpack_require__) {
-// modified from https://github.com/es-shims/es5-shim
-var has = Object.prototype.hasOwnProperty;
-var toStr = Object.prototype.toString;
-var slice = Array.prototype.slice;
-var isArgs = require('./isArguments');
-var hasDontEnumBug = !({ toString: null }).propertyIsEnumerable('toString');
-var hasProtoEnumBug = function () {}.propertyIsEnumerable('prototype');
-var dontEnums = [
- 'toString',
- 'toLocaleString',
- 'valueOf',
- 'hasOwnProperty',
- 'isPrototypeOf',
- 'propertyIsEnumerable',
- 'constructor'
-];
-var equalsConstructorPrototype = function (o) {
- var ctor = o.constructor;
- return ctor && ctor.prototype === o;
-};
-var blacklistedKeys = {
- $console: true,
- $frame: true,
- $frameElement: true,
- $frames: true,
- $parent: true,
- $self: true,
- $webkitIndexedDB: true,
- $webkitStorageInfo: true,
- $window: true
-};
-var hasAutomationEqualityBug = (function () {
- /* global window */
- if (typeof window === 'undefined') { return false; }
- for (var k in window) {
- try {
- if (!blacklistedKeys['$' + k] && has.call(window, k) && window[k] !== null && typeof window[k] === 'object') {
- try {
- equalsConstructorPrototype(window[k]);
- } catch (e) {
- return true;
- }
- }
- } catch (e) {
- return true;
- }
- }
- return false;
-}());
-var equalsConstructorPrototypeIfNotBuggy = function (o) {
- /* global window */
- if (typeof window === 'undefined' || !hasAutomationEqualityBug) {
- return equalsConstructorPrototype(o);
- }
- try {
- return equalsConstructorPrototype(o);
- } catch (e) {
- return false;
- }
-};
+"use strict";
+// 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.
-var keysShim = function keys(object) {
- var isObject = object !== null && typeof object === 'object';
- var isFunction = toStr.call(object) === '[object Function]';
- var isArguments = isArgs(object);
- var isString = isObject && toStr.call(object) === '[object String]';
- var theKeys = [];
- if (!isObject && !isFunction && !isArguments) {
- throw new TypeError('Object.keys called on a non-object');
- }
- var skipProto = hasProtoEnumBug && isFunction;
- if (isString && object.length > 0 && !has.call(object, 0)) {
- for (var i = 0; i < object.length; ++i) {
- theKeys.push(String(i));
- }
- }
+/**/
- if (isArguments && object.length > 0) {
- for (var j = 0; j < object.length; ++j) {
- theKeys.push(String(j));
- }
- } else {
- for (var name in object) {
- if (!(skipProto && name === 'prototype') && has.call(object, name)) {
- theKeys.push(String(name));
- }
- }
- }
+var objectKeys = Object.keys || function (obj) {
+ var keys = [];
+ for (var key in obj) {
+ keys.push(key);
+ }return keys;
+};
+/**/
- if (hasDontEnumBug) {
- var skipConstructor = equalsConstructorPrototypeIfNotBuggy(object);
+module.exports = Duplex;
- for (var k = 0; k < dontEnums.length; ++k) {
- if (!(skipConstructor && dontEnums[k] === 'constructor') && has.call(object, dontEnums[k])) {
- theKeys.push(dontEnums[k]);
- }
- }
- }
- return theKeys;
-};
+/**/
+var processNextTick = __webpack_require__(12);
+/**/
-keysShim.shim = function shimObjectKeys() {
- if (Object.keys) {
- var keysWorksWithArguments = (function () {
- // Safari 5.0 bug
- return (Object.keys(arguments) || '').length === 2;
- }(1, 2));
- if (!keysWorksWithArguments) {
- var originalKeys = Object.keys;
- Object.keys = function keys(object) {
- if (isArgs(object)) {
- return originalKeys(slice.call(object));
- } else {
- return originalKeys(object);
- }
- };
- }
- } else {
- Object.keys = keysShim;
- }
- return Object.keys || keysShim;
-};
+/**/
+var util = __webpack_require__(8);
+util.inherits = __webpack_require__(2);
+/**/
-module.exports = keysShim;
+var Readable = __webpack_require__(26);
+var Writable = __webpack_require__(14);
-},{"./isArguments":22}],22:[function(require,module,exports){
-'use strict';
+util.inherits(Duplex, Readable);
-var toStr = Object.prototype.toString;
+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];
+}
-module.exports = function isArguments(value) {
- var str = toStr.call(value);
- var isArgs = str === '[object Arguments]';
- if (!isArgs) {
- isArgs = str !== '[object Array]' &&
- value !== null &&
- typeof value === 'object' &&
- typeof value.length === 'number' &&
- value.length >= 0 &&
- toStr.call(value.callee) === '[object Function]';
- }
- return isArgs;
-};
+function Duplex(options) {
+ if (!(this instanceof Duplex)) return new Duplex(options);
-},{}],23:[function(require,module,exports){
-'use strict';
+ Readable.call(this, options);
+ Writable.call(this, options);
-var implementation = require('./implementation');
+ if (options && options.readable === false) this.readable = false;
-var lacksProperEnumerationOrder = function () {
- if (!Object.assign) {
- return false;
- }
- // v8, specifically in node 4.x, has a bug with incorrect property enumeration order
- // note: this does not detect the bug unless there's 20 characters
- var str = 'abcdefghijklmnopqrst';
- var letters = str.split('');
- var map = {};
- for (var i = 0; i < letters.length; ++i) {
- map[letters[i]] = letters[i];
- }
- var obj = Object.assign({}, map);
- var actual = '';
- for (var k in obj) {
- actual += k;
- }
- return str !== actual;
-};
+ if (options && options.writable === false) this.writable = false;
-var assignHasPendingExceptions = function () {
- if (!Object.assign || !Object.preventExtensions) {
- return false;
- }
- // Firefox 37 still has "pending exception" logic in its Object.assign implementation,
- // which is 72% slower than our shim, and Firefox 40's native implementation.
- var thrower = Object.preventExtensions({ 1: 2 });
- try {
- Object.assign(thrower, 'xy');
- } catch (e) {
- return thrower[1] === 'y';
- }
-};
+ this.allowHalfOpen = true;
+ if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;
-module.exports = function getPolyfill() {
- if (!Object.assign) {
- return implementation;
- }
- if (lacksProperEnumerationOrder()) {
- return implementation;
- }
- if (assignHasPendingExceptions()) {
- return implementation;
- }
- return Object.assign;
-};
+ this.once('end', onend);
+}
-},{"./implementation":18}],24:[function(require,module,exports){
-/*!
- * object.pick
- *
- * Copyright (c) 2014-2015 Jon Schlinkert, contributors.
- * Licensed under the MIT License
- */
+// 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;
-'use strict';
+ // no more data can be written.
+ // But allow more writes to happen in this tick.
+ processNextTick(onEndNT, this);
+}
-var isObject = require('isobject');
+function onEndNT(self) {
+ self.end();
+}
-module.exports = function pick(obj, keys) {
- if (!isObject(obj) && typeof obj !== 'function') {
- return {};
+function forEach(xs, f) {
+ for (var i = 0, l = xs.length; i < l; i++) {
+ f(xs[i], i);
}
+}
- var res = {};
- if (typeof keys === 'string') {
- if (keys in obj) {
- res[keys] = obj[keys];
- }
- return res;
- }
+/***/ }),
+/* 7 */
+/***/ (function(module, exports, __webpack_require__) {
- var len = keys.length;
- var idx = -1;
+exports = module.exports = __webpack_require__(26);
+exports.Stream = exports;
+exports.Readable = exports;
+exports.Writable = __webpack_require__(14);
+exports.Duplex = __webpack_require__(6);
+exports.Transform = __webpack_require__(29);
+exports.PassThrough = __webpack_require__(48);
- while (++idx < len) {
- var key = keys[idx];
- if (key in obj) {
- res[key] = obj[key];
- }
- }
- return res;
-};
-},{"isobject":15}],25:[function(require,module,exports){
-(function (process){
-'use strict';
+/***/ }),
+/* 8 */
+/***/ (function(module, exports, __webpack_require__) {
-if (!process.version ||
- process.version.indexOf('v0.') === 0 ||
- process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) {
- module.exports = nextTick;
-} else {
- module.exports = process.nextTick;
-}
+/* WEBPACK VAR INJECTION */(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.
-function nextTick(fn) {
- var args = new Array(arguments.length - 1);
- var i = 0;
- while (i < args.length) {
- args[i++] = arguments[i];
+// 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);
}
- process.nextTick(function afterTick() {
- fn.apply(null, args);
- });
+ return objectToString(arg) === '[object Array]';
}
+exports.isArray = isArray;
-}).call(this,require('_process'))
+function isBoolean(arg) {
+ return typeof arg === 'boolean';
+}
+exports.isBoolean = isBoolean;
-},{"_process":26}],26:[function(require,module,exports){
-// shim for using process in browser
+function isNull(arg) {
+ return arg === null;
+}
+exports.isNull = isNull;
-var process = module.exports = {};
-var queue = [];
-var draining = false;
-var currentQueue;
-var queueIndex = -1;
+function isNullOrUndefined(arg) {
+ return arg == null;
+}
+exports.isNullOrUndefined = isNullOrUndefined;
-function cleanUpNextTick() {
- draining = false;
- if (currentQueue.length) {
- queue = currentQueue.concat(queue);
- } else {
- queueIndex = -1;
- }
- if (queue.length) {
- drainQueue();
- }
+function isNumber(arg) {
+ return typeof arg === 'number';
}
+exports.isNumber = isNumber;
-function drainQueue() {
- if (draining) {
- return;
- }
- var timeout = setTimeout(cleanUpNextTick);
- draining = true;
+function isString(arg) {
+ return typeof arg === 'string';
+}
+exports.isString = isString;
- 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;
- clearTimeout(timeout);
+function isSymbol(arg) {
+ return typeof arg === 'symbol';
}
+exports.isSymbol = isSymbol;
-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) {
- setTimeout(drainQueue, 0);
- }
-};
+function isUndefined(arg) {
+ return arg === void 0;
+}
+exports.isUndefined = isUndefined;
-// v8 likes predictible objects
-function Item(fun, array) {
- this.fun = fun;
- this.array = array;
+function isRegExp(re) {
+ return objectToString(re) === '[object RegExp]';
}
-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 = {};
+exports.isRegExp = isRegExp;
-function noop() {}
+function isObject(arg) {
+ return typeof arg === 'object' && arg !== null;
+}
+exports.isObject = isObject;
-process.on = noop;
-process.addListener = noop;
-process.once = noop;
-process.off = noop;
-process.removeListener = noop;
-process.removeAllListeners = noop;
-process.emit = noop;
+function isDate(d) {
+ return objectToString(d) === '[object Date]';
+}
+exports.isDate = isDate;
-process.binding = function (name) {
- throw new Error('process.binding is not supported');
-};
+function isError(e) {
+ return (objectToString(e) === '[object Error]' || e instanceof Error);
+}
+exports.isError = isError;
-process.cwd = function () { return '/' };
-process.chdir = function (dir) {
- throw new Error('process.chdir is not supported');
-};
-process.umask = function() { return 0; };
+function isFunction(arg) {
+ return typeof arg === 'function';
+}
+exports.isFunction = isFunction;
-},{}],27:[function(require,module,exports){
-(function (global,Buffer){
-'use strict';
+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;
-var Readable = require('stream').Readable;
-// When required from browserify, Buffer is also an Uint8Array, which is important for ejson.
-var inherits = require('inherits');
-var FileReader = global.FileReader;
-var Uint8Array = global.Uint8Array;
-
-/**
- * Read W3C Blob & File objects as a Node stream.
- * @param {Blob} blob
- * @constructor
- */
-function ReadableBlobStream(blob, opts)
-{
- if (!(this instanceof ReadableBlobStream)) {
- return new ReadableBlobStream(blob, opts);
- }
-
- opts = opts || {};
- opts.objectMode = false;
- Readable.call(this, opts);
-
- if (!blob)
- {
- throw Error('Missing argument "blob"');
- }
-
- if (typeof blob.slice !== 'function')
- {
- throw Error('Given argument "blob" is not really a Blob/File or your environment does not support .slice()');
- }
-
- if (!FileReader)
- {
- throw Error('Your environment does not support FileReader');
- }
-
- if (!Uint8Array)
- {
- throw Error('Your environment does not support Uint8Array');
- }
-
- this.totalSize = blob.size;
- this._blob = blob;
- this._nextByteStart = 0;
-}
-module.exports = ReadableBlobStream;
-inherits(ReadableBlobStream, Readable);
-
-function uint8ArrayToBuffer(buf)
-{
- if (typeof Buffer._augment === 'function')
- {
- buf = Buffer._augment(buf);
-
- if (!(buf instanceof Uint8Array))
- {
- throw Error('Assertion error, buf should be an Uint8Array');
- }
- }
- else
- {
- buf = new Buffer(buf);
- }
+exports.isBuffer = Buffer.isBuffer;
- return buf;
+function objectToString(o) {
+ return Object.prototype.toString.call(o);
}
-function bufferToUint8Array(buf)
-{
- buf = new Uint8Array(buf);
- if (typeof Buffer._augment === 'function')
- {
- buf = Buffer._augment(buf);
- // buf is now both an Uint8Array and an Buffer
- }
-
- if (!(buf instanceof Uint8Array)) // this is the check ejson uses
- {
- // this is the check ejson uses
- throw Error('Assertion error, buf should be an Uint8Array');
- }
-
- return buf;
-}
+/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(0).Buffer))
-ReadableBlobStream.prototype.read = function()
-{
- var buf = ReadableBlobStream.super_.prototype.read.apply(this, arguments);
+/***/ }),
+/* 9 */
+/***/ (function(module, exports, __webpack_require__) {
- // make sure it is a Uint8Array in case browserify's Buffer
- // stops using Uint8Array
- if (Buffer.isBuffer(buf) && !(buf instanceof Uint8Array))
- {
- buf = bufferToUint8Array(buf);
- }
+"use strict";
+/* WEBPACK VAR INJECTION */(function(Buffer) {
- return buf;
+/**
+ * Helper method that can be bound to a stream - it sets the output to utf-8, captures all of the results, and returns a promise that resolves to the final text.
+ * Essentially a smaller version of concat-stream wrapped in a promise
+ *
+ * @param {Stream} [stream=] optional stream param for when not bound to an existing stream instance
+ * @return {Promise}
+ */
+module.exports = function promise(stream) {
+ stream = stream || this;
+ return new Promise(function(resolve, reject) {
+ var results = [];
+ stream
+ .on('data', function(result) {
+ results.push(result);
+ })
+ .on('end', function() {
+ resolve(Buffer.isBuffer(results[0]) ? Buffer.concat(results).toString() : results);
+ })
+ .on('error', reject);
+ });
};
-ReadableBlobStream.prototype._read = function(chunkSize)
-{
- var size = this._blob.size;
- var start, end;
-
- start = this._nextByteStart;
- end = Math.min(start + chunkSize, size); // exclusive
- this._nextByteStart = end;
-
- if (start >= this._blob.size)
- {
- return void this.push(null);
- }
+/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(0).Buffer))
- var chunk = this._blob.slice(start, end);
- var reader = new FileReader();
+/***/ }),
+/* 10 */
+/***/ (function(module, exports, __webpack_require__) {
- reader.onload = function()
- {
- // reader.result is an ArrayBuffer
- var buf = new Uint8Array(reader.result);
- buf = uint8ArrayToBuffer(buf);
+var clone = __webpack_require__(60);
- this.push(buf);
- }.bind(this);
+module.exports = function(options, defaults) {
+ options = options || {};
- reader.onerror = function()
- {
- this.emit('error', reader.error);
- }.bind(this);
+ Object.keys(defaults).forEach(function(key) {
+ if (typeof options[key] === 'undefined') {
+ options[key] = clone(defaults[key]);
+ }
+ });
- reader.readAsArrayBuffer(chunk);
+ return options;
};
-}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer)
+/***/ }),
+/* 11 */
+/***/ (function(module, exports) {
-},{"buffer":4,"inherits":28,"stream":39}],28:[function(require,module,exports){
-arguments[4][12][0].apply(exports,arguments)
-},{"dup":12}],29:[function(require,module,exports){
-module.exports = require("./lib/_stream_duplex.js")
-
-},{"./lib/_stream_duplex.js":30}],30:[function(require,module,exports){
-// 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';
+// 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 objectKeys = Object.keys || function (obj) {
- var keys = [];
- for (var key in obj) keys.push(key);
- return keys;
+function EventEmitter() {
+ this._events = this._events || {};
+ this._maxListeners = this._maxListeners || undefined;
}
-/**/
-
+module.exports = EventEmitter;
-module.exports = Duplex;
+// Backwards-compat with node 0.10.x
+EventEmitter.EventEmitter = EventEmitter;
-/**/
-var processNextTick = require('process-nextick-args');
-/**/
+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.
+EventEmitter.defaultMaxListeners = 10;
+// 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(n) {
+ if (!isNumber(n) || n < 0 || isNaN(n))
+ throw TypeError('n must be a positive number');
+ this._maxListeners = n;
+ return this;
+};
-/**/
-var util = require('core-util-is');
-util.inherits = require('inherits');
-/**/
+EventEmitter.prototype.emit = function(type) {
+ var er, handler, len, args, i, listeners;
-var Readable = require('./_stream_readable');
-var Writable = require('./_stream_writable');
+ if (!this._events)
+ this._events = {};
-util.inherits(Duplex, Readable);
+ // If there is no 'error' event listener then throw.
+ if (type === 'error') {
+ if (!this._events.error ||
+ (isObject(this._events.error) && !this._events.error.length)) {
+ 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('Uncaught, unspecified "error" event. (' + er + ')');
+ err.context = er;
+ throw err;
+ }
+ }
+ }
-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];
-}
+ handler = this._events[type];
-function Duplex(options) {
- if (!(this instanceof Duplex))
- return new Duplex(options);
+ if (isUndefined(handler))
+ return false;
- Readable.call(this, options);
- Writable.call(this, options);
+ if (isFunction(handler)) {
+ switch (arguments.length) {
+ // fast cases
+ case 1:
+ handler.call(this);
+ break;
+ case 2:
+ handler.call(this, arguments[1]);
+ break;
+ case 3:
+ handler.call(this, arguments[1], arguments[2]);
+ break;
+ // slower
+ default:
+ args = Array.prototype.slice.call(arguments, 1);
+ handler.apply(this, args);
+ }
+ } else if (isObject(handler)) {
+ args = Array.prototype.slice.call(arguments, 1);
+ listeners = handler.slice();
+ len = listeners.length;
+ for (i = 0; i < len; i++)
+ listeners[i].apply(this, args);
+ }
- if (options && options.readable === false)
- this.readable = false;
+ return true;
+};
- if (options && options.writable === false)
- this.writable = false;
+EventEmitter.prototype.addListener = function(type, listener) {
+ var m;
- this.allowHalfOpen = true;
- if (options && options.allowHalfOpen === false)
- this.allowHalfOpen = false;
+ if (!isFunction(listener))
+ throw TypeError('listener must be a function');
- this.once('end', onend);
-}
+ if (!this._events)
+ this._events = {};
-// 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;
+ // To avoid recursion in the case that type === "newListener"! Before
+ // adding it to the listeners, first emit "newListener".
+ if (this._events.newListener)
+ this.emit('newListener', type,
+ isFunction(listener.listener) ?
+ listener.listener : listener);
- // no more data can be written.
- // But allow more writes to happen in this tick.
- processNextTick(onEndNT, this);
-}
+ if (!this._events[type])
+ // Optimize the case of one listener. Don't need the extra array object.
+ this._events[type] = listener;
+ else if (isObject(this._events[type]))
+ // If we've already got an array, just append.
+ this._events[type].push(listener);
+ else
+ // Adding the second element, need to change to array.
+ this._events[type] = [this._events[type], listener];
-function onEndNT(self) {
- self.end();
-}
+ // Check for listener leak
+ if (isObject(this._events[type]) && !this._events[type].warned) {
+ if (!isUndefined(this._maxListeners)) {
+ m = this._maxListeners;
+ } else {
+ m = EventEmitter.defaultMaxListeners;
+ }
-function forEach (xs, f) {
- for (var i = 0, l = xs.length; i < l; i++) {
- f(xs[i], i);
+ if (m && m > 0 && this._events[type].length > m) {
+ this._events[type].warned = true;
+ console.error('(node) warning: possible EventEmitter memory ' +
+ 'leak detected. %d listeners added. ' +
+ 'Use emitter.setMaxListeners() to increase limit.',
+ this._events[type].length);
+ if (typeof console.trace === 'function') {
+ // not supported in IE 10
+ console.trace();
+ }
+ }
}
-}
-
-},{"./_stream_readable":32,"./_stream_writable":34,"core-util-is":7,"inherits":12,"process-nextick-args":25}],31:[function(require,module,exports){
-// a passthrough stream.
-// basically just the most minimal sort of Transform stream.
-// Every written chunk gets output as-is.
-'use strict';
+ return this;
+};
-module.exports = PassThrough;
+EventEmitter.prototype.on = EventEmitter.prototype.addListener;
-var Transform = require('./_stream_transform');
+EventEmitter.prototype.once = function(type, listener) {
+ if (!isFunction(listener))
+ throw TypeError('listener must be a function');
-/**/
-var util = require('core-util-is');
-util.inherits = require('inherits');
-/**/
+ var fired = false;
-util.inherits(PassThrough, Transform);
+ function g() {
+ this.removeListener(type, g);
-function PassThrough(options) {
- if (!(this instanceof PassThrough))
- return new PassThrough(options);
+ if (!fired) {
+ fired = true;
+ listener.apply(this, arguments);
+ }
+ }
- Transform.call(this, options);
-}
+ g.listener = listener;
+ this.on(type, g);
-PassThrough.prototype._transform = function(chunk, encoding, cb) {
- cb(null, chunk);
+ return this;
};
-},{"./_stream_transform":33,"core-util-is":7,"inherits":12}],32:[function(require,module,exports){
-(function (process){
-'use strict';
+// emits a 'removeListener' event iff the listener was removed
+EventEmitter.prototype.removeListener = function(type, listener) {
+ var list, position, length, i;
-module.exports = Readable;
+ if (!isFunction(listener))
+ throw TypeError('listener must be a function');
-/**/
-var processNextTick = require('process-nextick-args');
-/**/
+ if (!this._events || !this._events[type])
+ return this;
+ list = this._events[type];
+ length = list.length;
+ position = -1;
-/**/
-var isArray = require('isarray');
-/**/
+ if (list === listener ||
+ (isFunction(list.listener) && list.listener === listener)) {
+ delete this._events[type];
+ if (this._events.removeListener)
+ this.emit('removeListener', type, listener);
+ } else if (isObject(list)) {
+ for (i = length; i-- > 0;) {
+ if (list[i] === listener ||
+ (list[i].listener && list[i].listener === listener)) {
+ position = i;
+ break;
+ }
+ }
-/**/
-var Buffer = require('buffer').Buffer;
-/**/
+ if (position < 0)
+ return this;
-Readable.ReadableState = ReadableState;
+ if (list.length === 1) {
+ list.length = 0;
+ delete this._events[type];
+ } else {
+ list.splice(position, 1);
+ }
-var EE = require('events');
+ if (this._events.removeListener)
+ this.emit('removeListener', type, listener);
+ }
-/**/
-var EElistenerCount = function(emitter, type) {
- return emitter.listeners(type).length;
+ return this;
};
-/**/
+EventEmitter.prototype.removeAllListeners = function(type) {
+ var key, listeners;
+ if (!this._events)
+ return this;
-/**/
-var Stream;
-(function (){try{
- Stream = require('st' + 'ream');
-}catch(_){}finally{
- if (!Stream)
- Stream = require('events').EventEmitter;
-}}())
-/**/
+ // not listening for removeListener, no need to emit
+ if (!this._events.removeListener) {
+ if (arguments.length === 0)
+ this._events = {};
+ else if (this._events[type])
+ delete this._events[type];
+ return this;
+ }
-var Buffer = require('buffer').Buffer;
+ // emit removeListener for all listeners on all events
+ if (arguments.length === 0) {
+ for (key in this._events) {
+ if (key === 'removeListener') continue;
+ this.removeAllListeners(key);
+ }
+ this.removeAllListeners('removeListener');
+ this._events = {};
+ return this;
+ }
-/**/
-var util = require('core-util-is');
-util.inherits = require('inherits');
-/**/
+ listeners = this._events[type];
+ if (isFunction(listeners)) {
+ this.removeListener(type, listeners);
+ } else if (listeners) {
+ // LIFO order
+ while (listeners.length)
+ this.removeListener(type, listeners[listeners.length - 1]);
+ }
+ delete this._events[type];
+ return this;
+};
-/**/
-var debugUtil = require('util');
-var debug;
-if (debugUtil && debugUtil.debuglog) {
- debug = debugUtil.debuglog('stream');
-} else {
- debug = function () {};
-}
-/**/
+EventEmitter.prototype.listeners = function(type) {
+ var ret;
+ if (!this._events || !this._events[type])
+ ret = [];
+ else if (isFunction(this._events[type]))
+ ret = [this._events[type]];
+ else
+ ret = this._events[type].slice();
+ return ret;
+};
-var StringDecoder;
+EventEmitter.prototype.listenerCount = function(type) {
+ if (this._events) {
+ var evlistener = this._events[type];
-util.inherits(Readable, Stream);
+ if (isFunction(evlistener))
+ return 1;
+ else if (evlistener)
+ return evlistener.length;
+ }
+ return 0;
+};
-var Duplex;
-function ReadableState(options, stream) {
- Duplex = Duplex || require('./_stream_duplex');
+EventEmitter.listenerCount = function(emitter, type) {
+ return emitter.listenerCount(type);
+};
- options = options || {};
+function isFunction(arg) {
+ return typeof arg === 'function';
+}
- // 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;
+function isNumber(arg) {
+ return typeof arg === 'number';
+}
- if (stream instanceof Duplex)
- this.objectMode = this.objectMode || !!options.readableObjectMode;
+function isObject(arg) {
+ return typeof arg === 'object' && arg !== null;
+}
- // 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 defaultHwm = this.objectMode ? 16 : 16 * 1024;
- this.highWaterMark = (hwm || hwm === 0) ? hwm : defaultHwm;
+function isUndefined(arg) {
+ return arg === void 0;
+}
- // cast to ints.
- this.highWaterMark = ~~this.highWaterMark;
- this.buffer = [];
- this.length = 0;
- this.pipes = null;
- this.pipesCount = 0;
- this.flowing = null;
- this.ended = false;
- this.endEmitted = false;
- this.reading = false;
+/***/ }),
+/* 12 */
+/***/ (function(module, exports, __webpack_require__) {
- // 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;
+"use strict";
+/* WEBPACK VAR INJECTION */(function(process) {
- // 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;
+if (!process.version ||
+ process.version.indexOf('v0.') === 0 ||
+ process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) {
+ module.exports = nextTick;
+} else {
+ module.exports = process.nextTick;
+}
- // 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';
+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);
+ });
+ }
+}
- // when piping, we only care about 'readable' events that happen
- // after read()ing all the bytes and not getting any pushback.
- this.ranOut = false;
+/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
- // the number of writers that are awaiting a drain event in .pipe()s
- this.awaitDrain = 0;
+/***/ }),
+/* 13 */
+/***/ (function(module, exports, __webpack_require__) {
- // if true, a maybeReadMore has been scheduled
- this.readingMore = false;
+"use strict";
+/* WEBPACK VAR INJECTION */(function(global) {
- 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;
+var buffer = __webpack_require__(0);
+var Buffer = buffer.Buffer;
+var SlowBuffer = buffer.SlowBuffer;
+var MAX_LEN = buffer.kMaxLength || 2147483647;
+exports.alloc = function alloc(size, fill, encoding) {
+ if (typeof Buffer.alloc === 'function') {
+ return Buffer.alloc(size, fill, encoding);
+ }
+ if (typeof encoding === 'number') {
+ throw new TypeError('encoding must not be number');
+ }
+ if (typeof size !== 'number') {
+ throw new TypeError('size must be a number');
+ }
+ if (size > MAX_LEN) {
+ throw new RangeError('size is too large');
+ }
+ var enc = encoding;
+ var _fill = fill;
+ if (_fill === undefined) {
+ enc = undefined;
+ _fill = 0;
+ }
+ var buf = new Buffer(size);
+ if (typeof _fill === 'string') {
+ var fillBuf = new Buffer(_fill, enc);
+ var flen = fillBuf.length;
+ var i = -1;
+ while (++i < size) {
+ buf[i] = fillBuf[i % flen];
+ }
+ } else {
+ buf.fill(_fill);
+ }
+ return buf;
+}
+exports.allocUnsafe = function allocUnsafe(size) {
+ if (typeof Buffer.allocUnsafe === 'function') {
+ return Buffer.allocUnsafe(size);
}
+ if (typeof size !== 'number') {
+ throw new TypeError('size must be a number');
+ }
+ if (size > MAX_LEN) {
+ throw new RangeError('size is too large');
+ }
+ return new Buffer(size);
}
+exports.from = function from(value, encodingOrOffset, length) {
+ if (typeof Buffer.from === 'function' && (!global.Uint8Array || Uint8Array.from !== Buffer.from)) {
+ return Buffer.from(value, encodingOrOffset, length);
+ }
+ if (typeof value === 'number') {
+ throw new TypeError('"value" argument must not be a number');
+ }
+ if (typeof value === 'string') {
+ return new Buffer(value, encodingOrOffset);
+ }
+ if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {
+ var offset = encodingOrOffset;
+ if (arguments.length === 1) {
+ return new Buffer(value);
+ }
+ if (typeof offset === 'undefined') {
+ offset = 0;
+ }
+ var len = length;
+ if (typeof len === 'undefined') {
+ len = value.byteLength - offset;
+ }
+ if (offset >= value.byteLength) {
+ throw new RangeError('\'offset\' is out of bounds');
+ }
+ if (len > value.byteLength - offset) {
+ throw new RangeError('\'length\' is out of bounds');
+ }
+ return new Buffer(value.slice(offset, offset + len));
+ }
+ if (Buffer.isBuffer(value)) {
+ var out = new Buffer(value.length);
+ value.copy(out, 0, 0, value.length);
+ return out;
+ }
+ if (value) {
+ if (Array.isArray(value) || (typeof ArrayBuffer !== 'undefined' && value.buffer instanceof ArrayBuffer) || 'length' in value) {
+ return new Buffer(value);
+ }
+ if (value.type === 'Buffer' && Array.isArray(value.data)) {
+ return new Buffer(value.data);
+ }
+ }
-var Duplex;
-function Readable(options) {
- Duplex = Duplex || require('./_stream_duplex');
+ throw new TypeError('First argument must be a string, Buffer, ' + 'ArrayBuffer, Array, or array-like object.');
+}
+exports.allocUnsafeSlow = function allocUnsafeSlow(size) {
+ if (typeof Buffer.allocUnsafeSlow === 'function') {
+ return Buffer.allocUnsafeSlow(size);
+ }
+ if (typeof size !== 'number') {
+ throw new TypeError('size must be a number');
+ }
+ if (size >= MAX_LEN) {
+ throw new RangeError('size is too large');
+ }
+ return new SlowBuffer(size);
+}
- if (!(this instanceof Readable))
- return new Readable(options);
+/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(5)))
- this._readableState = new ReadableState(options, this);
+/***/ }),
+/* 14 */
+/***/ (function(module, exports, __webpack_require__) {
- // legacy
- this.readable = true;
+"use strict";
+/* WEBPACK VAR INJECTION */(function(process, setImmediate) {// A bit simpler than readable streams.
+// Implement an async ._write(chunk, encoding, cb), and it'll handle all
+// the drain event emission and buffering.
- if (options && typeof options.read === 'function')
- this._read = options.read;
- Stream.call(this);
-}
-// 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;
+module.exports = Writable;
- if (!state.objectMode && typeof chunk === 'string') {
- encoding = encoding || state.defaultEncoding;
- if (encoding !== state.encoding) {
- chunk = new Buffer(chunk, encoding);
- encoding = '';
- }
- }
+/**/
+var processNextTick = __webpack_require__(12);
+/**/
- return readableAddChunk(this, state, chunk, encoding, false);
-};
+/**/
+var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : processNextTick;
+/**/
-// Unshift should *always* be something directly out of read()
-Readable.prototype.unshift = function(chunk) {
- var state = this._readableState;
- return readableAddChunk(this, state, chunk, '', true);
-};
+/**/
+var Duplex;
+/**/
-Readable.prototype.isPaused = function() {
- return this._readableState.flowing === false;
-};
+Writable.WritableState = WritableState;
-function readableAddChunk(stream, state, chunk, encoding, addToFront) {
- var er = chunkInvalid(state, chunk);
- if (er) {
- stream.emit('error', er);
- } else if (chunk === null) {
- state.reading = false;
- onEofChunk(stream, state);
- } else if (state.objectMode || chunk && chunk.length > 0) {
- if (state.ended && !addToFront) {
- var e = new Error('stream.push() after EOF');
- stream.emit('error', e);
- } else if (state.endEmitted && addToFront) {
- var e = new Error('stream.unshift() after end event');
- stream.emit('error', e);
- } else {
- if (state.decoder && !addToFront && !encoding)
- chunk = state.decoder.write(chunk);
+/**/
+var util = __webpack_require__(8);
+util.inherits = __webpack_require__(2);
+/**/
- if (!addToFront)
- state.reading = false;
+/**/
+var internalUtil = {
+ deprecate: __webpack_require__(46)
+};
+/**/
- // if we want the data now, just emit it.
- 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);
+/**/
+var Stream = __webpack_require__(27);
+/**/
- if (state.needReadable)
- emitReadable(stream);
- }
+var Buffer = __webpack_require__(0).Buffer;
+/**/
+var bufferShim = __webpack_require__(13);
+/**/
- maybeReadMore(stream, state);
- }
- } else if (!addToFront) {
- state.reading = false;
- }
+util.inherits(Writable, Stream);
- return needMoreData(state);
+function nop() {}
+
+function WriteReq(chunk, encoding, cb) {
+ this.chunk = chunk;
+ this.encoding = encoding;
+ this.callback = cb;
+ this.next = null;
}
+function WritableState(options, stream) {
+ Duplex = Duplex || __webpack_require__(6);
-// 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);
-}
+ options = options || {};
-// 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;
-};
+ // object stream flag to indicate whether or not this stream
+ // contains buffers or objects.
+ this.objectMode = !!options.objectMode;
-// 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
- n--;
- n |= n >>> 1;
- n |= n >>> 2;
- n |= n >>> 4;
- n |= n >>> 8;
- n |= n >>> 16;
- n++;
- }
- return n;
-}
+ if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode;
-function howMuchToRead(n, state) {
- if (state.length === 0 && state.ended)
- return 0;
+ // 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 defaultHwm = this.objectMode ? 16 : 16 * 1024;
+ this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm;
- if (state.objectMode)
- return n === 0 ? 0 : 1;
+ // cast to ints.
+ this.highWaterMark = ~~this.highWaterMark;
- if (n === null || isNaN(n)) {
- // only flow one buffer at a time
- if (state.flowing && state.buffer.length)
- return state.buffer[0].length;
- else
- return state.length;
- }
+ // 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;
- if (n <= 0)
- return 0;
+ // 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;
- // If we're asking for more than the target buffer level,
- // then raise the water mark. Bump up to the next highest
- // power of 2, to prevent increasing it excessively in tiny
- // amounts.
- if (n > state.highWaterMark)
- state.highWaterMark = computeNewHighWaterMark(n);
-
- // don't have that much. return null, unless we've ended.
- if (n > state.length) {
- if (!state.ended) {
- state.needReadable = true;
- return 0;
- } else {
- return state.length;
- }
- }
+ // 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';
- return n;
-}
+ // 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;
-// you can override either this method, or the async _read(n) below.
-Readable.prototype.read = function(n) {
- debug('read', n);
- var state = this._readableState;
- var nOrig = n;
+ // a flag to see when we're in the middle of a write.
+ this.writing = false;
- if (typeof n !== 'number' || n > 0)
- state.emittedReadable = false;
+ // when true all writes will be buffered until .uncork() call
+ this.corked = 0;
- // 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;
- }
+ // 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;
- n = howMuchToRead(n, state);
+ // 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;
- // 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;
- }
+ // the callback that's passed to _write(chunk,cb)
+ this.onwrite = function (er) {
+ onwrite(stream, er);
+ };
- // 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.
+ // the callback that the user supplies to write(chunk,encoding,cb)
+ this.writecb = null;
- // if we need a readable event, then we need to do some reading.
- var doRead = state.needReadable;
- debug('need readable', doRead);
+ // the amount that is being written when _write is called.
+ this.writelen = 0;
- // 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);
- }
+ this.bufferedRequest = null;
+ this.lastBufferedRequest = null;
- // however, if we've ended, then there's no point, and if we're already
- // reading, then it's unnecessary.
+ // 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.')
+ });
+ } 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;
+
+ return object && object._writableState instanceof WritableState;
+ }
+ });
+} else {
+ realHasInstance = function (object) {
+ return object instanceof this;
+ };
+}
+
+function Writable(options) {
+ Duplex = Duplex || __webpack_require__(6);
+
+ // 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;
+ }
+
+ 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);
+ processNextTick(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);
+ processNextTick(cb, er);
+ valid = false;
+ }
+ return valid;
+}
+
+Writable.prototype.write = function (chunk, encoding, cb) {
+ var state = this._writableState;
+ var ret = false;
+ var isBuf = Buffer.isBuffer(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 = bufferShim.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) {
+ chunk = decodeChunk(state, chunk, encoding);
+ if (Buffer.isBuffer(chunk)) encoding = 'buffer';
+ }
+ 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 = new WriteReq(chunk, encoding, cb);
+ 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) processNextTick(cb, er);else cb(er);
+
+ stream._writableState.errorEmitted = true;
+ stream.emit('error', er);
+}
+
+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;
+ while (entry) {
+ buffer[count] = entry;
+ entry = entry.next;
+ count += 1;
+ }
+
+ 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);
+ }
+ } 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;
+ // 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.bufferedRequestCount = 0;
+ 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 prefinish(stream, state) {
+ if (!state.prefinished) {
+ state.prefinished = true;
+ stream.emit('prefinish');
+ }
+}
+
+function finishMaybe(stream, state) {
+ var need = needFinish(state);
+ if (need) {
+ if (state.pendingcb === 0) {
+ prefinish(stream, state);
+ state.finished = true;
+ stream.emit('finish');
+ } else {
+ prefinish(stream, state);
+ }
+ }
+ return need;
+}
+
+function endWritable(stream, state, cb) {
+ state.ending = true;
+ finishMaybe(stream, state);
+ if (cb) {
+ if (state.finished) processNextTick(cb);else stream.once('finish', cb);
+ }
+ state.ended = true;
+ stream.writable = false;
+}
+
+// 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 (err) {
+ var entry = _this.entry;
+ _this.entry = null;
+ while (entry) {
+ var cb = entry.callback;
+ state.pendingcb--;
+ cb(err);
+ entry = entry.next;
+ }
+ if (state.corkedRequestsFree) {
+ state.corkedRequestsFree.next = _this;
+ } else {
+ state.corkedRequestsFree = _this;
+ }
+ };
+}
+/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3), __webpack_require__(44).setImmediate))
+
+/***/ }),
+/* 15 */
+/***/ (function(module, exports, __webpack_require__) {
+
+/* WEBPACK VAR INJECTION */(function(Buffer) {var toString = Object.prototype.toString
+
+var isModern = (
+ typeof Buffer.alloc === 'function' &&
+ typeof Buffer.allocUnsafe === 'function' &&
+ typeof Buffer.from === 'function'
+)
+
+function isArrayBuffer (input) {
+ return toString.call(input).slice(8, -1) === 'ArrayBuffer'
+}
+
+function fromArrayBuffer (obj, byteOffset, length) {
+ byteOffset >>>= 0
+
+ var maxLength = obj.byteLength - byteOffset
+
+ if (maxLength < 0) {
+ throw new RangeError("'offset' is out of bounds")
+ }
+
+ if (length === undefined) {
+ length = maxLength
+ } else {
+ length >>>= 0
+
+ if (length > maxLength) {
+ throw new RangeError("'length' is out of bounds")
+ }
+ }
+
+ return isModern
+ ? Buffer.from(obj.slice(byteOffset, byteOffset + length))
+ : new Buffer(new Uint8Array(obj.slice(byteOffset, byteOffset + length)))
+}
+
+function fromString (string, encoding) {
+ if (typeof encoding !== 'string' || encoding === '') {
+ encoding = 'utf8'
+ }
+
+ if (!Buffer.isEncoding(encoding)) {
+ throw new TypeError('"encoding" must be a valid string encoding')
+ }
+
+ return isModern
+ ? Buffer.from(string, encoding)
+ : new Buffer(string, encoding)
+}
+
+function bufferFrom (value, encodingOrOffset, length) {
+ if (typeof value === 'number') {
+ throw new TypeError('"value" argument must not be a number')
+ }
+
+ if (isArrayBuffer(value)) {
+ return fromArrayBuffer(value, encodingOrOffset, length)
+ }
+
+ if (typeof value === 'string') {
+ return fromString(value, encodingOrOffset)
+ }
+
+ return isModern
+ ? Buffer.from(value)
+ : new Buffer(value)
+}
+
+module.exports = bufferFrom
+
+/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(0).Buffer))
+
+/***/ }),
+/* 16 */
+/***/ (function(module, exports, __webpack_require__) {
+
+"use strict";
+/* WEBPACK VAR INJECTION */(function(process) {/**
+ * Copyright 2014 IBM Corp. All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+
+var Duplex = __webpack_require__(1).Duplex;
+var util = __webpack_require__(4);
+var pick = __webpack_require__(30);
+var W3CWebSocket = __webpack_require__(56).w3cwebsocket;
+var contentType = __webpack_require__(17);
+var qs = __webpack_require__(31);
+
+var OPENING_MESSAGE_PARAMS_ALLOWED = [
+ 'inactivity_timeout',
+ 'timestamps',
+ 'word_confidence',
+ 'content-type',
+ 'interim_results',
+ 'keywords',
+ 'keywords_threshold',
+ 'max_alternatives',
+ 'word_alternatives_threshold',
+ 'profanity_filter',
+ 'smart_formatting',
+ 'speaker_labels'
+];
+
+var QUERY_PARAMS_ALLOWED = ['customization_id', 'acoustic_customization_id', 'model', 'watson-token', 'access_token', 'X-Watson-Learning-Opt-Out'];
+
+/**
+ * pipe()-able Node.js Duplex stream - accepts binary audio and emits text/objects in it's `data` events.
+ *
+ * Uses WebSockets under the hood. For audio with no recognizable speech, no `data` events are emitted.
+ *
+ * By default, only finalized text is emitted in the data events, however when `objectMode`/`readableObjectMode` and `interim_results` are enabled, both interim and final results objects are emitted.
+ * WriteableElementStream uses this, for example, to live-update the DOM with word-by-word transcriptions.
+ *
+ * Note that the WebSocket connection is not established until the first chunk of data is recieved. This allows for auto-detection of content type (for wav/flac/opus audio).
+ *
+ * @param {Object} options
+ * @param {String} [options.model='en-US_BroadbandModel'] - voice model to use. Microphone streaming only supports broadband models.
+ * @param {String} [options.url='wss://stream.watsonplatform.net/speech-to-text/api'] base URL for service
+ * @param {String} [options.token] - Auth token for CF services
+ * @param {String} options.access_token - IAM Access Token for RC services
+ * @param {Object} [options.headers] - Only works in Node.js, not in browsers. Allows for custom headers to be set, including an Authorization header (preventing the need for auth tokens)
+ * @param {String} [options.content-type='audio/wav'] - content type of audio; can be automatically determined from file header in most cases. only wav, flac, ogg/opus, and webm are supported
+ * @param {Boolean} [options.interim_results=true] - Send back non-final previews of each "sentence" as it is being processed. These results are ignored in text mode.
+ * @param {Boolean} [options.word_confidence=false] - include confidence scores with results.
+ * @param {Boolean} [options.timestamps=false] - include timestamps with results.
+ * @param {Number} [options.max_alternatives=1] - maximum number of alternative transcriptions to include.
+ * @param {Array} [options.keywords] - a list of keywords to search for in the audio
+ * @param {Number} [options.keywords_threshold] - Number between 0 and 1 representing the minimum confidence before including a keyword in the results. Required when options.keywords is set
+ * @param {Number} [options.word_alternatives_threshold] - Number between 0 and 1 representing the minimum confidence before including an alternative word in the results. Must be set to enable word alternatives,
+ * @param {Boolean} [options.profanity_filter=false] - set to true to filter out profanity and replace the words with *'s
+ * @param {Number} [options.inactivity_timeout=30] - how many seconds of silence before automatically closing the stream. use -1 for infinity
+ * @param {Boolean} [options.readableObjectMode=false] - emit `result` objects instead of string Buffers for the `data` events. Does not affect input (which must be binary)
+ * @param {Boolean} [options.objectMode=false] - alias for options.readableObjectMode
+ * @param {Number} [options.X-Watson-Learning-Opt-Out=false] - set to true to opt-out of allowing Watson to use this request to improve it's services
+ * @param {Boolean} [options.smart_formatting=false] - formats numeric values such as dates, times, currency, etc.
+ * @param {String} [options.customization_id] - Customization ID
+ * @param {String} [options.acoustic_customization_id] - Acoustic customization ID
+ *
+ * @constructor
+ */
+function RecognizeStream(options) {
+ // this stream only supports objectMode on the output side.
+ // It must receive binary data input.
+ if (options.objectMode) {
+ options.readableObjectMode = true;
+ delete options.objectMode;
+ }
+ Duplex.call(this, options);
+ this.options = options;
+ this.listening = false;
+ this.initialized = false;
+ this.finished = false;
+
+ this.on('newListener', function(event) {
+ if (!options.silent) {
+ if (event === 'results' || event === 'result' || event === 'speaker_labels') {
+ // eslint-disable-next-line no-console
+ console.log(
+ new Error(
+ 'Watson Speech to Text RecognizeStream: the ' +
+ event +
+ ' event was deprecated. ' +
+ "Please set {objectMode: true} and listen for the 'data' event instead. " +
+ 'Pass {silent: true} to disable this message.'
+ )
+ );
+ } else if (event === 'connection-close') {
+ // eslint-disable-next-line no-console
+ console.log(
+ new Error(
+ 'Watson Speech to Text RecognizeStream: the ' +
+ event +
+ ' event was deprecated. ' +
+ "Please listen for the 'close' event instead. " +
+ 'Pass {silent: true} to disable this message.'
+ )
+ );
+ } else if (event === 'connect') {
+ // eslint-disable-next-line no-console
+ console.log(
+ new Error(
+ 'Watson Speech to Text RecognizeStream: the ' +
+ event +
+ ' event was deprecated. ' +
+ "Please listen for the 'open' event instead. " +
+ 'Pass {silent: true} to disable this message.'
+ )
+ );
+ }
+ }
+ });
+}
+util.inherits(RecognizeStream, Duplex);
+
+RecognizeStream.WEBSOCKET_CONNECTION_ERROR = 'WebSocket connection error';
+
+RecognizeStream.prototype.initialize = function() {
+ var options = this.options;
+
+ if (options.token && !options['watson-token']) {
+ options['watson-token'] = options.token;
+ }
+ if (options.content_type && !options['content-type']) {
+ options['content-type'] = options.content_type;
+ }
+ if (options['X-WDC-PL-OPT-OUT'] && !options['X-Watson-Learning-Opt-Out']) {
+ options['X-Watson-Learning-Opt-Out'] = options['X-WDC-PL-OPT-OUT'];
+ }
+
+ var queryParams = util._extend(
+ 'customization_id' in options ? pick(options, QUERY_PARAMS_ALLOWED) : { model: 'en-US_BroadbandModel' },
+ pick(options, QUERY_PARAMS_ALLOWED)
+ );
+
+ var queryString = qs.stringify(queryParams);
+ var url = (options.url || 'wss://stream.watsonplatform.net/speech-to-text/api').replace(/^http/, 'ws') + '/v1/recognize?' + queryString;
+
+ var openingMessage = pick(options, OPENING_MESSAGE_PARAMS_ALLOWED);
+ openingMessage.action = 'start';
+
+ var self = this;
+
+ // node params: requestUrl, protocols, origin, headers, extraRequestOptions
+ // browser params: requestUrl, protocols (all others ignored)
+ var socket = (this.socket = new W3CWebSocket(url, null, null, options.headers, null));
+
+ // when the input stops, let the service know that we're done
+ self.on('finish', self.finish.bind(self));
+
+ /**
+ * This can happen if the credentials are invalid - in that case, the response from DataPower doesn't include the
+ * necessary CORS headers, so JS can't even read it :(
+ *
+ * @param {Event} event - event object with essentially no useful information
+ */
+ socket.onerror = function(event) {
+ self.listening = false;
+ var err = new Error('WebSocket connection error');
+ err.name = RecognizeStream.WEBSOCKET_CONNECTION_ERROR;
+ err.event = event;
+ self.emit('error', err);
+ self.push(null);
+ };
+
+ this.socket.onopen = function() {
+ self.sendJSON(openingMessage);
+ /**
+ * emitted once the WebSocket connection has been established
+ * @event RecognizeStream#open
+ */
+ self.emit('open');
+ };
+
+ this.socket.onclose = function(e) {
+ // if (self.listening) {
+ self.listening = false;
+ self.push(null);
+ // }
+ /**
+ * @event RecognizeStream#close
+ * @param {Number} reasonCode
+ * @param {String} description
+ */
+ self.emit('close', e.code, e.reason);
+ };
+
+ /**
+ * @event RecognizeStream#error
+ * @param {String} msg custom error message
+ * @param {*} [frame] unprocessed frame (should have a .data property with either string or binary data)
+ * @param {Error} [err]
+ */
+ function emitError(msg, frame, err) {
+ if (err) {
+ err.message = msg + ' ' + err.message;
+ } else {
+ err = new Error(msg);
+ }
+ err.raw = frame;
+ self.emit('error', err);
+ }
+
+ socket.onmessage = function(frame) {
+ if (typeof frame.data !== 'string') {
+ return emitError('Unexpected binary data received from server', frame);
+ }
+
+ var data;
+ try {
+ data = JSON.parse(frame.data);
+ } catch (jsonEx) {
+ return emitError('Invalid JSON received from service:', frame, jsonEx);
+ }
+
+ /**
+ * Emit any messages received over the wire, mainly used for debugging.
+ *
+ * @event RecognizeStream#message
+ * @param {Object} message - frame object with a data attribute that's either a string or a Buffer/TypedArray
+ * @param {Object} [data] - parsed JSON object (if possible);
+ */
+ self.emit('message', frame, data);
+
+ if (data.error) {
+ emitError(data.error, frame);
+ } else if (data.state === 'listening') {
+ // this is emitted both when the server is ready for audio, and after we send the close message to indicate that it's done processing
+ if (self.listening) {
+ self.listening = false;
+ socket.close();
+ } else {
+ self.listening = true;
+ /**
+ * Emitted when the Watson Service indicates readiness to transcribe audio. Any audio sent before this point will be buffered until now.
+ * @event RecognizeStream#listening
+ */
+ self.emit('listening');
+ }
+ } else {
+ if (options.readableObjectMode) {
+ /**
+ * Object with interim or final results, possibly including confidence scores, alternatives, and word timing.
+ * @event RecognizeStream#data
+ * @param {Object} data
+ */
+ self.push(data);
+ } else if (Array.isArray(data.results)) {
+ data.results.forEach(function(result) {
+ if (result.final && result.alternatives) {
+ /**
+ * Finalized text
+ * @event RecognizeStream#data
+ * @param {String} transcript
+ */
+ self.push(result.alternatives[0].transcript, 'utf8');
+ }
+ });
+ }
+ }
+ };
+
+ this.initialized = true;
+};
+
+RecognizeStream.prototype.sendJSON = function sendJSON(msg) {
+ /**
+ * Emits any JSON object sent to the service from the client. Mainly used for debugging.
+ * @event RecognizeStream#send-json
+ * @param {Object} msg
+ */
+ this.emit('send-json', msg);
+ return this.socket.send(JSON.stringify(msg));
+};
+
+RecognizeStream.prototype.sendData = function sendData(data) {
+ /**
+ * Emits any Binary object sent to the service from the client. Mainly used for debugging.
+ * @event RecognizeStream#send-data
+ * @param {Object} msg
+ */
+ this.emit('send-data', data);
+ return this.socket.send(data);
+};
+
+RecognizeStream.prototype._read = function() /* size*/ {
+ // there's no easy way to control reads from the underlying library
+ // so, the best we can do here is a no-op
+};
+
+RecognizeStream.ERROR_UNRECOGNIZED_FORMAT = 'UNRECOGNIZED_FORMAT';
+
+RecognizeStream.prototype._write = function(chunk, encoding, callback) {
+ var self = this;
+ if (self.finished) {
+ // can't send any more data after the stop message (although this shouldn't happen normally...)
+ return;
+ }
+ if (!this.initialized) {
+ if (!this.options['content-type']) {
+ var ct = RecognizeStream.getContentType(chunk);
+ if (ct) {
+ this.options['content-type'] = ct;
+ } else {
+ var err = new Error('Unable to determine content-type from file header, please specify manually.');
+ err.name = RecognizeStream.ERROR_UNRECOGNIZED_FORMAT;
+ this.emit('error', err);
+ this.push(null);
+ return;
+ }
+ }
+ this.initialize();
+
+ this.once('open', function() {
+ self.sendData(chunk);
+ self.afterSend(callback);
+ });
+ } else {
+ self.sendData(chunk);
+ this.afterSend(callback);
+ }
+};
+
+/**
+ * Flow control - don't ask for more data until we've finished what we have
+ *
+ * Notes:
+ *
+ * This limits upload speed to 100 * options.highWaterMark / second.
+ *
+ * The default highWaterMark is 16kB, so the default max upload speed is ~1.6MB/s.
+ *
+ * Microphone input provides audio at a (downsampled) rate of:
+ * 16000 samples/s * 16-bits * 1 channel = 32kB/s
+ * (note the bits to Bytes conversion there)
+ *
+ * @private
+ * @param {Function} next
+ */
+RecognizeStream.prototype.afterSend = function afterSend(next) {
+ if (this.socket.bufferedAmount <= (this._writableState.highWaterMark || 0)) {
+ process.nextTick(next);
+ } else {
+ setTimeout(this.afterSend.bind(this, next), 10);
+ }
+};
+
+/**
+ * Prevents any more audio from being sent over the WebSocket and gracefully closes the connection.
+ * Additional data may still be emitted up until the `end` event is triggered.
+ */
+RecognizeStream.prototype.stop = function() {
+ /**
+ * Event emitted when the stop method is called. Mainly for synchronising with file reading and playback.
+ * @event RecognizeStream#stop
+ */
+ this.emit('stop');
+ this.finish();
+};
+
+RecognizeStream.prototype.finish = function finish() {
+ // this is called both when the source stream finishes, and when .stop() is fired, but we only want to send the stop message once.
+ if (this.finished) {
+ return;
+ }
+ this.finished = true;
+ var self = this;
+ var closingMessage = { action: 'stop' };
+ if (self.socket && self.socket.readyState === self.socket.OPEN) {
+ self.sendJSON(closingMessage);
+ } else {
+ this.once('open', function() {
+ self.sendJSON(closingMessage);
+ });
+ }
+};
+
+RecognizeStream.prototype.promise = __webpack_require__(9);
+
+RecognizeStream.getContentType = function(buffer) {
+ // the substr really shouldn't be necessary, but there's a bug somewhere that can cause buffer.slice(0,4) to return
+ // the entire contents of the buffer, so it's a failsafe to catch that
+ return contentType.fromHeader(buffer);
+};
+
+module.exports = RecognizeStream;
+
+/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
+
+/***/ }),
+/* 17 */
+/***/ (function(module, exports, __webpack_require__) {
+
+"use strict";
+
+
+var extname = __webpack_require__(59).extname;
+
+// This module attempts to identify common content-types based on the filename or header.
+// It is not exhaustive, and for best results, you should always manually specify the content-type option.
+// See the complete list of supported content-types at
+// https://console.bluemix.net/docs/services/speech-to-text/input.html#formats
+
+// *some* file types can be identified by the first 3-4 bytes of the file
+var headerContentTypes = {
+ fLaC: 'audio/flac',
+ RIFF: 'audio/wav',
+ OggS: 'audio/ogg',
+ ID3: 'audio/mp3',
+ '\u001aEߣ': 'audio/webm' // String for first four hex's of webm: [1A][45][DF][A3] (https://www.matroska.org/technical/specs/index.html#EBML)
+};
+
+/**
+ * Takes the beginning of an audio file and returns the associated content-type / mime type
+ *
+ * @param {Buffer} buffer with at least the first 4 bytes of the file
+ * @return {String|undefined} - the contentType of undefined
+ */
+exports.fromHeader = function contentTypeFromHeader(buffer) {
+ var headerStr = buffer
+ .slice(0, 4)
+ .toString()
+ .substr(0, 4);
+ // mp3's are only consistent for the first 3 characters
+ return headerContentTypes[headerStr] || headerContentTypes[headerStr.substr(0, 3)];
+};
+
+var filenameContentTypes = {
+ '.mp3': 'audio/mp3',
+ '.wav': 'audio/wav',
+ '.flac': 'audio/flac',
+ '.ogg': 'audio/ogg',
+ '.oga': 'audio/ogg',
+ '.opus': 'audio/ogg; codec=opus',
+ '.webm': 'audio/webm'
+};
+
+/**
+ * Guess the content type from the filename
+ *
+ * Note: Blob and File objects include a .type property, but we're ignoring it because it's frequently either
+ * incorrect (e.g. video/ogg instead of audio/ogg) or else a different format than what's expected (e.g. audio/x-wav)
+ *
+ * @param {String|Blob|File} file - string filename or url, or binary File/Blob object
+ * @return {String|undefined}
+ */
+exports.fromFilename = function contentTypeFromFilename(file) {
+ // todo: consider retrying with querystring & hash stripped from URLs
+ var ext = extname((typeof file === 'string' && file) || file.name || '');
+ return filenameContentTypes[ext];
+};
+
+
+/***/ }),
+/* 18 */
+/***/ (function(module, exports, __webpack_require__) {
+
+"use strict";
+
+
+var Transform = __webpack_require__(1).Transform;
+var util = __webpack_require__(4);
+var clone = __webpack_require__(19);
+var defaults = __webpack_require__(10);
+
+/**
+ * Applies some basic formatting to transcriptions:
+ * - Capitalize the first word of each sentence
+ * - Add a period to the end
+ * - Fix any "cruft" in the transcription
+ * - etc.
+ *
+ * May be used as either a Stream, or a standalone helper.
+ *
+ * @param {Object} opts
+ * @param {String} [opts.model] - some models / languages need special handling
+ * @param {String} [opts.hesitation=''] - what to put down for a "hesitation" event, also consider \u2026 (ellipsis: ...)
+ * @param {Boolean} [options.objectMode=false] - emit `result` objects instead of string Buffers for the `data` events.
+ * @constructor
+ */
+function FormatStream(opts) {
+ this.options = defaults(opts, {
+ model: '', // some models should have all spaces removed
+ hesitation: '',
+ decodeStrings: false // false = don't convert strings to buffers before passing to _write
+ });
+ Transform.call(this, this.options);
+
+ this.isJaCn = this.options.model.substring(0, 5) === 'ja-JP' || this.options.model.substring(0, 5) === 'zh-CN';
+ this._transform = this.options.objectMode ? this.transformObject : this.transformString;
+}
+util.inherits(FormatStream, Transform);
+
+var reHesitation = /%HESITATION ?/g; // https://console.bluemix.net/docs/services/speech-to-text/output.html#output - D_ is handled below
+var reRepeatedCharacter = /([a-z])\1{2,}/gi; // detect the same character repeated three or more times and remove it
+var reDUnderscoreWords = /D_[^\s]+/g; // replace D_(anything)
+
+/**
+ * Formats one or more words, removing special symbols, junk, and spacing for some languages
+ * @param {String} text
+ * @param {Boolean} isFinal
+ * @return {String}
+ */
+FormatStream.prototype.clean = function clean(text) {
+ // clean out "junk"
+ text = text
+ .replace(reHesitation, this.options.hesitation ? this.options.hesitation.trim() + ' ' : this.options.hesitation)
+ .replace(reRepeatedCharacter, '')
+ .replace(reDUnderscoreWords, '');
+
+ // remove spaces for Japanese and Chinese
+ if (this.isJaCn) {
+ text = text.replace(/ /g, '');
+ }
+
+ return text.trim() + ' '; // we want exactly 1 space at the end
+};
+
+/**
+ * Capitalizes the first word of a sentence
+ * @param {String} text
+ * @return {string}
+ */
+FormatStream.prototype.capitalize = function capitalize(text) {
+ // capitalize first word, returns '' in the case of an empty word
+ return text.charAt(0).toUpperCase() + text.substring(1);
+};
+
+/**
+ * Puts a period on the end of a sentence
+ * @param {String} text
+ * @return {string}
+ */
+FormatStream.prototype.period = function period(text) {
+ text = text.trim();
+ // don't put a period down if the clean stage remove all of the text
+ if (!text) {
+ return ' ';
+ }
+ // just add a space if the sentence ends in an ellipse
+ if (text.substr(-1) === '\u2026') {
+ return text + ' ';
+ }
+ return text + (this.isJaCn ? '。' : '. ');
+};
+
+FormatStream.prototype.transformString = function(chunk, encoding, next) {
+ this.push(this.formatString(chunk.toString()));
+ next();
+};
+
+FormatStream.prototype.transformObject = function formatResult(result, encoding, next) {
+ this.push(this.formatResult(result));
+ next();
+};
+
+/**
+ * Formats a single string result.
+ *
+ * May be used outside of Node.js streams
+ *
+ * @param {String} str - text to format
+ * @param {bool} [isInterim=false] - set to true to prevent adding a period to the end of the sentence
+ * @return {String}
+ */
+FormatStream.prototype.formatString = function(str, isInterim) {
+ str = this.capitalize(this.clean(str));
+ return isInterim ? str : this.period(str);
+};
+
+/**
+ * Creates a new result with all transcriptions formatted
+ *
+ * May be used outside of Node.js streams
+ *
+ * @param {Object} data
+ * @return {Object}
+ */
+FormatStream.prototype.formatResult = function formatResult(data) {
+ data = clone(data);
+ if (Array.isArray(data.results)) {
+ data.results.forEach(function(result, i) {
+ // if there are multiple interim results (as produced by the speaker stream),
+ // treat the text as final in all but the last result
+ var textFinal = result.final || i !== data.results.length - 1;
+
+ result.alternatives = result.alternatives.map(function(alt) {
+ alt.transcript = this.formatString(alt.transcript, !textFinal);
+ if (alt.timestamps) {
+ alt.timestamps = alt.timestamps
+ .map(function(ts, j, arr) {
+ // timestamps is an array of arrays, each sub-array is in the form ["word", startTime, endTime]'
+ ts[0] = this.clean(ts[0]);
+ if (j === 0) {
+ ts[0] = this.capitalize(ts[0]);
+ }
+
+ if (j === arr.length - 1 && textFinal) {
+ ts[0] = this.period(ts[0]);
+ }
+ return ts;
+ }, this)
+ .filter(function(ts) {
+ return ts[0]; // remove any timestamps without a word (due to cleaning out junk words)
+ });
+ }
+ return alt;
+ }, this);
+ }, this);
+ }
+ return data;
+};
+
+FormatStream.prototype.promise = __webpack_require__(9);
+
+module.exports = FormatStream;
+
+
+/***/ }),
+/* 19 */
+/***/ (function(module, exports, __webpack_require__) {
+
+/* WEBPACK VAR INJECTION */(function(Buffer) {var clone = (function() {
+'use strict';
+
+function _instanceof(obj, type) {
+ return type != null && obj instanceof type;
+}
+
+var nativeMap;
+try {
+ nativeMap = Map;
+} catch(_) {
+ // maybe a reference error because no `Map`. Give it a dummy value that no
+ // value will ever be an instanceof.
+ nativeMap = function() {};
+}
+
+var nativeSet;
+try {
+ nativeSet = Set;
+} catch(_) {
+ nativeSet = function() {};
+}
+
+var nativePromise;
+try {
+ nativePromise = Promise;
+} catch(_) {
+ nativePromise = function() {};
+}
+
+/**
+ * Clones (copies) an Object using deep copying.
+ *
+ * This function supports circular references by default, but if you are certain
+ * there are no circular references in your object, you can save some CPU time
+ * by calling clone(obj, false).
+ *
+ * Caution: if `circular` is false and `parent` contains circular references,
+ * your program may enter an infinite loop and crash.
+ *
+ * @param `parent` - the object to be cloned
+ * @param `circular` - set to true if the object to be cloned may contain
+ * circular references. (optional - true by default)
+ * @param `depth` - set to a number if the object is only to be cloned to
+ * a particular depth. (optional - defaults to Infinity)
+ * @param `prototype` - sets the prototype to be used when cloning an object.
+ * (optional - defaults to parent prototype).
+ * @param `includeNonEnumerable` - set to true if the non-enumerable properties
+ * should be cloned as well. Non-enumerable properties on the prototype
+ * chain will be ignored. (optional - false by default)
+*/
+function clone(parent, circular, depth, prototype, includeNonEnumerable) {
+ if (typeof circular === 'object') {
+ depth = circular.depth;
+ prototype = circular.prototype;
+ includeNonEnumerable = circular.includeNonEnumerable;
+ circular = circular.circular;
+ }
+ // maintain two arrays for circular references, where corresponding parents
+ // and children have the same index
+ var allParents = [];
+ var allChildren = [];
+
+ var useBuffer = typeof Buffer != 'undefined';
+
+ if (typeof circular == 'undefined')
+ circular = true;
+
+ if (typeof depth == 'undefined')
+ depth = Infinity;
+
+ // recurse this function so we don't reset allParents and allChildren
+ function _clone(parent, depth) {
+ // cloning null always returns null
+ if (parent === null)
+ return null;
+
+ if (depth === 0)
+ return parent;
+
+ var child;
+ var proto;
+ if (typeof parent != 'object') {
+ return parent;
+ }
+
+ if (_instanceof(parent, nativeMap)) {
+ child = new nativeMap();
+ } else if (_instanceof(parent, nativeSet)) {
+ child = new nativeSet();
+ } else if (_instanceof(parent, nativePromise)) {
+ child = new nativePromise(function (resolve, reject) {
+ parent.then(function(value) {
+ resolve(_clone(value, depth - 1));
+ }, function(err) {
+ reject(_clone(err, depth - 1));
+ });
+ });
+ } else if (clone.__isArray(parent)) {
+ child = [];
+ } else if (clone.__isRegExp(parent)) {
+ child = new RegExp(parent.source, __getRegExpFlags(parent));
+ if (parent.lastIndex) child.lastIndex = parent.lastIndex;
+ } else if (clone.__isDate(parent)) {
+ child = new Date(parent.getTime());
+ } else if (useBuffer && Buffer.isBuffer(parent)) {
+ child = new Buffer(parent.length);
+ parent.copy(child);
+ return child;
+ } else if (_instanceof(parent, Error)) {
+ child = Object.create(parent);
+ } else {
+ if (typeof prototype == 'undefined') {
+ proto = Object.getPrototypeOf(parent);
+ child = Object.create(proto);
+ }
+ else {
+ child = Object.create(prototype);
+ proto = prototype;
+ }
+ }
+
+ if (circular) {
+ var index = allParents.indexOf(parent);
+
+ if (index != -1) {
+ return allChildren[index];
+ }
+ allParents.push(parent);
+ allChildren.push(child);
+ }
+
+ if (_instanceof(parent, nativeMap)) {
+ parent.forEach(function(value, key) {
+ var keyChild = _clone(key, depth - 1);
+ var valueChild = _clone(value, depth - 1);
+ child.set(keyChild, valueChild);
+ });
+ }
+ if (_instanceof(parent, nativeSet)) {
+ parent.forEach(function(value) {
+ var entryChild = _clone(value, depth - 1);
+ child.add(entryChild);
+ });
+ }
+
+ for (var i in parent) {
+ var attrs;
+ if (proto) {
+ attrs = Object.getOwnPropertyDescriptor(proto, i);
+ }
+
+ if (attrs && attrs.set == null) {
+ continue;
+ }
+ child[i] = _clone(parent[i], depth - 1);
+ }
+
+ if (Object.getOwnPropertySymbols) {
+ var symbols = Object.getOwnPropertySymbols(parent);
+ for (var i = 0; i < symbols.length; i++) {
+ // Don't need to worry about cloning a symbol because it is a primitive,
+ // like a number or string.
+ var symbol = symbols[i];
+ var descriptor = Object.getOwnPropertyDescriptor(parent, symbol);
+ if (descriptor && !descriptor.enumerable && !includeNonEnumerable) {
+ continue;
+ }
+ child[symbol] = _clone(parent[symbol], depth - 1);
+ if (!descriptor.enumerable) {
+ Object.defineProperty(child, symbol, {
+ enumerable: false
+ });
+ }
+ }
+ }
+
+ if (includeNonEnumerable) {
+ var allPropertyNames = Object.getOwnPropertyNames(parent);
+ for (var i = 0; i < allPropertyNames.length; i++) {
+ var propertyName = allPropertyNames[i];
+ var descriptor = Object.getOwnPropertyDescriptor(parent, propertyName);
+ if (descriptor && descriptor.enumerable) {
+ continue;
+ }
+ child[propertyName] = _clone(parent[propertyName], depth - 1);
+ Object.defineProperty(child, propertyName, {
+ enumerable: false
+ });
+ }
+ }
+
+ return child;
+ }
+
+ return _clone(parent, depth);
+}
+
+/**
+ * Simple flat clone using prototype, accepts only objects, usefull for property
+ * override on FLAT configuration object (no nested props).
+ *
+ * USE WITH CAUTION! This may not behave as you wish if you do not know how this
+ * works.
+ */
+clone.clonePrototype = function clonePrototype(parent) {
+ if (parent === null)
+ return null;
+
+ var c = function () {};
+ c.prototype = parent;
+ return new c();
+};
+
+// private utility functions
+
+function __objToStr(o) {
+ return Object.prototype.toString.call(o);
+}
+clone.__objToStr = __objToStr;
+
+function __isDate(o) {
+ return typeof o === 'object' && __objToStr(o) === '[object Date]';
+}
+clone.__isDate = __isDate;
+
+function __isArray(o) {
+ return typeof o === 'object' && __objToStr(o) === '[object Array]';
+}
+clone.__isArray = __isArray;
+
+function __isRegExp(o) {
+ return typeof o === 'object' && __objToStr(o) === '[object RegExp]';
+}
+clone.__isRegExp = __isRegExp;
+
+function __getRegExpFlags(re) {
+ var flags = '';
+ if (re.global) flags += 'g';
+ if (re.ignoreCase) flags += 'i';
+ if (re.multiline) flags += 'm';
+ return flags;
+}
+clone.__getRegExpFlags = __getRegExpFlags;
+
+return clone;
+})();
+
+if (typeof module === 'object' && module.exports) {
+ module.exports = clone;
+}
+
+/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(0).Buffer))
+
+/***/ }),
+/* 20 */
+/***/ (function(module, exports, __webpack_require__) {
+
+"use strict";
+
+
+var Writable = __webpack_require__(1).Writable;
+var util = __webpack_require__(4);
+var defaults = __webpack_require__(10);
+
+/**
+ * Writable stream that accepts results in either object or string mode and outputs the text to a supplied html element
+ *
+ * Can show interim results when in objectMode
+ *
+ * @param {Object} options
+ * @param {String|DOMElement} options.outputElement
+ * @param {String} [options.property] what property of the element should the text be set to. Defaults to `value` for ``s and `