text: (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<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
  
  var devices = [];
  $('#result').hide();
  $('#top1').hide();
  $('#top2').hide();
  $('#top3').hide();
  $('#top4').hide();
  $('#top5').hide();
  var values = [];
  
  
  // IOT client
  var client = require('ibmiotf');
  var appClientConfig = {
    org : 'imsxbu',
    id : 'myapp',
    "auth-key" : 'a-imsxbu-fopieq5oa7',
    "auth-token" : 'D@OFs?_mz6l&QmqDy!'
  }
  var appClient = new client.IotfApplication(appClientConfig);
  
  
  appClient.on("connect", function () {
  
    console.log("connected to watson IoT");
    
    appClient.subscribeToDeviceStatus("iotphone");
  });
  appClient.on("deviceStatus", function (deviceType, deviceId, payload, topic) {
  
    console.log("Device status from :: "+deviceType+" : "+deviceId+" with payload : "+payload);
    var mess = JSON.parse(payload);
    if (mess.Action =="Connect"){
      if(!document.getElementById('device_'+deviceId)){
  
        var device = document.createElement("div");
        device.setAttribute("id","device_"+deviceId);
        $(device).addClass('col-md-3');
  
        output.appendChild(device);
  
        var device_title = document.createElement("div");
        device_title.setAttribute("id","device_title_"+deviceId);
        $(device_title).addClass('col-md-12');
        $(device_title).addClass('circle-title');
        device_title.innerHTML=deviceId;
        device.appendChild(device_title);
  
        var device_accel = document.createElement("div");
        device_accel.setAttribute("id","device_accel_"+deviceId);
        $(device_accel).addClass('col-md-12');
        $(device_accel).addClass('circle-accel');
        device.appendChild(device_accel);
      }
      appClient.subscribeToDeviceEvents("iotphone", deviceId);
    }
  
  });
  appClient.on("deviceEvent", function (deviceType, deviceId, eventType, format, payload) {
  
    console.log("Device Event from :: "+deviceType+" : "+deviceId+" of event "+eventType+" with payload : "+payload);
    var value = JSON.parse(payload);
    var x = Math.abs(value.d.ax);
    var y = Math.abs(value.d.ay);
    var z = Math.abs(value.d.az);
    var moy = ( x+ y + z)/3;
    document.getElementById('device_accel_' + deviceId).innerHTML = moy.toFixed(2);
    var index = devices.indexOf(deviceId);
    if(index == -1){
      devices.push(deviceId);
      values.push([deviceId, [moy.toFixed(2)]]);
    
    } else {
      
  
      values[index][1].push(moy.toFixed(2));
    }
  
  });
  function calcMoy(){
    var listMoy =[];
    for (var d in values){
  
      var moy = 0;
      for (var i in values[d][1]){
        moy = moy+parseFloat(values[d][1][i]);
      }
      var l = values[d][1].length;
      moy = parseFloat(moy);
      moy = parseFloat((moy / l).toFixed(2));
      console.log(moy, values[d][0])
      listMoy.push([values[d][0], moy]);
    }
    return listMoy;
    
  }
  
  
  document.getElementById("stopbtn").onclick = function () { 
    console.log("STOP to connect ");
    console.log(values);
    appClient.disconnect();
  
    $('#result').show();
    $('#top1').show();
    $('#top2').show();
    $('#top3').show();
    $('#top4').show();
    $('#top5').show();
  };
  document.getElementById("startbtn").onclick = function () { 
    console.log("START to connect ");
    $('#result').hide();
    $('#top1').hide();
    $('#top2').hide();
    $('#top3').hide();
    $('#top4').hide();
    $('#top5').hide();
    appClient.connect();
  };  
  
  
  
  
  
  
  },{"ibmiotf":8}],2:[function(require,module,exports){
  (function (Buffer){
  (function (global, factory) {
    if (typeof define === 'function' && define.amd) {
      define(['exports', 'module', 'axios', 'bluebird', 'format', 'btoa', '../util/util.js', './BaseClient.js'], factory);
    } else if (typeof exports !== 'undefined' && typeof module !== 'undefined') {
      factory(exports, module, require('axios'), require('bluebird'), require('format'), require('btoa'), require('../util/util.js'), require('./BaseClient.js'));
    } else {
      var mod = {
        exports: {}
      };
      factory(mod.exports, mod, global.xhr, global.Promise, global.format, global.nodeBtoa, global.util, global.BaseClient);
      global.ApplicationClient = mod.exports;
    }
  })(this, function (exports, module, _axios, _bluebird, _format, _btoa, _utilUtilJs, _BaseClientJs) {
    /**
     *****************************************************************************
     Copyright (c) 2014, 2015 IBM Corporation and other Contributors.
     All rights reserved. This program and the accompanying materials
     are made available under the terms of the Eclipse Public License v1.0
     which accompanies this distribution, and is available at
     http://www.eclipse.org/legal/epl-v10.html
     Contributors:
     Tim-Daniel Jacobi - Initial Contribution
     Jeffrey Dare
     *****************************************************************************
     *
     */
    'use strict';
  
    var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
  
    var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
  
    function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  
    function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
  
    function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
  
    var _xhr = _interopRequireDefault(_axios);
  
    var _Promise = _interopRequireDefault(_bluebird);
  
    var _format2 = _interopRequireDefault(_format);
  
    var _nodeBtoa = _interopRequireDefault(_btoa);
  
    var _BaseClient2 = _interopRequireDefault(_BaseClientJs);
  
    var btoa = btoa || _nodeBtoa['default']; // if browser btoa is available use it otherwise use node module
  
    var QUICKSTART_ORG_ID = "quickstart";
  
    var DEVICE_EVT_RE = /^iot-2\/type\/(.+)\/id\/(.+)\/evt\/(.+)\/fmt\/(.+)$/;
    var DEVICE_CMD_RE = /^iot-2\/type\/(.+)\/id\/(.+)\/cmd\/(.+)\/fmt\/(.+)$/;
    var DEVICE_MON_RE = /^iot-2\/type\/(.+)\/id\/(.+)\/mon$/;
    var APP_MON_RE = /^iot-2\/app\/(.+)\/mon$/;
  
    var ApplicationClient = (function (_BaseClient) {
      _inherits(ApplicationClient, _BaseClient);
  
      function ApplicationClient(config) {
        _classCallCheck(this, ApplicationClient);
  
        _get(Object.getPrototypeOf(ApplicationClient.prototype), 'constructor', this).call(this, config);
  
        if (config.org !== QUICKSTART_ORG_ID) {
          if (config.useLtpa) {
            this.useLtpa = true;
          } else {
            if (!(0, _utilUtilJs.isDefined)(config['auth-key'])) {
              throw new Error('[ApplicationClient:constructor] config must contain auth-key');
            } else if (!(0, _utilUtilJs.isString)(config['auth-key'])) {
              throw new Error('[ApplicationClient:constructor] auth-key must be a string');
            }
  
            this.mqttConfig.username = config['auth-key'];
          }
        }
  
        this.org = config.org;
        this.apiKey = config['auth-key'];
        this.apiToken = config['auth-token'];
        //support for shared subscription
        this.shared = (config['type'] + '').toLowerCase() === "shared" || false;
        if (this.shared) {
          this.mqttConfig.clientId = "A:" + config.org + ":" + config.id;
        } else {
          this.mqttConfig.clientId = "a:" + config.org + ":" + config.id;
        }
        this.subscriptions = [];
  
        this.httpServer = "";
        // Parse http-server & domain property. http-server takes precedence over domain
        if ((0, _utilUtilJs.isDefined)(config['http-server'])) {
          if (!(0, _utilUtilJs.isString)(config['http-server'])) {
            throw new Error('[BaseClient:constructor] http-server must be a string, ' + 'see Bluemix Watson IoT service credentials for more information');
          }
          this.httpServer = config['http-server'];
        } else if ((0, _utilUtilJs.isDefined)(config.domain)) {
          if (!(0, _utilUtilJs.isString)(config.domain)) {
            throw new Error('[BaseClient:constructor] domain must be a string');
          }
          this.httpServer = config.org + "." + config.domain;
          this.domainName = config.domain;
        } else {
          this.httpServer = config.org + ".internetofthings.ibmcloud.com";
        }
  
        this.withProxy = false;
        if ((0, _utilUtilJs.isDefined)(config['with-proxy'])) {
          this.withProxy = config['with-proxy'];
        }
  
        this.log.info("[ApplicationClient:constructor] ApplicationClient initialized for organization : " + config.org);
      }
  
      _createClass(ApplicationClient, [{
        key: 'connect',
        value: function connect(QoS) {
          var _this = this;
  
          QoS = QoS || 0;
          _get(Object.getPrototypeOf(ApplicationClient.prototype), 'connect', this).call(this);
  
          this.mqtt.on('connect', function () {
            _this.log.info("[ApplicationClient:connnect] ApplicationClient Connected");
            _this.isConnected = true;
  
            if (_this.retryCount === 0) {
              _this.emit('connect');
            } else {
              _this.emit('reconnect');
            }
  
            //reset the counter to 0 incase of reconnection
            _this.retryCount = 0;
  
            try {
              for (var i = 0, l = _this.subscriptions.length; i < l; i++) {
                _this.mqtt.subscribe(_this.subscriptions[i], { qos: parseInt(QoS) });
              }
            } catch (err) {
              _this.log.error("[ApplicationClient:connect] Error while trying to subscribe : " + err);
            }
          });
  
          this.mqtt.on('message', function (topic, payload) {
            _this.log.trace("[ApplicationClient:onMessage] mqtt: ", topic, payload.toString());
  
            // For each type of registered callback, check the incoming topic against a Regexp.
            // If matches, forward the payload and various fields from the topic (extracted using groups in the regexp)
  
            var match = DEVICE_EVT_RE.exec(topic);
            if (match) {
              _this.emit('deviceEvent', match[1], match[2], match[3], match[4], payload, topic);
  
              return;
            }
  
            var match = DEVICE_CMD_RE.exec(topic);
            if (match) {
              _this.emit('deviceCommand', match[1], match[2], match[3], match[4], payload, topic);
  
              return;
            }
  
            var match = DEVICE_MON_RE.exec(topic);
            if (match) {
              _this.emit('deviceStatus', match[1], match[2], payload, topic);
  
              return;
            }
  
            var match = APP_MON_RE.exec(topic);
            if (match) {
              _this.emit('appStatus', match[1], payload, topic);
              return;
            }
  
            // catch all which logs the receipt of an unexpected message
            _this.log.warn("[ApplicationClient:onMessage] Message received on unexpected topic" + ", " + topic + ", " + payload);
          });
        }
      }, {
        key: 'subscribe',
        value: function subscribe(topic, QoS) {
          QoS = QoS || 0;
          if (!this.isConnected) {
            this.log.error("[ApplicationClient:subscribe] Client is not connected");
            //throw new Error("Client is not connected");
            //instead of throwing error, will emit 'error' event.
            this.emit('error', "[ApplicationClient:subscribe] Client is not connected");
          }
  
          this.log.debug("[ApplicationClient:subscribe] Subscribing to topic " + topic + " with QoS " + QoS);
          this.subscriptions.push(topic);
  
          this.mqtt.subscribe(topic, { qos: parseInt(QoS) });
          this.log.debug("[ApplicationClient:subscribe] Subscribed to topic " + topic + " with QoS " + QoS);
        }
      }, {
        key: 'unsubscribe',
        value: function unsubscribe(topic) {
          if (!this.isConnected) {
            this.log.error("[ApplicationClient:unsubscribe] Client is not connected");
            // throw new Error("Client is not connected");
            //instead of throwing error, will emit 'error' event.
            this.emit('error', "[ApplicationClient:unsubscribe] Client is not connected");
          }
  
          this.log.debug("[ApplicationClient:unsubscribe] Unsubscribe: " + topic);
          var i = this.subscriptions.indexOf(topic);
          if (i != -1) {
            this.subscriptions.splice(i, 1);
          }
  
          this.mqtt.unsubscribe(topic);
          this.log.debug("[ApplicationClient:unsubscribe] Unsubscribed to: " + topic);
        }
      }, {
        key: 'publish',
        value: function publish(topic, msg, QoS, callback) {
          QoS = QoS || 0;
          if (!this.isConnected) {
            this.log.error("[ApplicationClient:publish] Client is not connected");
            // throw new Error("Client is not connected");
            //instead of throwing error, will emit 'error' event.
            this.emit('error', "[ApplicationClient:publish] Client is not connected");
          }
  
          if ((typeof msg === 'object' || typeof msg === 'boolean' || typeof msg === 'number') && !Buffer.isBuffer(msg)) {
            // mqtt library does not support sending JSON/Boolean/Number data. So stringifying it.
            // All JSON object, array will be encoded.
            msg = JSON.stringify(msg);
          }
          this.log.debug("[ApplicationClient:publish] Publish: " + topic + ", " + msg + ", QoS : " + QoS);
          this.mqtt.publish(topic, msg, { qos: parseInt(QoS) }, callback);
        }
      }, {
        key: 'subscribeToDeviceEvents',
        value: function subscribeToDeviceEvents(type, id, event, format, qos) {
          type = type || '+';
          id = id || '+';
          event = event || '+';
          format = format || '+';
          qos = qos || 0;
  
          var topic = "iot-2/type/" + type + "/id/" + id + "/evt/" + event + "/fmt/" + format;
          this.log.debug("[ApplicationClient:subscribeToDeviceEvents] Calling subscribe with QoS " + qos);
          this.subscribe(topic, qos);
          return this;
        }
      }, {
        key: 'unsubscribeToDeviceEvents',
        value: function unsubscribeToDeviceEvents(type, id, event, format) {
          type = type || '+';
          id = id || '+';
          event = event || '+';
          format = format || '+';
  
          var topic = "iot-2/type/" + type + "/id/" + id + "/evt/" + event + "/fmt/" + format;
          this.unsubscribe(topic);
          return this;
        }
      }, {
        key: 'subscribeToDeviceCommands',
        value: function subscribeToDeviceCommands(type, id, command, format, qos) {
          type = type || '+';
          id = id || '+';
          command = command || '+';
          format = format || '+';
          qos = qos || 0;
  
          var topic = "iot-2/type/" + type + "/id/" + id + "/cmd/" + command + "/fmt/" + format;
          this.log.debug("[ApplicationClient:subscribeToDeviceCommands] Calling subscribe with QoS " + qos);
          this.subscribe(topic, qos);
          return this;
        }
      }, {
        key: 'unsubscribeToDeviceCommands',
        value: function unsubscribeToDeviceCommands(type, id, command, format) {
          type = type || '+';
          id = id || '+';
          command = command || '+';
          format = format || '+';
  
          var topic = "iot-2/type/" + type + "/id/" + id + "/cmd/" + command + "/fmt/" + format;
          this.unsubscribe(topic);
          return this;
        }
      }, {
        key: 'subscribeToDeviceStatus',
        value: function subscribeToDeviceStatus(type, id, qos) {
          type = type || '+';
          id = id || '+';
          qos = qos || 0;
  
          var topic = "iot-2/type/" + type + "/id/" + id + "/mon";
          this.log.debug("[ApplicationClient:subscribeToDeviceStatus] Calling subscribe with QoS " + qos);
          this.subscribe(topic, qos);
          return this;
        }
      }, {
        key: 'subscribeToAppStatus',
        value: function subscribeToAppStatus(id, qos) {
          id = id || '+';
          qos = qos || 0;
  
          var topic = "iot-2/app/" + id + "/mon";
          this.log.debug("[ApplicationClient:subscribeToAppStatus] Calling subscribe with QoS " + qos);
          this.subscribe(topic, qos);
          return this;
        }
      }, {
        key: 'unsubscribeToDeviceStatus',
        value: function unsubscribeToDeviceStatus(type, id) {
          type = type || '+';
          id = id || '+';
  
          var topic = "iot-2/type/" + type + "/id/" + id + "/mon";
          this.unsubscribe(topic);
          return this;
        }
      }, {
        key: 'unsubscribeToAppStatus',
        value: function unsubscribeToAppStatus(id) {
          id = id || '+';
  
          var topic = "iot-2/app/" + id + "/mon";
          this.unsubscribe(topic);
  
          return this;
        }
      }, {
        key: 'publishDeviceEvent',
        value: function publishDeviceEvent(type, id, event, format, data, qos, callback) {
          qos = qos || 0;
          if (!(0, _utilUtilJs.isDefined)(type) || !(0, _utilUtilJs.isDefined)(id) || !(0, _utilUtilJs.isDefined)(event) || !(0, _utilUtilJs.isDefined)(format)) {
            this.log.error("[ApplicationClient:publishDeviceEvent] Required params for publishDeviceEvent not present");
            //instead of throwing error, will emit 'error' event.
            this.emit('error', "[ApplicationClient:publishDeviceEvent] Required params for publishDeviceEvent not present");
            return;
          }
          var topic = "iot-2/type/" + type + "/id/" + id + "/evt/" + event + "/fmt/" + format;
          this.publish(topic, data, qos, callback);
          return this;
        }
      }, {
        key: 'publishDeviceCommand',
        value: function publishDeviceCommand(type, id, command, format, data, qos, callback) {
          qos = qos || 0;
          if (!(0, _utilUtilJs.isDefined)(type) || !(0, _utilUtilJs.isDefined)(id) || !(0, _utilUtilJs.isDefined)(command) || !(0, _utilUtilJs.isDefined)(format)) {
            this.log.error("[ApplicationClient:publishToDeviceCommand] Required params for publishDeviceCommand not present");
            //instead of throwing error, will emit 'error' event.
            this.emit('error', "[ApplicationClient:subscribeToDeviceCommand] Required params for publishDeviceCommand not present");
            return;
          }
          var topic = "iot-2/type/" + type + "/id/" + id + "/cmd/" + command + "/fmt/" + format;
          this.publish(topic, data, qos, callback);
          return this;
        }
      }, {
        key: 'callApi',
        value: function callApi(method, expectedHttpCode, expectJsonContent, paths, body, params) {
          var _this2 = this;
  
          return new _Promise['default'](function (resolve, reject) {
            // const API_HOST = "https://%s.internetofthings.ibmcloud.com/api/v0002";
            var uri = _this2.withProxy ? "/api/v0002" : (0, _format2['default'])("https://%s/api/v0002", _this2.httpServer);
  
            if (Array.isArray(paths)) {
              for (var i = 0, l = paths.length; i < l; i++) {
                uri += '/' + paths[i];
              }
            }
  
            var xhrConfig = {
              url: uri,
              method: method,
              headers: {
                'Content-Type': 'application/json'
              }
            };
  
            if (_this2.useLtpa) {
              xhrConfig.withCredentials = true;
            } else {
              xhrConfig.headers['Authorization'] = 'Basic ' + btoa(_this2.apiKey + ':' + _this2.apiToken);
            }
  
            if (body) {
              xhrConfig.data = body;
            }
  
            if (params) {
              xhrConfig.params = params;
            }
  
            function transformResponse(response) {
              if (response.status === expectedHttpCode) {
                if (expectJsonContent && !(typeof response.data === 'object')) {
                  try {
                    resolve(JSON.parse(response.data));
                  } catch (e) {
                    reject(e);
                  }
                } else {
                  resolve(response.data);
                }
              } else {
                reject(new Error(method + " " + uri + ": Expected HTTP " + expectedHttpCode + " from server but got HTTP " + response.status + ". Error Body: " + data));
              }
            }
            _this2.log.debug("[ApplicationClient:transformResponse] " + xhrConfig);
            (0, _xhr['default'])(xhrConfig).then(transformResponse, reject);
          });
        }
      }, {
        key: 'getOrganizationDetails',
        value: function getOrganizationDetails() {
          this.log.debug("[ApplicationClient] getOrganizationDetails()");
          return this.callApi('GET', 200, true, null, null);
        }
      }, {
        key: 'listAllDevicesOfType',
        value: function listAllDevicesOfType(type) {
          this.log.debug("[ApplicationClient] listAllDevicesOfType(" + type + ")");
          return this.callApi('GET', 200, true, ['device', 'types', type, 'devices'], null);
        }
      }, {
        key: 'deleteDeviceType',
        value: function deleteDeviceType(type) {
          this.log.debug("[ApplicationClient] deleteDeviceType(" + type + ")");
          return this.callApi('DELETE', 204, false, ['device', 'types', type], null);
        }
      }, {
        key: 'getDeviceType',
        value: function getDeviceType(type) {
          this.log.debug("[ApplicationClient] getDeviceType(" + type + ")");
          return this.callApi('GET', 200, true, ['device', 'types', type], null);
        }
      }, {
        key: 'getAllDeviceTypes',
        value: function getAllDeviceTypes() {
          this.log.debug("[ApplicationClient] getAllDeviceTypes()");
          return this.callApi('GET', 200, true, ['device', 'types'], null);
        }
      }, {
        key: 'updateDeviceType',
        value: function updateDeviceType(type, description, deviceInfo, metadata) {
          this.log.debug("[ApplicationClient] updateDeviceType(" + type + ", " + description + ", " + deviceInfo + ", " + metadata + ")");
          var body = {
            deviceInfo: deviceInfo,
            description: description,
            metadata: metadata
          };
  
          return this.callApi('PUT', 200, true, ['device', 'types', type], JSON.stringify(body));
        }
      }, {
        key: 'registerDeviceType',
        value: function registerDeviceType(typeId, description, deviceInfo, metadata, classId) {
          this.log.debug("[ApplicationClient] registerDeviceType(" + typeId + ", " + description + ", " + deviceInfo + ", " + metadata + ", " + classId + ")");
          // TODO: field validation
          classId = classId || "Device";
          var body = {
            id: typeId,
            classId: classId,
            deviceInfo: deviceInfo,
            description: description,
            metadata: metadata
          };
  
          return this.callApi('POST', 201, true, ['device', 'types'], JSON.stringify(body));
        }
      }, {
        key: 'registerDevice',
        value: function registerDevice(type, deviceId, authToken, deviceInfo, location, metadata) {
          this.log.debug("[ApplicationClient] registerDevice(" + type + ", " + deviceId + ", " + deviceInfo + ", " + location + ", " + metadata + ")");
          // TODO: field validation
          var body = {
            deviceId: deviceId,
            authToken: authToken,
            deviceInfo: deviceInfo,
            location: location,
            metadata: metadata
          };
  
          return this.callApi('POST', 201, true, ['device', 'types', type, 'devices'], JSON.stringify(body));
        }
      }, {
        key: 'unregisterDevice',
        value: function unregisterDevice(type, deviceId) {
          this.log.debug("[ApplicationClient] unregisterDevice(" + type + ", " + deviceId + ")");
          return this.callApi('DELETE', 204, false, ['device', 'types', type, 'devices', deviceId], null);
        }
      }, {
        key: 'updateDevice',
        value: function updateDevice(type, deviceId, deviceInfo, status, metadata, extensions) {
          this.log.debug("[ApplicationClient] updateDevice(" + type + ", " + deviceId + ", " + deviceInfo + ", " + status + ", " + metadata + ")");
          var body = {
            deviceInfo: deviceInfo,
            status: status,
            metadata: metadata,
            extensions: extensions
          };
  
          return this.callApi('PUT', 200, true, ['device', 'types', type, 'devices', deviceId], JSON.stringify(body));
        }
      }, {
        key: 'getDevice',
        value: function getDevice(type, deviceId) {
          this.log.debug("[ApplicationClient] getDevice(" + type + ", " + deviceId + ")");
          return this.callApi('GET', 200, true, ['device', 'types', type, 'devices', deviceId], null);
        }
      }, {
        key: 'getDeviceLocation',
        value: function getDeviceLocation(type, deviceId) {
          this.log.debug("[ApplicationClient] getDeviceLocation(" + type + ", " + deviceId + ")");
          return this.callApi('GET', 200, true, ['device', 'types', type, 'devices', deviceId, 'location'], null);
        }
      }, {
        key: 'updateDeviceLocation',
        value: function updateDeviceLocation(type, deviceId, location) {
          this.log.debug("[ApplicationClient] updateDeviceLocation(" + type + ", " + deviceId + ", " + location + ")");
  
          return this.callApi('PUT', 200, true, ['device', 'types', type, 'devices', deviceId, 'location'], JSON.stringify(location));
        }
      }, {
        key: 'getDeviceManagementInformation',
        value: function getDeviceManagementInformation(type, deviceId) {
          this.log.debug("[ApplicationClient] getDeviceManagementInformation(" + type + ", " + deviceId + ")");
          return this.callApi('GET', 200, true, ['device', 'types', type, 'devices', deviceId, 'mgmt'], null);
        }
      }, {
        key: 'getAllDiagnosticLogs',
        value: function getAllDiagnosticLogs(type, deviceId) {
          this.log.debug("[ApplicationClient] getAllDiagnosticLogs(" + type + ", " + deviceId + ")");
          return this.callApi('GET', 200, true, ['device', 'types', type, 'devices', deviceId, 'diag', 'logs'], null);
        }
      }, {
        key: 'clearAllDiagnosticLogs',
        value: function clearAllDiagnosticLogs(type, deviceId) {
          this.log.debug("[ApplicationClient] clearAllDiagnosticLogs(" + type + ", " + deviceId + ")");
          return this.callApi('DELETE', 204, false, ['device', 'types', type, 'devices', deviceId, 'diag', 'logs'], null);
        }
      }, {
        key: 'addDeviceDiagLogs',
        value: function addDeviceDiagLogs(type, deviceId, log) {
          this.log.debug("[ApplicationClient] addDeviceDiagLogs(" + type + ", " + deviceId + ", " + log + ")");
          return this.callApi('POST', 201, false, ['device', 'types', type, 'devices', deviceId, 'diag', 'logs'], JSON.stringify(log));
        }
      }, {
        key: 'getDiagnosticLog',
        value: function getDiagnosticLog(type, deviceId, logId) {
          this.log.debug("[ApplicationClient] getAllDiagnosticLogs(" + type + ", " + deviceId + ", " + logId + ")");
          return this.callApi('GET', 200, true, ['device', 'types', type, 'devices', deviceId, 'diag', 'logs', logId], null);
        }
      }, {
        key: 'deleteDiagnosticLog',
        value: function deleteDiagnosticLog(type, deviceId, logId) {
          this.log.debug("[ApplicationClient] deleteDiagnosticLog(" + type + ", " + deviceId + ", " + logId + ")");
          return this.callApi('DELETE', 204, false, ['device', 'types', type, 'devices', deviceId, 'diag', 'logs', logId], null);
        }
      }, {
        key: 'getDeviceErrorCodes',
        value: function getDeviceErrorCodes(type, deviceId) {
          this.log.debug("[ApplicationClient] getDeviceErrorCodes(" + type + ", " + deviceId + ")");
          return this.callApi('GET', 200, true, ['device', 'types', type, 'devices', deviceId, 'diag', 'errorCodes'], null);
        }
      }, {
        key: 'clearDeviceErrorCodes',
        value: function clearDeviceErrorCodes(type, deviceId) {
          this.log.debug("[ApplicationClient] clearDeviceErrorCodes(" + type + ", " + deviceId + ")");
          return this.callApi('DELETE', 204, false, ['device', 'types', type, 'devices', deviceId, 'diag', 'errorCodes'], null);
        }
      }, {
        key: 'addErrorCode',
        value: function addErrorCode(type, deviceId, log) {
          this.log.debug("[ApplicationClient] addErrorCode(" + type + ", " + deviceId + ", " + log + ")");
          return this.callApi('POST', 201, false, ['device', 'types', type, 'devices', deviceId, 'diag', 'errorCodes'], JSON.stringify(log));
        }
      }, {
        key: 'getDeviceConnectionLogs',
        value: function getDeviceConnectionLogs(typeId, deviceId) {
          this.log.debug("[ApplicationClient] getDeviceConnectionLogs(" + typeId + ", " + deviceId + ")");
          var params = {
            typeId: typeId,
            deviceId: deviceId
          };
          return this.callApi('GET', 200, true, ['logs', 'connection'], null, params);
        }
      }, {
        key: 'getServiceStatus',
        value: function getServiceStatus() {
          this.log.debug("[ApplicationClient] getServiceStatus()");
          return this.callApi('GET', 200, true, ['service-status'], null);
        }
      }, {
        key: 'getAllDeviceManagementRequests',
        value: function getAllDeviceManagementRequests() {
          this.log.debug("[ApplicationClient] getAllDeviceManagementRequests()");
          return this.callApi('GET', 200, true, ['mgmt', 'requests'], null);
        }
      }, {
        key: 'initiateDeviceManagementRequest',
        value: function initiateDeviceManagementRequest(action, parameters, devices) {
          this.log.debug("[ApplicationClient] initiateDeviceManagementRequest(" + action + ", " + parameters + ", " + devices + ")");
          var body = {
            action: action,
            parameters: parameters,
            devices: devices
          };
          return this.callApi('POST', 202, true, ['mgmt', 'requests'], JSON.stringify(body));
        }
      }, {
        key: 'getDeviceManagementRequest',
        value: function getDeviceManagementRequest(requestId) {
          this.log.debug("[ApplicationClient] getDeviceManagementRequest(" + requestId + ")");
          return this.callApi('GET', 200, true, ['mgmt', 'requests', requestId], null);
        }
      }, {
        key: 'deleteDeviceManagementRequest',
        value: function deleteDeviceManagementRequest(requestId) {
          this.log.debug("[ApplicationClient] deleteDeviceManagementRequest(" + requestId + ")");
          return this.callApi('DELETE', 204, false, ['mgmt', 'requests', requestId], null);
        }
      }, {
        key: 'getDeviceManagementRequestStatus',
        value: function getDeviceManagementRequestStatus(requestId) {
          this.log.debug("[ApplicationClient] getDeviceManagementRequestStatus(" + requestId + ")");
          return this.callApi('GET', 200, true, ['mgmt', 'requests', requestId, 'deviceStatus'], null);
        }
      }, {
        key: 'getDeviceManagementRequestStatusByDevice',
        value: function getDeviceManagementRequestStatusByDevice(requestId, typeId, deviceId) {
          this.log.debug("[ApplicationClient] getDeviceManagementRequestStatusByDevice(" + requestId + ", " + typeId + ", " + deviceId + ")");
          return this.callApi('GET', 200, true, ['mgmt', 'requests', requestId, 'deviceStatus', typeId, deviceId], null);
        }
  
        //Usage Management
      }, {
        key: 'getActiveDevices',
        value: function getActiveDevices(start, end, detail) {
          this.log.debug("[ApplicationClient] getActiveDevices(" + start + ", " + end + ")");
          detail = detail | false;
          var params = {
            start: start,
            end: end,
            detail: detail
          };
          return this.callApi('GET', 200, true, ['usage', 'active-devices'], null, params);
        }
      }, {
        key: 'getHistoricalDataUsage',
        value: function getHistoricalDataUsage(start, end, detail) {
          this.log.debug("[ApplicationClient] getHistoricalDataUsage(" + start + ", " + end + ")");
          detail = detail | false;
          var params = {
            start: start,
            end: end,
            detail: detail
          };
          return this.callApi('GET', 200, true, ['usage', 'historical-data'], null, params);
        }
      }, {
        key: 'getDataUsage',
        value: function getDataUsage(start, end, detail) {
          this.log.debug("[ApplicationClient] getDataUsage(" + start + ", " + end + ")");
          detail = detail | false;
          var params = {
            start: start,
            end: end,
            detail: detail
          };
          return this.callApi('GET', 200, true, ['usage', 'data-traffic'], null, params);
        }
  
        //Historian
      }, {
        key: 'getAllHistoricalEvents',
        value: function getAllHistoricalEvents(evtType, start, end) {
          this.log.debug("[ApplicationClient] getAllHistoricalEvents(" + evtType + ", " + start + ", " + end + ")");
          var params = {
            start: start,
            end: end,
            evt_type: evtType
          };
          return this.callApi('GET', 200, true, ['historian'], null, params);
        }
      }, {
        key: 'getAllHistoricalEventsByDeviceType',
        value: function getAllHistoricalEventsByDeviceType(evtType, start, end, typeId) {
          this.log.debug("[ApplicationClient] getAllHistoricalEvents(" + evtType + ", " + start + ", " + end + ")");
          var params = {
            start: start,
            end: end,
            evt_type: evtType
          };
          return this.callApi('GET', 200, true, ['historian', 'types', typeId], null, params);
        }
      }, {
        key: 'getAllHistoricalEventsByDeviceId',
        value: function getAllHistoricalEventsByDeviceId(evtType, start, end, typeId, deviceId) {
          this.log.debug("[ApplicationClient] getAllHistoricalEvents(" + evtType + ", " + start + ", " + end + ")");
          var params = {
            start: start,
            end: end,
            evt_type: evtType
          };
          return this.callApi('GET', 200, true, ['historian', 'types', typeId, 'devices', deviceId], null, params);
        }
      }, {
        key: 'publishHTTPS',
        value: function publishHTTPS(deviceType, deviceId, eventType, eventFormat, payload) {
          var _this3 = this;
  
          this.log.debug("[ApplicationClient:publishHTTPS] Publishing event of Type: " + eventType + " with payload : " + payload);
          return new _Promise['default'](function (resolve, reject) {
  
            var uri = (0, _format2['default'])("https://%s/api/v0002/application/types/%s/devices/%s/events/%s", _this3.mqttServer, deviceType, deviceId, eventType);
  
            var xhrConfig = {
              url: uri,
              method: 'POST',
              data: payload,
              headers: {}
            };
  
            if (eventFormat === 'json') {
              xhrConfig.headers['Content-Type'] = 'application/json';
            } else if (eventFormat === 'xml') {
              xhrConfig.headers['Content-Type'] = 'application/xml';
            }
  
            if (_this3.org !== QUICKSTART_ORG_ID) {
              xhrConfig.headers['Authorization'] = 'Basic ' + btoa(_this3.apiKey + ':' + _this3.apiToken);
            }
            _this3.log.debug("[ApplicationClient:publishHTTPS]" + xhrConfig);
  
            (0, _xhr['default'])(xhrConfig).then(resolve, reject);
          });
        }
  
        //event cache
      }, {
        key: 'getLastEvents',
        value: function getLastEvents(type, id) {
          this.log.debug("[ApplicationClient] getLastEvents() - event cache");
          return this.callApi('GET', 200, true, ["device", "types", type, "devices", id, "events"], null);
        }
      }, {
        key: 'getLastEventsByEventType',
        value: function getLastEventsByEventType(type, id, eventType) {
          this.log.debug("[ApplicationClient] getLastEventsByEventType() - event cache");
          return this.callApi('GET', 200, true, ["device", "types", type, "devices", id, "events", eventType], null);
        }
  
        //bulk apis
      }, {
        key: 'getAllDevices',
        value: function getAllDevices(params) {
          this.log.debug("[ApplicationClient] getAllDevices() - BULK");
          return this.callApi('GET', 200, true, ["bulk", "devices"], null, params);
        }
  
        /**
         * Register multiple new devices, each request can contain a maximum of 512KB.
         * The response body will contain the generated authentication tokens for all devices.
         * The caller of the method must make sure to record these tokens when processing
         * the response. The IBM Watson IoT Platform will not be able to retrieve lost authentication tokens
         *
         * @param arryOfDevicesToBeAdded Array of JSON devices to be added. Refer to
         * <a href="https://docs.internetofthings.ibmcloud.com/swagger/v0002.html#!/Bulk_Operations/post_bulk_devices_add">link</a>
         * for more information about the schema to be used
         */
      }, {
        key: 'registerMultipleDevices',
        value: function registerMultipleDevices(arryOfDevicesToBeAdded) {
          this.log.debug("[ApplicationClient] arryOfDevicesToBeAdded() - BULK");
          return this.callApi('POST', 201, true, ["bulk", "devices", "add"], JSON.stringify(arryOfDevicesToBeAdded));
        }
  
        /**
        * Delete multiple devices, each request can contain a maximum of 512Kb
        *
        * @param arryOfDevicesToBeDeleted Array of JSON devices to be deleted. Refer to
        * <a href="https://docs.internetofthings.ibmcloud.com/swagger/v0002.html#!/Bulk_Operations/post_bulk_devices_remove">link</a>
        * for more information about the schema to be used.
        */
      }, {
        key: 'deleteMultipleDevices',
        value: function deleteMultipleDevices(arryOfDevicesToBeDeleted) {
  
          this.log.debug("[ApplicationClient] deleteMultipleDevices() - BULK");
          return this.callApi('POST', 201, true, ["bulk", "devices", "remove"], JSON.stringify(arryOfDevicesToBeDeleted));
        }
      }]);
  
      return ApplicationClient;
    })(_BaseClient2['default']);
  
    module.exports = ApplicationClient;
  });
  }).call(this,{"isBuffer":require("../../../../../../../../../usr/local/lib/node_modules/browserify/node_modules/insert-module-globals/node_modules/is-buffer/index.js")})
  },{"../../../../../../../../../usr/local/lib/node_modules/browserify/node_modules/insert-module-globals/node_modules/is-buffer/index.js":102,"../util/util.js":9,"./BaseClient.js":3,"axios":10,"bluebird":25,"btoa":26,"format":27}],3:[function(require,module,exports){
  (function (__dirname){
  (function (global, factory) {
    if (typeof define === 'function' && define.amd) {
      define(['exports', 'module', 'events', 'mqtt', 'loglevel', '../util/util.js'], factory);
    } else if (typeof exports !== 'undefined' && typeof module !== 'undefined') {
      factory(exports, module, require('events'), require('mqtt'), require('loglevel'), require('../util/util.js'));
    } else {
      var mod = {
        exports: {}
      };
      factory(mod.exports, mod, global.events, global.mqtt, global.log, global.util);
      global.BaseClient = mod.exports;
    }
  })(this, function (exports, module, _events, _mqtt, _loglevel, _utilUtilJs) {
    /**
     *****************************************************************************
     Copyright (c) 2014, 2015 IBM Corporation and other Contributors.
     All rights reserved. This program and the accompanying materials
     are made available under the terms of the Eclipse Public License v1.0
     which accompanies this distribution, and is available at
     http://www.eclipse.org/legal/epl-v10.html
     Contributors:
     Tim-Daniel Jacobi - Initial Contribution
     Jeffrey Dare
     Lokesh Haralakatta - Added Client Side Certificates Support
     *****************************************************************************
     *
     */
    'use strict';
  
    var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
  
    var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
  
    function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  
    function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
  
    function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
  
    var _events2 = _interopRequireDefault(_events);
  
    var _mqtt2 = _interopRequireDefault(_mqtt);
  
    var _log = _interopRequireDefault(_loglevel);
  
    var QUICKSTART_ORG_ID = "quickstart";
  
    var BaseClient = (function (_events$EventEmitter) {
      _inherits(BaseClient, _events$EventEmitter);
  
      function BaseClient(config) {
        _classCallCheck(this, BaseClient);
  
        _get(Object.getPrototypeOf(BaseClient.prototype), 'constructor', this).call(this);
        this.log = _log['default'];
        this.log.setDefaultLevel("warn");
        //removed as now we have support of domain name in config.
        /*    this.staging = false;
            if(process.env.STAGING === '1') {
              this.staging = true;
            }*/
        if (!config) {
          throw new Error('[BaseClient:constructor] Client instantiated with missing properties');
        }
  
        if (!(0, _utilUtilJs.isDefined)(config.org)) {
          throw new Error('[BaseClient:constructor] config must contain org');
        } else if (!(0, _utilUtilJs.isString)(config.org)) {
          throw new Error('[BaseClient:constructor] org must be a string');
        }
  
        if (!(0, _utilUtilJs.isDefined)(config.id)) {
          throw new Error('[BaseClient:constructor] config must contain id');
        } else if (!(0, _utilUtilJs.isString)(config.id)) {
          throw new Error('[BaseClient:constructor] id must be a string');
        }
  
        this.domainName = "internetofthings.ibmcloud.com";
        this.mqttServer = "";
        this.enforceWs = false;
        // Parse mqtt-server & domain property. mqtt-server takes precedence over domain
        if ((0, _utilUtilJs.isDefined)(config['mqtt-server'])) {
          if (!(0, _utilUtilJs.isString)(config['mqtt-server'])) {
            throw new Error('[BaseClient:constructor] mqtt-server must be a string');
          }
          this.mqttServer = config['mqtt-server'];
        } else if ((0, _utilUtilJs.isDefined)(config['domain'])) {
          if (!(0, _utilUtilJs.isString)(config['domain'])) {
            throw new Error('[BaseClient:constructor] domain must be a string');
          }
          this.mqttServer = config.org + ".messaging." + config.domain;
          this.domainName = config.domain;
          config['mqtt-server'] = this.mqttServer;
        } else {
          this.mqttServer = config.org + ".messaging.internetofthings.ibmcloud.com";
          config['mqtt-server'] = this.mqttServer;
        }
  
        //property to enforce Websockets even in Node
  
        // CAUTION : This is deprecated and may be removed in future
  
        // Parse enforce-ws property
  
        if ((0, _utilUtilJs.isDefined)(config['enforce-ws'])) {
  
          if (!(0, _utilUtilJs.isBoolean)(config['enforce-ws'])) {
  
            throw new Error('enforce-ws must be a boolean');
          }
  
          this.enforceWs = config['enforce-ws'];
        }
  
        if (config.org === QUICKSTART_ORG_ID) {
          if ((0, _utilUtilJs.isNode)() && !this.enforceWs) {
  
            this.host = "tcp://quickstart.messaging.internetofthings.ibmcloud.com:1883";
          } else {
  
            this.host = "ws://quickstart.messaging.internetofthings.ibmcloud.com:1883";
          }
          this.isQuickstart = true;
          this.mqttConfig = {};
        } else {
  
          if (!(0, _utilUtilJs.isDefined)(config['auth-token'])) {
            throw new Error('[BaseClient:constructor] config must contain auth-token');
          } else if (!(0, _utilUtilJs.isString)(config['auth-token'])) {
            throw new Error('[BaseClient:constructor] auth-token must be a string');
          }
  
          if ((0, _utilUtilJs.isNode)() && !this.enforceWs) {
  
            this.host = "ssl://" + this.mqttServer + ":8883";
          } else {
            this.host = "wss://" + this.mqttServer + ":8883";
          }
  
          this.isQuickstart = false;
          this.mqttConfig = (0, _utilUtilJs.initializeMqttConfig)(config);
  
          if ((0, _utilUtilJs.isNode)()) {
            this.mqttConfig.caPaths = [__dirname + '/IoTFoundation.pem'];
          }
        }
        this.mqttConfig.connectTimeout = 90 * 1000;
        this.retryCount = 0;
        this.isConnected = false;
      }
  
      _createClass(BaseClient, [{
        key: 'setKeepAliveInterval',
        value: function setKeepAliveInterval(keepAliveInterval) {
          this.mqttConfig.keepalive = keepAliveInterval || 60;
          this.log.debug("[BaseClient:setKeepAliveInterval] Connection Keep Alive Interval value set to " + this.mqttConfig.keepalive + " Seconds");
        }
      }, {
        key: 'setCleanSession',
        value: function setCleanSession(cleanSession) {
          if (!(0, _utilUtilJs.isBoolean)(cleanSession) && cleanSession !== 'true' && cleanSession !== 'false') {
            this.log.debug("[BaseClient:setCleanSession] Value given for cleanSession is " + cleanSession + " , is not a Boolean, setting to true");
            cleanSession = true;
          }
          this.mqttConfig.clean = cleanSession;
          this.log.debug("[BaseClient:setCleanSession] Connection Clean Session value set to " + this.mqttConfig.clean);
        }
      }, {
        key: 'connect',
        value: function connect() {
          var _this = this;
  
          this.log.info("[BaseClient:connect] Connecting to IoTF with host : " + this.host);
  
          this.mqtt = _mqtt2['default'].connect(this.host, this.mqttConfig);
  
          this.mqtt.on('offline', function () {
            _this.log.warn("[BaseClient:connect] Iotfclient is offline. Retrying connection");
  
            _this.isConnected = false;
            _this.retryCount++;
  
            if (_this.retryCount < 5) {
              _this.log.debug("[BaseClient:connect] Retry in 3 sec. Count : " + _this.retryCount);
              _this.mqtt.options.reconnectPeriod = 3000;
            } else if (_this.retryCount < 10) {
              _this.log.debug("[BaseClient:connect] Retry in 10 sec. Count : " + _this.retryCount);
              _this.mqtt.options.reconnectPeriod = 10000;
            } else {
              _this.log.debug("[BaseClient:connect] Retry in 60 sec. Count : " + _this.retryCount);
              _this.mqtt.options.reconnectPeriod = 60000;
            }
          });
  
          this.mqtt.on('close', function () {
            _this.log.info("[BaseClient:onClose] Connection was closed.");
            _this.isConnected = false;
            _this.emit('disconnect');
          });
  
          this.mqtt.on('error', function (error) {
            _this.log.error("[BaseClient:onError] Connection Error :: " + error);
            _this.isConnected = false;
            _this.emit('error', error);
          });
        }
      }, {
        key: 'disconnect',
        value: function disconnect() {
          var _this2 = this;
  
          if (!this.isConnected) {
            if (this.mqtt) {
              // The client is disconnected, but the reconnect thread
              // is running. Need to stop it.
              this.mqtt.end(true, function () {});
            }
            throw new Error("[BaseClient:disconnect] Client is not connected");
          }
  
          this.isConnected = false;
          this.mqtt.end(false, function () {
            _this2.log.info("[BaseClient:disconnect] Disconnected from the client.");
          });
  
          delete this.mqtt;
        }
      }]);
  
      return BaseClient;
    })(_events2['default'].EventEmitter);
  
    module.exports = BaseClient;
  });
  }).call(this,"/node_modules/ibmiotf/dist/clients")
  },{"../util/util.js":9,"events":100,"loglevel":28,"mqtt":30}],4:[function(require,module,exports){
  (function (Buffer){
  (function (global, factory) {
    if (typeof define === 'function' && define.amd) {
      define(['exports', 'module', 'format', 'axios', 'bluebird', 'btoa', '../util/util.js', './BaseClient.js'], factory);
    } else if (typeof exports !== 'undefined' && typeof module !== 'undefined') {
      factory(exports, module, require('format'), require('axios'), require('bluebird'), require('btoa'), require('../util/util.js'), require('./BaseClient.js'));
    } else {
      var mod = {
        exports: {}
      };
      factory(mod.exports, mod, global.format, global.xhr, global.Promise, global.nodeBtoa, global.util, global.BaseClient);
      global.DeviceClient = mod.exports;
    }
  })(this, function (exports, module, _format, _axios, _bluebird, _btoa, _utilUtilJs, _BaseClientJs) {
    /**
     *****************************************************************************
     Copyright (c) 2014, 2015 IBM Corporation and other Contributors.
     All rights reserved. This program and the accompanying materials
     are made available under the terms of the Eclipse Public License v1.0
     which accompanies this distribution, and is available at
     http://www.eclipse.org/legal/epl-v10.html
     Contributors:
     Tim-Daniel Jacobi - Initial Contribution
     Jeffrey Dare
     Lokesh Haralakatta - Added Client Side Certificates Support
     *****************************************************************************
     *
     */
    'use strict';
  
    var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
  
    var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
  
    function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  
    function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
  
    function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
  
    var _format2 = _interopRequireDefault(_format);
  
    var _xhr = _interopRequireDefault(_axios);
  
    var _Promise = _interopRequireDefault(_bluebird);
  
    var _nodeBtoa = _interopRequireDefault(_btoa);
  
    var _BaseClient2 = _interopRequireDefault(_BaseClientJs);
  
    var btoa = btoa || _nodeBtoa['default']; // if browser btoa is available use it otherwise use node module
  
    var WILDCARD_TOPIC = 'iot-2/cmd/+/fmt/+';
    var CMD_RE = /^iot-2\/cmd\/(.+)\/fmt\/(.+)$/;
    var QUICKSTART_ORG_ID = "quickstart";
  
    var DeviceClient = (function (_BaseClient) {
      _inherits(DeviceClient, _BaseClient);
  
      function DeviceClient(config) {
        _classCallCheck(this, DeviceClient);
  
        _get(Object.getPrototypeOf(DeviceClient.prototype), 'constructor', this).call(this, config);
  
        if (!(0, _utilUtilJs.isDefined)(config.type)) {
          throw new Error('[DeviceClient:constructor] config must contain type');
        } else if (!(0, _utilUtilJs.isString)(config.type)) {
          throw new Error('[DeviceClient:constructor] type must be a string');
        }
  
        if (config.org !== QUICKSTART_ORG_ID) {
          if (!(0, _utilUtilJs.isDefined)(config['auth-method'])) {
            throw new Error('[DeviceClient:constructor] config must contain auth-method');
          } else if (!(0, _utilUtilJs.isString)(config['auth-method'])) {
            throw new Error('[DeviceClient:constructor] auth-method must be a string');
          } else if (config['auth-method'] !== 'token') {
            throw new Error('[DeviceClient:constructor] unsupported authentication method' + config['auth-method']);
          }
  
          this.mqttConfig.username = 'use-token-auth';
        }
  
        this.org = config.org;
        this.typeId = config.type;
        this.deviceId = config.id;
        this.deviceToken = config['auth-token'];
        this.mqttConfig.clientId = "d:" + config.org + ":" + config.type + ":" + config.id;
  
        this.log.info("[DeviceClient:constructor] DeviceClient initialized for organization : " + config.org + " for ID : " + config.id);
      }
  
      _createClass(DeviceClient, [{
        key: 'connect',
        value: function connect(QoS) {
          var _this = this;
  
          QoS = QoS || 2;
          _get(Object.getPrototypeOf(DeviceClient.prototype), 'connect', this).call(this);
  
          var mqtt = this.mqtt;
  
          this.mqtt.on('connect', function () {
            _this.isConnected = true;
            if ((0, _utilUtilJs.isDefined)(_this.mqttConfig.servername)) {
              _this.log.info("[DeviceClient:connect] DeviceClient Connected using Client Side Certificates");
            } else {
              _this.log.info("[DeviceClient:connect] DeviceClient Connected");
            }
            if (_this.retryCount === 0) {
              _this.emit('connect');
            } else {
              _this.emit('reconnect');
            }
  
            //reset the counter to 0 incase of reconnection
            _this.retryCount = 0;
  
            if (!_this.isQuickstart) {
              mqtt.subscribe(WILDCARD_TOPIC, { qos: parseInt(QoS) }, function () {});
            }
          });
  
          this.mqtt.on('message', function (topic, payload) {
            _this.log.debug("[DeviceClient:onMessage] Message received on topic : " + topic + " with payload : " + payload);
  
            var match = CMD_RE.exec(topic);
  
            if (match) {
              _this.emit('command', match[1], match[2], payload, topic);
            }
          });
        }
      }, {
        key: 'publish',
        value: function publish(eventType, eventFormat, payload, qos, callback) {
          if (!this.isConnected) {
            this.log.error("[DeviceClient:publish] Client is not connected");
            //throw new Error();
            //instead of throwing error, will emit 'error' event.
            this.emit('error', "[DeviceClient:publish] Client is not connected");
          }
  
          var topic = (0, _format2['default'])("iot-2/evt/%s/fmt/%s", eventType, eventFormat);
          var QOS = qos || 0;
  
          if ((typeof payload === 'object' || typeof payload === 'boolean' || typeof payload === 'number') && !Buffer.isBuffer(payload)) {
            // mqtt library does not support sending JSON/boolean/number data. So stringifying it.
            // All JSON object, array will be encoded.
            payload = JSON.stringify(payload);
          }
          this.log.debug("[DeviceClient:publish] Publishing to topic " + topic + " with payload " + payload + " with QoS " + QOS);
          this.mqtt.publish(topic, payload, { qos: parseInt(QOS) }, callback);
  
          return this;
        }
      }, {
        key: 'publishHTTPS',
        value: function publishHTTPS(eventType, eventFormat, payload) {
          var _this2 = this;
  
          this.log.debug("[DeviceClient:publishHTTPS] Publishing event of Type: " + eventType + " with payload : " + payload);
          return new _Promise['default'](function (resolve, reject) {
            var uri = (0, _format2['default'])("https://%s/api/v0002/device/types/%s/devices/%s/events/%s", _this2.mqttServer, _this2.typeId, _this2.deviceId, eventType);
  
            var xhrConfig = {
              url: uri,
              method: 'POST',
              data: payload,
              headers: {}
            };
  
            if (eventFormat === 'json') {
              xhrConfig.headers['Content-Type'] = 'application/json';
            } else if (eventFormat === 'xml') {
              xhrConfig.headers['Content-Type'] = 'application/xml';
            }
  
            if (_this2.org !== QUICKSTART_ORG_ID) {
              xhrConfig.headers['Authorization'] = 'Basic ' + btoa('use-token-auth' + ':' + _this2.deviceToken);
            }
            _this2.log.debug("[DeviceClient:publishHTTPS] " + xhrConfig);
  
            (0, _xhr['default'])(xhrConfig).then(resolve, reject);
          });
        }
      }]);
  
      return DeviceClient;
    })(_BaseClient2['default']);
  
    module.exports = DeviceClient;
  });
  }).call(this,{"isBuffer":require("../../../../../../../../../usr/local/lib/node_modules/browserify/node_modules/insert-module-globals/node_modules/is-buffer/index.js")})
  },{"../../../../../../../../../usr/local/lib/node_modules/browserify/node_modules/insert-module-globals/node_modules/is-buffer/index.js":102,"../util/util.js":9,"./BaseClient.js":3,"axios":10,"bluebird":25,"btoa":26,"format":27}],5:[function(require,module,exports){
  (function (Buffer){
  (function (global, factory) {
    if (typeof define === 'function' && define.amd) {
      define(['exports', 'module', 'format', 'axios', 'bluebird', 'btoa', '../util/util.js', './BaseClient.js'], factory);
    } else if (typeof exports !== 'undefined' && typeof module !== 'undefined') {
      factory(exports, module, require('format'), require('axios'), require('bluebird'), require('btoa'), require('../util/util.js'), require('./BaseClient.js'));
    } else {
      var mod = {
        exports: {}
      };
      factory(mod.exports, mod, global.format, global.xhr, global.Promise, global.nodeBtoa, global.util, global.BaseClient);
      global.GatewayClient = mod.exports;
    }
  })(this, function (exports, module, _format, _axios, _bluebird, _btoa, _utilUtilJs, _BaseClientJs) {
    /**
     *****************************************************************************
     Copyright (c) 2014, 2015 IBM Corporation and other Contributors.
     All rights reserved. This program and the accompanying materials
     are made available under the terms of the Eclipse Public License v1.0
     which accompanies this distribution, and is available at
     http://www.eclipse.org/legal/epl-v10.html
     Contributors:
     Tim-Daniel Jacobi - Initial Contribution
     Jeffrey Dare
     Lokesh Haralakatta - Added Client Side Certificates Support
     *****************************************************************************
     *
     */
    'use strict';
  
    var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
  
    var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
  
    function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  
    function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
  
    function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
  
    var _format2 = _interopRequireDefault(_format);
  
    var _xhr = _interopRequireDefault(_axios);
  
    var _Promise = _interopRequireDefault(_bluebird);
  
    var _nodeBtoa = _interopRequireDefault(_btoa);
  
    var _BaseClient2 = _interopRequireDefault(_BaseClientJs);
  
    var btoa = btoa || _nodeBtoa['default']; // if browser btoa is available use it otherwise use node module
  
    var CMD_RE = /^iot-2\/type\/(.+)\/id\/(.+)\/cmd\/(.+)\/fmt\/(.+)$/;
    var QUICKSTART_ORG_ID = "quickstart";
  
    var GatewayClient = (function (_BaseClient) {
      _inherits(GatewayClient, _BaseClient);
  
      function GatewayClient(config) {
        _classCallCheck(this, GatewayClient);
  
        _get(Object.getPrototypeOf(GatewayClient.prototype), 'constructor', this).call(this, config);
  
        if (!(0, _utilUtilJs.isDefined)(config.type)) {
          throw new Error('[GatewayClient:constructor] config must contain type');
        } else if (!(0, _utilUtilJs.isString)(config.type)) {
          throw new Error('[GatewayClient:constructor] type must be a string');
        }
  
        if (config.org === QUICKSTART_ORG_ID) {
          throw new Error('[GatewayClient:constructor] Quickstart not supported in Gateways');
        }
  
        if (!(0, _utilUtilJs.isDefined)(config['auth-method'])) {
          throw new Error('[GatewayClient:constructor] config must contain auth-method');
        } else if (!(0, _utilUtilJs.isString)(config['auth-method'])) {
          throw new Error('[GatewayClient:constructor] auth-method must be a string');
        } else if (config['auth-method'] !== 'token') {
          throw new Error('[GatewayClient:constructor] unsupported authentication method' + config['auth-method']);
        }
  
        this.mqttConfig.username = 'use-token-auth';
  
        this.org = config.org;
        this.type = config.type;
        this.id = config.id;
        this.deviceToken = config['auth-token'];
        this.mqttConfig.clientId = "g:" + config.org + ":" + config.type + ":" + config.id;
  
        this.subscriptions = [];
  
        this.log.info("[GatewayClient:constructor] GatewayClient initialized for organization : " + config.org + " for ID : " + config.id);
      }
  
      _createClass(GatewayClient, [{
        key: 'connect',
        value: function connect(QoS) {
          var _this = this;
  
          QoS = QoS || 0;
          _get(Object.getPrototypeOf(GatewayClient.prototype), 'connect', this).call(this);
  
          var mqtt = this.mqtt;
  
          this.mqtt.on('connect', function () {
            _this.isConnected = true;
            if ((0, _utilUtilJs.isDefined)(_this.mqttConfig.servername)) {
              _this.log.info("[GatewayClient:connect] GatewayClient Connected using Client Side Certificates");
            } else {
              _this.log.info("[GatewayClient:connect] GatewayClient Connected");
            }
            if (_this.retryCount === 0) {
              _this.emit('connect');
            } else {
              _this.emit('reconnect');
            }
  
            //reset the counter to 0 incase of reconnection
            _this.retryCount = 0;
  
            try {
              for (var i = 0, l = _this.subscriptions.length; i < l; i++) {
                mqtt.subscribe(_this.subscriptions[i], { qos: parseInt(QoS) });
              }
            } catch (err) {
              _this.log.error("[GatewayClient:connect] Error while trying to subscribe : " + err);
            }
  
            //subscribe to all the commands for this gateway by default
            /*let gatewayWildCardTopic = format("iot-2/type/%s/id/%s/cmd/+/fmt/+", this.type, this.id);
            mqtt.subscribe(gatewayWildCardTopic, { qos: 2 }, function(){});*/
          });
  
          this.mqtt.on('message', function (topic, payload) {
            _this.log.debug("[GatewayClient:onMessage] Message received on topic : " + topic + " with payload : " + payload);
  
            var match = CMD_RE.exec(topic);
  
            if (match) {
              _this.emit('command', match[1], match[2], match[3], match[4], payload, topic);
            }
          });
        }
      }, {
        key: 'publishGatewayEvent',
        value: function publishGatewayEvent(eventType, eventFormat, payload, qos, callback) {
          return this.publishEvent(this.type, this.id, eventType, eventFormat, payload, qos, callback);
        }
      }, {
        key: 'publishDeviceEvent',
        value: function publishDeviceEvent(deviceType, deviceId, eventType, eventFormat, payload, qos, callback) {
          return this.publishEvent(deviceType, deviceId, eventType, eventFormat, payload, qos, callback);
        }
      }, {
        key: 'publishEvent',
        value: function publishEvent(type, id, eventType, eventFormat, payload, qos, callback) {
          if (!this.isConnected) {
            this.log.error("[GatewayClient:publishEvent] Client is not connected");
            //throw new Error("Client is not connected");
            //instead of throwing error, will emit 'error' event.
            this.emit('error', "[GatewayClient:publishEvent] Client is not connected");
          }
  
          if (!(0, _utilUtilJs.isDefined)(payload)) {
            this.log.error("[GatewayClient:publishEvent] Payload is undefined");
            payload = "";
          }
  
          var topic = (0, _format2['default'])("iot-2/type/%s/id/%s/evt/%s/fmt/%s", type, id, eventType, eventFormat);
          var QoS = qos || 0;
  
          if ((typeof payload === 'object' || typeof payload === 'boolean' || typeof payload === 'number') && !Buffer.isBuffer(payload)) {
            // mqtt library does not support sending JSON data. So stringifying it.
            // All JSON object, array will be encoded.
            payload = JSON.stringify(payload);
          }
  
          this.log.debug("[GatewayClient:publishEvent] Publishing to topic : " + topic + " with payload : " + payload + " with QoS : " + QoS);
          this.mqtt.publish(topic, payload, { qos: parseInt(QoS) }, callback);
  
          return this;
        }
      }, {
        key: 'publishHTTPS',
        value: function publishHTTPS(eventType, eventFormat, payload) {
          var _this2 = this;
  
          this.log.debug("Publishing event of Type: " + eventType + " with payload : " + payload);
          return new _Promise['default'](function (resolve, reject) {
            var uri = (0, _format2['default'])("https://%s.messaging.%s/api/v0002/device/types/%s/devices/%s/events/%s", _this2.org, _this2.domainName, _this2.type, _this2.id, eventType);
  
            var xhrConfig = {
              url: uri,
              method: 'POST',
              data: payload,
              headers: {}
            };
  
            if (eventFormat === 'json') {
              xhrConfig.headers['Content-Type'] = 'application/json';
            } else if (eventFormat === 'xml') {
              xhrConfig.headers['Content-Type'] = 'application/xml';
            }
  
            if (_this2.org !== QUICKSTART_ORG_ID) {
              xhrConfig.headers['Authorization'] = 'Basic ' + btoa('use-token-auth' + ':' + _this2.deviceToken);
            }
            _this2.log.debug("[GatewayClient:publishHTTPS]" + xhrConfig);
  
            (0, _xhr['default'])(xhrConfig).then(resolve, reject);
          });
        }
      }, {
        key: 'subscribeToDeviceCommand',
        value: function subscribeToDeviceCommand(type, id, command, format, qos) {
          type = type || '+';
          id = id || '+';
          command = command || '+';
          format = format || '+';
          qos = qos || 0;
  
          var topic = "iot-2/type/" + type + "/id/" + id + "/cmd/" + command + "/fmt/" + format;
  
          this.log.debug("[GatewayClient:subscribeToDeviceCommand] Subscribing to topic: " + topic + " with QoS: " + qos);
          this.subscribe(topic, qos);
  
          return this;
        }
      }, {
        key: 'unsubscribeToDeviceCommand',
        value: function unsubscribeToDeviceCommand(type, id, command, format) {
          type = type || '+';
          id = id || '+';
          command = command || '+';
          format = format || '+';
  
          var topic = "iot-2/type/" + type + "/id/" + id + "/cmd/" + command + "/fmt/" + format;
  
          this.unsubscribe(topic);
  
          return this;
        }
      }, {
        key: 'subscribeToGatewayCommand',
        value: function subscribeToGatewayCommand(command, format, qos) {
          command = command || '+';
          format = format || '+';
          qos = qos || 0;
  
          var topic = "iot-2/type/" + this.type + "/id/" + this.id + "/cmd/" + command + "/fmt/" + format;
  
          this.subscribe(topic, qos);
          return this;
        }
      }, {
        key: 'unsubscribeToGatewayCommand',
        value: function unsubscribeToGatewayCommand(command, format) {
          command = command || '+';
          format = format || '+';
  
          var topic = "iot-2/type/" + this.type + "/id/" + this.id + "/cmd/" + command + "/fmt/" + format;
  
          this.unsubscribe(topic);
  
          return this;
        }
      }, {
        key: 'subscribe',
        value: function subscribe(topic, QoS) {
          QoS = QoS || 0;
          if (!this.isConnected) {
            this.log.error("[GatewayClient:subscribe] Client is not connected");
            //throw new Error("Client is not connected");
            //instead of throwing error, will emit 'error' event.
            this.emit('error', "[GatewayClient:subscribe] Client is not connected. So cannot subscribe to topic :" + topic);
          }
  
          this.subscriptions.push(topic);
  
          if (this.isConnected) {
            this.mqtt.subscribe(topic, { qos: parseInt(QoS) });
            this.log.debug("[GatewayClient:subscribe] Subscribed to: " + topic);
          } else {
            this.log.error("[GatewayClient:subscribe] Unable to subscribe as application is not currently connected");
          }
        }
      }, {
        key: 'unsubscribe',
        value: function unsubscribe(topic) {
          if (!this.isConnected) {
            this.log.error("[GatewayClient:unsubscribe] Client is not connected");
            //throw new Error("Client is not connected");
            //instead of throwing error, will emit 'error' event.
            this.emit('error', "[GatewayClient:unsubscribe] Client is not connected");
          }
  
          this.log.debug("[GatewayClient:unsubscribe] Unsubscribe: " + topic);
          var i = this.subscriptions.indexOf(topic);
          if (i != -1) {
            this.subscriptions.splice(i, 1);
          }
  
          this.mqtt.unsubscribe(topic);
          this.log.debug("[GatewayClient:unsubscribe] Unsubscribed to: " + topic);
        }
      }]);
  
      return GatewayClient;
    })(_BaseClient2['default']);
  
    module.exports = GatewayClient;
  });
  }).call(this,{"isBuffer":require("../../../../../../../../../usr/local/lib/node_modules/browserify/node_modules/insert-module-globals/node_modules/is-buffer/index.js")})
  },{"../../../../../../../../../usr/local/lib/node_modules/browserify/node_modules/insert-module-globals/node_modules/is-buffer/index.js":102,"../util/util.js":9,"./BaseClient.js":3,"axios":10,"bluebird":25,"btoa":26,"format":27}],6:[function(require,module,exports){
  (function (global, factory) {
    if (typeof define === 'function' && define.amd) {
      define(['exports', 'module', 'format', '../util/util.js', './DeviceClient.js'], factory);
    } else if (typeof exports !== 'undefined' && typeof module !== 'undefined') {
      factory(exports, module, require('format'), require('../util/util.js'), require('./DeviceClient.js'));
    } else {
      var mod = {
        exports: {}
      };
      factory(mod.exports, mod, global.format, global.util, global.DeviceClient);
      global.ManagedDeviceClient = mod.exports;
    }
  })(this, function (exports, module, _format, _utilUtilJs, _DeviceClientJs) {
    /**
     *****************************************************************************
     Copyright (c) 2014, 2015 IBM Corporation and other Contributors.
     All rights reserved. This program and the accompanying materials
     are made available under the terms of the Eclipse Public License v1.0
     which accompanies this distribution, and is available at
     http://www.eclipse.org/legal/epl-v10.html
     Contributors:
     Harrison Kurtz - Initial Contribution
     Jeffrey Dare
     *****************************************************************************
     *
     */
    'use strict';
  
    var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
  
    var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
  
    function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  
    function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
  
    function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
  
    var _format2 = _interopRequireDefault(_format);
  
    var _DeviceClient2 = _interopRequireDefault(_DeviceClientJs);
  
    var QUICKSTART_ORG_ID = 'quickstart';
    var QOS = 1;
  
    // Publish MQTT topics
    var RESPONSE_TOPIC = 'iotdevice-1/response';
    var MANAGE_TOPIC = 'iotdevice-1/mgmt/manage';
    var UNMANAGE_TOPIC = 'iotdevice-1/mgmt/unmanage';
    var UPDATE_LOCATION_TOPIC = 'iotdevice-1/device/update/location';
    var ADD_LOG_TOPIC = 'iotdevice-1/add/diag/log';
    var CLEAR_LOGS_TOPIC = 'iotdevice-1/clear/diag/log';
    var ADD_ERROR_CODE_TOPIC = 'iotdevice-1/add/diag/errorCodes';
    var CLEAR_ERROR_CODES_TOPIC = 'iotdevice-1/clear/diag/errorCodes';
    var NOTIFY_TOPIC = 'iotdevice-1/notify';
  
    // Subscribe MQTT topics
    var DM_WILDCARD_TOPIC = 'iotdm-1/#';
    var DM_RESPONSE_TOPIC = 'iotdm-1/response';
    var DM_UPDATE_TOPIC = 'iotdm-1/device/update';
    var DM_OBSERVE_TOPIC = 'iotdm-1/observe';
    var DM_CANCEL_OBSERVE_TOPIC = 'iotdm-1/cancel';
    var DM_REBOOT_TOPIC = 'iotdm-1/mgmt/initiate/device/reboot';
    var DM_FACTORY_RESET_TOPIC = 'iotdm-1/mgmt/initiate/device/factory_reset';
    var DM_FIRMWARE_DOWNLOAD_TOPIC = 'iotdm-1/mgmt/initiate/firmware/download';
    var DM_FIRMWARE_UPDATE_TOPIC = 'iotdm-1/mgmt/initiate/firmware/update';
  
    // Regex topic
    var DM_REQUEST_RE = /^iotdm-1\/*/;
    var DM_ACTION_RE = /^iotdm-1\/mgmt\/initiate\/(.+)\/(.+)$/;
    var DM_CUSTOM_ACTION_RE = /^iotdm-1\/mgmt\/custom\/(.+)\/(.+)$/;
  
    var ManagedDeviceClient = (function (_DeviceClient) {
      _inherits(ManagedDeviceClient, _DeviceClient);
  
      function ManagedDeviceClient(config) {
        _classCallCheck(this, ManagedDeviceClient);
  
        _get(Object.getPrototypeOf(ManagedDeviceClient.prototype), 'constructor', this).call(this, config);
  
        if (config.org === QUICKSTART_ORG_ID) {
          throw new Error('cannot use quickstart for a managed device');
        }
  
        this._deviceRequests = {};
        this._dmRequests = {};
  
        //variables for firmware update
        this.location = {};
        this.mgmtFirmware = {};
  
        this.observe;
  
        //various states in update of firmware
        this.FIRMWARESTATE = {
          IDLE: 0,
          DOWNLOADING: 1,
          DOWNLOADED: 2
        };
  
        this.FIRMWAREUPDATESTATE = {
          SUCCESS: 0,
          IN_PROGRESS: 1,
          OUT_OF_MEMORY: 2,
          CONNECTION_LOST: 3,
          VERIFICATION_FAILED: 4,
          UNSUPPORTED_IMAGE: 5,
          INVALID_URL: 6
        };
  
        this.RESPONSECODE = {
          SUCCESS: 200,
          ACCEPTED: 202,
          UPDATE_SUCCESS: 204,
          BAD_REQUEST: 400,
          NOT_FOUND: 404,
          INTERNAL_ERROR: 500,
          FUNCTION_NOT_SUPPORTED: 501
        };
      }
  
      _createClass(ManagedDeviceClient, [{
        key: 'connect',
        value: function connect() {
          var _this = this;
  
          _get(Object.getPrototypeOf(ManagedDeviceClient.prototype), 'connect', this).call(this);
  
          var mqtt = this.mqtt;
  
          this.mqtt.on('connect', function () {
            mqtt.subscribe(DM_WILDCARD_TOPIC, { qos: QOS }, function () {});
          });
  
          this.mqtt.on('message', function (topic, payload) {
            var match = DM_REQUEST_RE.exec(topic);
  
            if (match) {
              if (topic == DM_RESPONSE_TOPIC) {
                _this._onDmResponse(payload);
              } else if (topic == DM_UPDATE_TOPIC) {
                _this._onDmUpdate(payload);
              } else if (topic == DM_OBSERVE_TOPIC) {
                _this._onDmObserve(payload);
              } else if (topic == DM_CANCEL_OBSERVE_TOPIC) {
                _this._onDmCancel(payload);
              } else {
                _this._onDmRequest(topic, payload);
              }
            }
          });
        }
      }, {
        key: 'manage',
        value: function manage(lifetime, supportDeviceActions, supportFirmwareActions, extensions) {
          if (!this.isConnected) {
            this.log.error("Client is not connected");
            //throw new Error();
            //instead of throwing error, will emit 'error' event.
            this.emit('error', "Client is not connected");
          }
  
          var d = new Object();
  
          if ((0, _utilUtilJs.isDefined)(lifetime)) {
            if (!(0, _utilUtilJs.isNumber)(lifetime)) {
              throw new Error("lifetime must be a number");
            }
  
            if (lifetime < 3600) {
              throw new Error("lifetime cannot be less than 3600");
            }
  
            d.lifetime = lifetime;
          }
  
          if ((0, _utilUtilJs.isDefined)(supportDeviceActions) || (0, _utilUtilJs.isDefined)(supportFirmwareActions) || (0, _utilUtilJs.isDefined)(extensions)) {
            d.supports = new Object();
  
            if ((0, _utilUtilJs.isDefined)(supportDeviceActions)) {
              if (!(0, _utilUtilJs.isBoolean)(supportDeviceActions)) {
                throw new Error("supportDeviceActions must be a boolean");
              }
              this.deviceActions = supportDeviceActions;
              d.supports.deviceActions = supportDeviceActions;
            }
  
            if ((0, _utilUtilJs.isDefined)(supportFirmwareActions)) {
              if (!(0, _utilUtilJs.isBoolean)(supportFirmwareActions)) {
                throw new Error("supportFirmwareActions must be a boolean");
              }
  
              this.supportFirmwareActions = supportFirmwareActions;
              d.supports.firmwareActions = supportFirmwareActions;
            }
  
            if ((0, _utilUtilJs.isDefined)(extensions)) {
              if (!Array.isArray(extensions)) {
                throw new Error("extensions must be an array");
              }
              var i;
              for (i = 0; i < extensions.length; i++) {
                d.supports[extensions[i]] = true;
              }
            }
          }
  
          var payload = new Object();
          payload.d = d;
  
          var reqId = (0, _utilUtilJs.generateUUID)();
          payload.reqId = reqId;
          payload = JSON.stringify(payload);
  
          this._deviceRequests[reqId] = { topic: MANAGE_TOPIC, payload: payload };
  
          this.log.debug("Publishing manage request with payload : %s", payload);
          this.mqtt.publish(MANAGE_TOPIC, payload, QOS);
  
          return reqId;
        }
      }, {
        key: 'unmanage',
        value: function unmanage() {
          if (!this.isConnected) {
            this.log.error("Client is not connected");
            //throw new Error();
            //instead of throwing error, will emit 'error' event.
            this.emit('error', "Client is not connected");
          }
  
          var payload = new Object();
  
          var reqId = (0, _utilUtilJs.generateUUID)();
          payload.reqId = reqId;
          payload = JSON.stringify(payload);
  
          this._deviceRequests[reqId] = { topic: UNMANAGE_TOPIC, payload: payload };
  
          this.log.debug("Publishing unmanage request with payload : %s", payload);
          this.mqtt.publish(UNMANAGE_TOPIC, payload, QOS);
  
          return reqId;
        }
      }, {
        key: 'updateLocation',
        value: function updateLocation(latitude, longitude, elevation, accuracy) {
          if (!this.isConnected) {
            this.log.error("Client is not connected");
            //throw new Error();
            //instead of throwing error, will emit 'error' event.
            this.emit('error', "Client is not connected");
          }
  
          if (!(0, _utilUtilJs.isDefined)(longitude) || !(0, _utilUtilJs.isDefined)(latitude)) {
            throw new Error("longitude and latitude are required for updating location");
          }
  
          if (!(0, _utilUtilJs.isNumber)(longitude) || !(0, _utilUtilJs.isNumber)(latitude)) {
            throw new Error("longitude and latitude must be numbers");
          }
  
          if (longitude < -180 || longitude > 180) {
            throw new Error("longitude cannot be less than -180 or greater than 180");
          }
  
          if (latitude < -90 || latitude > 90) {
            throw new Error("latitude cannot be less than -90 or greater than 90");
          }
  
          var d = new Object();
          d.longitude = longitude;
          d.latitude = latitude;
  
          if ((0, _utilUtilJs.isDefined)(elevation)) {
            if (!(0, _utilUtilJs.isNumber)(elevation)) {
              throw new Error("elevation must be a number");
            }
  
            d.elevation = elevation;
          }
  
          if ((0, _utilUtilJs.isDefined)(accuracy)) {
            if (!(0, _utilUtilJs.isNumber)(accuracy)) {
              throw new Error("accuracy must be a number");
            }
  
            d.accuracy = accuracy;
          }
  
          d.measuredDateTime = new Date().toISOString();
  
          var payload = new Object();
          payload.d = d;
  
          var reqId = (0, _utilUtilJs.generateUUID)();
          payload.reqId = reqId;
          payload = JSON.stringify(payload);
  
          //update the location
          this.location = d;
  
          this._deviceRequests[reqId] = { topic: UPDATE_LOCATION_TOPIC, payload: payload };
  
          this.log.debug("Publishing update location request with payload : %s", payload);
          this.mqtt.publish(UPDATE_LOCATION_TOPIC, payload, QOS);
  
          return reqId;
        }
      }, {
        key: 'addErrorCode',
        value: function addErrorCode(errorCode) {
          if (!this.isConnected) {
            this.log.error("Client is not connected");
            //throw new Error();
            //instead of throwing error, will emit 'error' event.
            this.emit('error', "Client is not connected");
          }
  
          if (!(0, _utilUtilJs.isDefined)(errorCode)) {
            throw new Error("error code is required for adding an error code");
          }
  
          if (!(0, _utilUtilJs.isNumber)(errorCode)) {
            throw new Error("error code must be a number");
          }
  
          var d = new Object();
          d.errorCode = errorCode;
  
          var payload = new Object();
          payload.d = d;
  
          var reqId = (0, _utilUtilJs.generateUUID)();
          payload.reqId = reqId;
          payload = JSON.stringify(payload);
  
          this._deviceRequests[reqId] = { topic: ADD_ERROR_CODE_TOPIC, payload: payload };
  
          this.log.debug("Publishing add error code request with payload : %s", payload);
          this.mqtt.publish(ADD_ERROR_CODE_TOPIC, payload, QOS);
  
          return reqId;
        }
      }, {
        key: 'clearErrorCodes',
        value: function clearErrorCodes() {
          if (!this.isConnected) {
            this.log.error("Client is not connected");
            //throw new Error();
            //instead of throwing error, will emit 'error' event.
            this.emit('error', "Client is not connected");
          }
  
          var payload = new Object();
  
          var reqId = (0, _utilUtilJs.generateUUID)();
          payload.reqId = reqId;
          payload = JSON.stringify(payload);
  
          this._deviceRequests[reqId] = { topic: CLEAR_ERROR_CODES_TOPIC, payload: payload };
  
          this.log.debug("Publishing clear error codes request with payload : %s", payload);
          this.mqtt.publish(CLEAR_ERROR_CODES_TOPIC, payload, QOS);
  
          return reqId;
        }
      }, {
        key: 'addLog',
        value: function addLog(message, severity, data) {
          if (!this.isConnected) {
            this.log.error("Client is not connected");
            //throw new Error();
            //instead of throwing error, will emit 'error' event.
            this.emit('error', "Client is not connected");
          }
  
          if (!(0, _utilUtilJs.isDefined)(message) || !(0, _utilUtilJs.isDefined)(severity)) {
            throw new Error("message and severity are required for adding a log");
          }
  
          if (!(0, _utilUtilJs.isString)(message)) {
            throw new Error("message must be a string");
          }
  
          if (!(0, _utilUtilJs.isNumber)(severity)) {
            throw new Error("severity must be a number");
          }
  
          if (!(severity === 0 || severity === 1 || severity === 2)) {
            throw new Error("severity can only equal 0, 1, or 2");
          }
  
          var d = new Object();
          d.message = message;
          d.severity = severity;
          d.timestamp = new Date().toISOString();
  
          if ((0, _utilUtilJs.isDefined)(data)) {
            if (!(0, _utilUtilJs.isString)(data)) {
              throw new Error("data must be a string");
            }
  
            d.data = data;
          }
  
          var payload = new Object();
          payload.d = d;
  
          var reqId = (0, _utilUtilJs.generateUUID)();
          payload.reqId = reqId;
          payload = JSON.stringify(payload);
  
          this._deviceRequests[reqId] = { topic: ADD_LOG_TOPIC, payload: payload };
  
          this.log.debug("Publishing add log request with payload : %s", payload);
          this.mqtt.publish(ADD_LOG_TOPIC, payload, QOS);
  
          return reqId;
        }
      }, {
        key: 'clearLogs',
        value: function clearLogs() {
          if (!this.isConnected) {
            this.log.error("Client is not connected");
            //throw new Error();
            //instead of throwing error, will emit 'error' event.
            this.emit('error', "Client is not connected");
          }
  
          var payload = new Object();
  
          var reqId = (0, _utilUtilJs.generateUUID)();
          payload.reqId = reqId;
          payload = JSON.stringify(payload);
  
          this._deviceRequests[reqId] = { topic: CLEAR_LOGS_TOPIC, payload: payload };
  
          this.log.debug("Publishing clear logs request with payload : %s", payload);
          this.mqtt.publish(CLEAR_LOGS_TOPIC, payload, QOS);
  
          return reqId;
        }
      }, {
        key: 'respondDeviceAction',
        value: function respondDeviceAction(request, rc, message) {
          if (!this.isConnected) {
            this.log.error("Client is not connected");
            //throw new Error();
            //instead of throwing error, will emit 'error' event.
            this.emit('error', "Client is not connected");
          }
  
          if (!(0, _utilUtilJs.isDefined)(request) || !(0, _utilUtilJs.isDefined)(rc)) {
            throw new Error("Request and rc(return code) are required");
          }
          var reqId = request.reqId;
  
          if (!(0, _utilUtilJs.isDefined)(reqId)) {
            throw new Error("reqId is required");
          }
  
          if (!(0, _utilUtilJs.isString)(reqId)) {
            throw new Error("reqId must be a string");
          }
  
          if (!(0, _utilUtilJs.isNumber)(rc)) {
            throw new Error("Return code must be a Number");
          }
  
          var request = this._dmRequests[reqId];
          if (!(0, _utilUtilJs.isDefined)(request)) {
            throw new Error("unknown request : " + reqId);
          }
  
          var payload = new Object();
          payload.rc = rc;
          payload.reqId = reqId;
  
          if ((0, _utilUtilJs.isDefined)(message)) {
            //setting the message on the response.
            payload.message = message;
          }
  
          payload = JSON.stringify(payload);
  
          this.log.debug("Publishing device action response with payload : %s", payload);
          this.mqtt.publish(RESPONSE_TOPIC, payload, QOS);
  
          delete this._dmRequests[reqId];
  
          return this;
        }
      }, {
        key: 'isRebootAction',
        value: function isRebootAction(request) {
          return request.action === "reboot";
        }
      }, {
        key: 'isFactoryResetAction',
        value: function isFactoryResetAction(request) {
          return request.action === "factory_reset";
        }
      }, {
        key: '_onDmResponse',
        value: function _onDmResponse(payload) {
          payload = JSON.parse(payload);
          var reqId = payload.reqId;
          var rc = payload.rc;
  
          var request = this._deviceRequests[reqId];
          if (!(0, _utilUtilJs.isDefined)(request)) {
            throw new Error("unknown request : %s", reqId);
          }
  
          switch (request.topic) {
            case MANAGE_TOPIC:
              if (rc == 200) {
                this.log.debug("[%s] Manage action completed : %s", rc, request.payload);
              } else {
                this.log.error("[%s] Manage action failed : %s", rc, request.payload);
              }
              break;
            case UNMANAGE_TOPIC:
              if (rc == 200) {
                this.log.debug("[%s] Unmanage action completed : %s", rc, request.payload);
              } else {
                this.log.error("[%s] Unmanage action failed : %s", rc, request.payload);
              }
              break;
            case UPDATE_LOCATION_TOPIC:
              if (rc == 200) {
                this.log.debug("[%s] Update location action completed : %s", rc, request.payload);
              } else {
                this.log.error("[%s] Update location failed : %s", rc, request.payload);
              }
              break;
            case ADD_LOG_TOPIC:
              if (rc == 200) {
                this.log.debug("[%s] Add log action completed : %s", rc, request.payload);
              } else {
                this.log.error("[%s] Add log action failed : %s", rc, request.payload);
              }
              break;
            case CLEAR_LOGS_TOPIC:
              if (rc == 200) {
                this.log.debug("[%s] Clear logs action completed : %s", rc, request.payload);
              } else {
                this.log.error("[%s] Clear logs action failed : %s", rc, request.payload);
              }
              break;
            case ADD_ERROR_CODE_TOPIC:
              if (rc == 200) {
                this.log.debug("[%s] Add error code action completed : %s", rc, request.payload);
              } else {
                this.log.error("[%s] Add error code action failed : %s", rc, request.payload);
              }
              break;
            case CLEAR_ERROR_CODES_TOPIC:
              if (rc == 200) {
                this.log.debug("[%s] Clear error codes action completed : %s", rc, request.payload);
              } else {
                this.log.error("[%s] Clear error codes action failed : %s", rc, request.payload);
              }
              break;
            default:
              throw new Error("unknown action response");
          }
  
          this.emit('dmResponse', {
            reqId: reqId,
            rc: rc
          });
  
          delete this._deviceRequests[reqId];
  
          return this;
        }
      }, {
        key: '_onDmUpdate',
        value: function _onDmUpdate(payload) {
          payload = JSON.parse(payload);
          var reqId = payload.reqId;
  
          var fields = payload.d.fields;
  
          for (var count = 0; count < fields.length; count++) {
  
            var field = fields[count];
            var fieldName = field.field;
            var value = field.value;
  
            this.log.debug("Update called for : %s with value : %s", fieldName, value);
  
            switch (fieldName) {
              case "mgmt.firmware":
                this.mgmtFirmware = value;
                break;
              case "location":
                this.location = value;
                //fire an event to notify user on location change
                this.emit('locationUpdate', value);
                break;
              case "metadata":
                //currently unsupported
                break;
              case "deviceInfo":
                //currently unsupported
                break;
              default:
                this.log.warn("Update called for Unknown field : " + fieldName);
            }
          }
  
          var payload = new Object();
          payload.rc = this.RESPONSECODE.UPDATE_SUCCESS;
          payload.reqId = reqId;
  
          payload = JSON.stringify(payload);
  
          this.log.debug("Publishing Device Update response with payload : %s", payload);
          this.mqtt.publish(RESPONSE_TOPIC, payload, QOS);
  
          return this;
        }
      }, {
        key: '_onDmObserve',
        value: function _onDmObserve(payload) {
  
          payload = JSON.parse(payload);
          var reqId = payload.reqId;
  
          var fields = payload.d.fields;
  
          for (var count = 0; count < fields.length; count++) {
  
            var field = fields[count];
            var fieldName = field.field;
            this.log.debug("Observe called for : " + fieldName);
            if (fieldName === 'mgmt.firmware') {
              this.observe = true;
              var payload = new Object();
              payload.rc = this.RESPONSECODE.SUCCESS;
              payload.reqId = reqId;
  
              payload.d = {};
              payload.d.fields = [];
  
              var fieldData = {
                field: fieldName,
                value: this.mgmtFirmware
              };
  
              payload.d.fields.push(fieldData);
  
              payload = JSON.stringify(payload);
  
              this.log.debug("Publishing Observe response with payload : %s", payload);
              this.mqtt.publish(RESPONSE_TOPIC, payload, QOS);
            }
          }
  
          return this;
        }
      }, {
        key: '_onDmCancel',
        value: function _onDmCancel(payload) {
  
          payload = JSON.parse(payload);
          var reqId = payload.reqId;
  
          var fields = payload.d.fields;
  
          for (var count = 0; count < fields.length; count++) {
  
            var field = fields[count];
            var fieldName = field.field;
            this.log.debug("Cancel called for : " + fieldName);
            if (fieldName === 'mgmt.firmware') {
              this.observe = false;
              var payload = new Object();
              payload.rc = this.RESPONSECODE.SUCCESS;
              payload.reqId = reqId;
  
              payload = JSON.stringify(payload);
  
              this.log.debug("Publishing Cancel response with payload : %s", payload);
              this.mqtt.publish(RESPONSE_TOPIC, payload, QOS);
            }
          }
  
          return this;
        }
      }, {
        key: '_onDmRequest',
        value: function _onDmRequest(topic, payload) {
          payload = JSON.parse(payload);
          var reqId = payload.reqId;
  
          this._dmRequests[reqId] = { topic: topic, payload: payload };
  
          var match = DM_ACTION_RE.exec(topic);
  
          if (match) {
            var type = match[1];
            var action = match[2];
  
            var data = {
              reqId: reqId,
              action: action
            };
  
            if (type === "firmware") {
              if (action === "download") {
                this._handleFirmwareDownload(payload, data);
              } else if (action === "update") {
                this._handleFirmwareUpdate(payload, data);
              }
            } else {
              this.emit('dmAction', data);
            }
          } else {
            match = DM_CUSTOM_ACTION_RE.exec(topic);
            if (match) {
              var action = match[2];
              this.emit('dmAction', { reqId: reqId, action: action });
            }
          }
  
          return this;
        }
      }, {
        key: '_handleFirmwareDownload',
        value: function _handleFirmwareDownload(payload, request) {
  
          this.log.debug("Called firmware Download");
  
          this.log.debug("Current value of mgmtFirmware : " + JSON.stringify(this.mgmtFirmware));
  
          var rc = undefined;
          var message = "";
          if (this.mgmtFirmware.state !== this.FIRMWARESTATE.IDLE) {
            rc = this.RESPONSECODE.BAD_REQUEST;
            message = "Cannot download as the device is not in idle state";
          } else {
            rc = this.RESPONSECODE.ACCEPTED;
            this.emit('firmwareDownload', this.mgmtFirmware);
          }
  
          this.respondDeviceAction(request, rc, message);
  
          return this;
        }
      }, {
        key: '_handleFirmwareUpdate',
        value: function _handleFirmwareUpdate(payload, request) {
  
          this.log.debug("Called firmware Update");
  
          this.log.debug("Current value of mgmtFirmware : " + JSON.stringify(this.mgmtFirmware));
  
          var rc = undefined;
          var message = "";
          if (this.mgmtFirmware.state !== this.FIRMWARESTATE.DOWNLOADED) {
            rc = this.RESPONSECODE.BAD_REQUEST;
            message = "Firmware is still not successfully downloaded.";
          } else {
            rc = this.RESPONSECODE.ACCEPTED;
            this.emit('firmwareUpdate', this.mgmtFirmware);
          }
  
          this.respondDeviceAction(request, rc, message);
  
          return this;
        }
      }, {
        key: 'changeState',
        value: function changeState(state) {
  
          if (this.observe) {
            this.mgmtFirmware.state = state;
            this._notify('mgmt.firmware', 'state', state);
          } else {
            this.log.warn("changeState called, but the mgmt.firmware is not observed now");
          }
        }
      }, {
        key: 'changeUpdateState',
        value: function changeUpdateState(state) {
  
          if (this.observe) {
            this.mgmtFirmware.updateStatus = state;
            this._notify('mgmt.firmware', 'updateStatus', state);
          } else {
            this.log.warn("changeUpdateState called, but the mgmt.firmware is not observed now");
          }
        }
      }, {
        key: '_notify',
        value: function _notify(property, field, newValue) {
          this.log.debug("Notify called : %s field : %s newValue : %s", property, field, newValue);
  
          var payload = {};
          payload.d = {};
          payload.d.fields = [];
  
          var data = {};
          data[field] = newValue;
          var fieldData = {
            field: property,
            value: data
          };
          payload.d.fields.push(fieldData);
  
          payload = JSON.stringify(payload);
          this.log.debug("Notify with %s", payload);
  
          this.mqtt.publish(NOTIFY_TOPIC, payload, QOS);
        }
      }]);
  
      return ManagedDeviceClient;
    })(_DeviceClient2['default']);
  
    module.exports = ManagedDeviceClient;
  });
  },{"../util/util.js":9,"./DeviceClient.js":4,"format":27}],7:[function(require,module,exports){
  (function (global, factory) {
    if (typeof define === 'function' && define.amd) {
      define(['exports', 'module', 'format', '../util/util.js', './GatewayClient.js'], factory);
    } else if (typeof exports !== 'undefined' && typeof module !== 'undefined') {
      factory(exports, module, require('format'), require('../util/util.js'), require('./GatewayClient.js'));
    } else {
      var mod = {
        exports: {}
      };
      factory(mod.exports, mod, global.format, global.util, global.GatewayClient);
      global.ManagedGatewayClient = mod.exports;
    }
  })(this, function (exports, module, _format, _utilUtilJs, _GatewayClientJs) {
    /**
     *****************************************************************************
     Copyright (c) 2014, 2015 IBM Corporation and other Contributors.
     All rights reserved. This program and the accompanying materials
     are made available under the terms of the Eclipse Public License v1.0
     which accompanies this distribution, and is available at
     http://www.eclipse.org/legal/epl-v10.html
     Contributors:
     Harrison Kurtz - Initial Contribution
     Jeffrey Dare
     *****************************************************************************
     *
     */
    'use strict';
  
    var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
  
    var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
  
    function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  
    function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
  
    function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
  
    var _format2 = _interopRequireDefault(_format);
  
    var _GatewayClient2 = _interopRequireDefault(_GatewayClientJs);
  
    var QUICKSTART_ORG_ID = 'quickstart';
    var QOS = 1;
  
    // Publish MQTT topics
    var RESPONSE_TOPIC = 'iotdevice-1/type/%s/id/%s/response';
    var MANAGE_TOPIC = 'iotdevice-1/type/%s/id/%s/mgmt/manage';
    var UNMANAGE_TOPIC = 'iotdevice-1/type/%s/id/%s/mgmt/unmanage';
    var UPDATE_LOCATION_TOPIC = 'iotdevice-1/type/%s/id/%s/device/update/location';
    var ADD_LOG_TOPIC = 'iotdevice-1/type/%s/id/%s/add/diag/log';
    var CLEAR_LOGS_TOPIC = 'iotdevice-1/type/%s/id/%s/clear/diag/log';
    var ADD_ERROR_CODE_TOPIC = 'iotdevice-1/type/%s/id/%s/add/diag/errorCodes';
    var CLEAR_ERROR_CODES_TOPIC = 'iotdevice-1/type/%s/id/%s/clear/diag/errorCodes';
    var NOTIFY_TOPIC = 'iotdevice-1/type/%s/id/%s/notify';
  
    // Subscribe MQTT topics
    var DM_WILDCARD_TOPIC = 'iotdm-1/#';
    var DM_RESPONSE_TOPIC = 'iotdm-1/response';
    var DM_UPDATE_TOPIC = 'iotdm-1/device/update';
    var DM_OBSERVE_TOPIC = 'iotdm-1/observe';
    var DM_CANCEL_OBSERVE_TOPIC = 'iotdm-1/cancel';
    var DM_REBOOT_TOPIC = 'iotdm-1/mgmt/initiate/device/reboot';
    var DM_FACTORY_RESET_TOPIC = 'iotdm-1/mgmt/initiate/device/factory_reset';
    var DM_FIRMWARE_DOWNLOAD_TOPIC = 'iotdm-1/mgmt/initiate/firmware/download';
    var DM_FIRMWARE_UPDATE_TOPIC = 'iotdm-1/mgmt/initiate/firmware/update';
  
    // Regex topic
    var DM_REQUEST_RE = /^iotdm-1\/*/;
    var DM_ACTION_RE = /^iotdm-1\/mgmt\/initiate\/(.+)\/(.+)$/;
    var DM_RESPONSE_TOPIC_RE = /^iotdm-1\/type\/(.+)\/id\/(.+)\/response$/;
  
    //Gateway actions
    var MANAGE = "manage";
    var UNMANAGE = "unmanage";
    var UPDATE_LOCATION = "updateLocation";
    var ADD_LOG = "addLog";
    var CLEAR_LOG = "clearLog";
    var ADD_ERROR = "addErrorCode";
    var CLEAR_ERROR = "clearErrorCodes";
  
    var ManagedGatewayClient = (function (_GatewayClient) {
      _inherits(ManagedGatewayClient, _GatewayClient);
  
      function ManagedGatewayClient(config) {
        _classCallCheck(this, ManagedGatewayClient);
  
        _get(Object.getPrototypeOf(ManagedGatewayClient.prototype), 'constructor', this).call(this, config);
  
        if (config.org === QUICKSTART_ORG_ID) {
          throw new Error('cannot use quickstart for a managed device');
        }
  
        this._deviceRequests = {};
        this._dmRequests = {};
      }
  
      _createClass(ManagedGatewayClient, [{
        key: 'connect',
        value: function connect() {
          var _this = this;
  
          _get(Object.getPrototypeOf(ManagedGatewayClient.prototype), 'connect', this).call(this);
  
          var mqtt = this.mqtt;
  
          this.mqtt.on('connect', function () {
            mqtt.subscribe(DM_WILDCARD_TOPIC, { qos: QOS }, function () {});
          });
  
          this.mqtt.on('message', function (topic, payload) {
            console.log("Message [%s] : %s", topic, payload);
  
            var match = DM_RESPONSE_TOPIC_RE.exec(topic);
  
            if (match) {
              _this._onDmResponse(match[1], match[2], payload);
            }
  
            /*let match = DM_REQUEST_RE.exec(topic);
             
            if(match){
              if(topic == DM_RESPONSE_TOPIC){
                this._onDmResponse(payload);
              } else{
                this._onDmRequest(topic, payload);
              }
            }*/
          });
        }
      }, {
        key: 'manageGateway',
        value: function manageGateway(lifetime, supportDeviceActions, supportFirmwareActions) {
          //this.type and this.id, are present in the parent Gateway Class.
          return this.manageDevice(this.type, this.id, lifetime, supportDeviceActions, supportFirmwareActions);
        }
      }, {
        key: 'manageDevice',
        value: function manageDevice(type, id, lifetime, supportDeviceActions, supportFirmwareActions) {
          if (!this.isConnected) {
            this.log.error("Client is not connected");
            //throw new Error("Client is not connected");
            //instead of throwing error, will emit 'error' event.
            this.emit('error', "Client is not connected");
          }
  
          var d = new Object();
  
          if ((0, _utilUtilJs.isDefined)(lifetime)) {
            if (!(0, _utilUtilJs.isNumber)(lifetime)) {
              throw new Error("lifetime must be a number");
            }
  
            if (lifetime < 3600) {
              throw new Error("lifetime cannot be less than 3600");
            }
  
            d.lifetime = lifetime;
          }
  
          if ((0, _utilUtilJs.isDefined)(supportDeviceActions) || (0, _utilUtilJs.isDefined)(supportFirmwareActions)) {
            d.supports = new Object();
  
            if ((0, _utilUtilJs.isDefined)(supportDeviceActions)) {
              if (!(0, _utilUtilJs.isBoolean)(supportDeviceActions)) {
                throw new Error("supportDeviceActions must be a boolean");
              }
  
              d.supports.deviceActions = supportDeviceActions;
            }
  
            if ((0, _utilUtilJs.isDefined)(supportFirmwareActions)) {
              if (!(0, _utilUtilJs.isBoolean)(supportFirmwareActions)) {
                throw new Error("supportFirmwareActions must be a boolean");
              }
  
              d.supports.firmwareActions = supportFirmwareActions;
            }
          }
  
          var payload = new Object();
          payload.d = d;
  
          var reqId = (0, _utilUtilJs.generateUUID)();
          payload.reqId = reqId;
          payload = JSON.stringify(payload);
  
          var builtTopic = (0, _format2['default'])(MANAGE_TOPIC, type, id);
  
          this._deviceRequests[reqId] = { action: MANAGE, topic: builtTopic, payload: payload };
  
          this.log.debug("Publishing manage request on topic [%s] with payload : %s", builtTopic, payload);
          this.mqtt.publish(builtTopic, payload, QOS);
  
          return reqId;
        }
      }, {
        key: 'unmanageGateway',
        value: function unmanageGateway() {
          //this.type and this.id, are present in the parent Gateway Class.
          return this.unmanageDevice(this.type, this.id);
        }
      }, {
        key: 'unmanageDevice',
        value: function unmanageDevice(type, id) {
          if (!this.isConnected) {
            this.log.error("Client is not connected");
            //throw new Error("Client is not connected");
            //instead of throwing error, will emit 'error' event.
            this.emit('error', "Client is not connected");
          }
  
          var payload = new Object();
  
          var reqId = (0, _utilUtilJs.generateUUID)();
          payload.reqId = reqId;
          payload = JSON.stringify(payload);
  
          var builtTopic = (0, _format2['default'])(UNMANAGE_TOPIC, type, id);
  
          this._deviceRequests[reqId] = { action: UNMANAGE, topic: builtTopic, payload: payload };
  
          this.log.debug("Publishing unmanage request on topic [%s] with payload : %s", builtTopic, payload);
          this.mqtt.publish(builtTopic, payload, QOS);
  
          return reqId;
        }
      }, {
        key: 'updateLocationGateway',
        value: function updateLocationGateway(latitude, longitude, elevation, accuracy) {
          //this.type and this.id, are present in the parent Gateway Class.
          return this.updateLocationDevice(this.type, this.id, latitude, longitude, elevation, accuracy);
        }
      }, {
        key: 'updateLocationDevice',
        value: function updateLocationDevice(type, id, latitude, longitude, elevation, accuracy) {
          if (!this.isConnected) {
            this.log.error("Client is not connected");
            //throw new Error("Client is not connected");
            //instead of throwing error, will emit 'error' event.
            this.emit('error', "Client is not connected");
          }
  
          if (!(0, _utilUtilJs.isDefined)(longitude) || !(0, _utilUtilJs.isDefined)(latitude)) {
            throw new Error("longitude and latitude are required for updating location");
          }
  
          if (!(0, _utilUtilJs.isNumber)(longitude) || !(0, _utilUtilJs.isNumber)(latitude)) {
            throw new Error("longitude and latitude must be numbers");
          }
  
          if (longitude < -180 || longitude > 180) {
            throw new Error("longitude cannot be less than -180 or greater than 180");
          }
  
          if (latitude < -90 || latitude > 90) {
            throw new Error("latitude cannot be less than -90 or greater than 90");
          }
  
          var d = new Object();
          d.longitude = longitude;
          d.latitude = latitude;
  
          if ((0, _utilUtilJs.isDefined)(elevation)) {
            if (!(0, _utilUtilJs.isNumber)(elevation)) {
              throw new Error("elevation must be a number");
            }
  
            d.elevation = elevation;
          }
  
          if ((0, _utilUtilJs.isDefined)(accuracy)) {
            if (!(0, _utilUtilJs.isNumber)(accuracy)) {
              throw new Error("accuracy must be a number");
            }
  
            d.accuracy = accuracy;
          }
  
          d.measuredDateTime = new Date().toISOString();
  
          var payload = new Object();
          payload.d = d;
  
          var reqId = (0, _utilUtilJs.generateUUID)();
          payload.reqId = reqId;
          payload = JSON.stringify(payload);
  
          var builtTopic = (0, _format2['default'])(UPDATE_LOCATION_TOPIC, type, id);
  
          this._deviceRequests[reqId] = { action: UPDATE_LOCATION, topic: builtTopic, payload: payload };
  
          this.log.debug("Publishing update location request on topic [%s] with payload : %s", builtTopic, payload);
          this.mqtt.publish(builtTopic, payload, QOS);
  
          return reqId;
        }
      }, {
        key: 'addErrorCodeGateway',
        value: function addErrorCodeGateway(errorCode) {
          //this.type and this.id, are present in the parent Gateway Class.
          return this.addErrorCodeDevice(this.type, this.id, errorCode);
        }
      }, {
        key: 'addErrorCodeDevice',
        value: function addErrorCodeDevice(type, id, errorCode) {
          if (!this.isConnected) {
            this.log.error("Client is not connected");
            //throw new Error("Client is not connected");
            //instead of throwing error, will emit 'error' event.
            this.emit('error', "Client is not connected");
          }
  
          if (!(0, _utilUtilJs.isDefined)(errorCode)) {
            throw new Error("error code is required for adding an error code");
          }
  
          if (!(0, _utilUtilJs.isNumber)(errorCode)) {
            throw new Error("error code must be a number");
          }
  
          var d = new Object();
          d.errorCode = errorCode;
  
          var payload = new Object();
          payload.d = d;
  
          var reqId = (0, _utilUtilJs.generateUUID)();
          payload.reqId = reqId;
          payload = JSON.stringify(payload);
  
          var builtTopic = (0, _format2['default'])(ADD_ERROR_CODE_TOPIC, type, id);
  
          this._deviceRequests[reqId] = { action: ADD_ERROR, topic: builtTopic, payload: payload };
  
          this.log.debug("Publishing add error code request on topic [%s] with payload : %s", builtTopic, payload);
          this.mqtt.publish(builtTopic, payload, QOS);
  
          return reqId;
        }
      }, {
        key: 'clearErrorCodesGateway',
        value: function clearErrorCodesGateway() {
          //this.type and this.id, are present in the parent Gateway Class.
          return this.clearErrorCodesDevice(this.type, this.id);
        }
      }, {
        key: 'clearErrorCodesDevice',
        value: function clearErrorCodesDevice(type, id) {
          if (!this.isConnected) {
            this.log.error("Client is not connected");
            //throw new Error("Client is not connected");
            //instead of throwing error, will emit 'error' event.
            this.emit('error', "Client is not connected");
          }
  
          var payload = new Object();
  
          var reqId = (0, _utilUtilJs.generateUUID)();
          payload.reqId = reqId;
          payload = JSON.stringify(payload);
  
          var builtTopic = (0, _format2['default'])(CLEAR_ERROR_CODES_TOPIC, type, id);
  
          this._deviceRequests[reqId] = { action: CLEAR_ERROR, topic: builtTopic, payload: payload };
  
          this.log.debug("Publishing clear error codes request on topic [%s] with payload : %s", builtTopic, payload);
          this.mqtt.publish(builtTopic, payload, QOS);
  
          return reqId;
        }
      }, {
        key: 'addLogGateway',
        value: function addLogGateway(message, severity, data) {
          return this.addLogDevice(this.type, this.id, message, severity, data);
        }
      }, {
        key: 'addLogDevice',
        value: function addLogDevice(type, id, message, severity, data) {
          if (!this.isConnected) {
            this.log.error("Client is not connected");
            //throw new Error("Client is not connected");
            //instead of throwing error, will emit 'error' event.
            this.emit('error', "Client is not connected");
          }
  
          if (!(0, _utilUtilJs.isDefined)(message) || !(0, _utilUtilJs.isDefined)(severity)) {
            throw new Error("message and severity are required for adding a log");
          }
  
          if (!(0, _utilUtilJs.isString)(message)) {
            throw new Error("message must be a string");
          }
  
          if (!(0, _utilUtilJs.isNumber)(severity)) {
            throw new Error("severity must be a number");
          }
  
          if (!(severity === 0 || severity === 1 || severity === 2)) {
            throw new Error("severity can only equal 0, 1, or 2");
          }
  
          var d = new Object();
          d.message = message;
          d.severity = severity;
          d.timestamp = new Date().toISOString();
  
          if ((0, _utilUtilJs.isDefined)(data)) {
            if (!(0, _utilUtilJs.isString)(data)) {
              throw new Error("data must be a string");
            }
  
            d.data = data;
          }
  
          var payload = new Object();
          payload.d = d;
  
          var reqId = (0, _utilUtilJs.generateUUID)();
          payload.reqId = reqId;
          payload = JSON.stringify(payload);
  
          var builtTopic = (0, _format2['default'])(ADD_LOG_TOPIC, type, id);
  
          this._deviceRequests[reqId] = { action: ADD_LOG, topic: builtTopic, payload: payload };
  
          this.log.debug("Publishing add log request on topic [%s] with payload : %s", builtTopic, payload);
          this.mqtt.publish(builtTopic, payload, QOS);
  
          return reqId;
        }
      }, {
        key: 'clearLogsGateway',
        value: function clearLogsGateway() {
          return this.clearLogsDevice(this.type, this.id);
        }
      }, {
        key: 'clearLogsDevice',
        value: function clearLogsDevice(type, id) {
          if (!this.isConnected) {
            this.log.error("Client is not connected");
            //throw new Error("Client is not connected");
            //instead of throwing error, will emit 'error' event.
            this.emit('error', "Client is not connected");
          }
  
          var payload = new Object();
  
          var reqId = (0, _utilUtilJs.generateUUID)();
          payload.reqId = reqId;
          payload = JSON.stringify(payload);
  
          var builtTopic = (0, _format2['default'])(CLEAR_LOGS_TOPIC, type, id);
  
          this._deviceRequests[reqId] = { action: CLEAR_LOG, topic: builtTopic, payload: payload };
  
          this.log.debug("Publishing clear logs request on topic [%s] with payload : %s", builtTopic, payload);
          this.mqtt.publish(builtTopic, payload, QOS);
  
          return reqId;
        }
      }, {
        key: 'respondDeviceAction',
        value: function respondDeviceAction(reqId, accept) {
          if (!this.isConnected) {
            this.log.error("Client is not connected");
            //throw new Error("Client is not connected");
            //instead of throwing error, will emit 'error' event.
            this.emit('error', "Client is not connected");
          }
  
          if (!(0, _utilUtilJs.isDefined)(reqId) || !(0, _utilUtilJs.isDefined)(accept)) {
            throw new Error("reqId and accept are required");
          }
  
          if (!(0, _utilUtilJs.isString)(reqId)) {
            throw new Error("reqId must be a string");
          }
  
          if (!(0, _utilUtilJs.isBoolean)(accept)) {
            throw new Error("accept must be a boolean");
          }
  
          var request = this._dmRequests[reqId];
          if (!(0, _utilUtilJs.isDefined)(request)) {
            throw new Error("unknown request : %s", reqId);
          }
  
          var rc;
          if (accept) {
            rc = 202;
          } else {
            rc = 500;
          }
  
          var payload = new Object();
          payload.rc = rc;
          payload.reqId = reqId;
          payload = JSON.stringify(payload);
  
          this.log.debug("Publishing device action response with payload : %s", payload);
          this.mqtt.publish(RESPONSE_TOPIC, payload, QOS);
  
          delete this._dmRequests[reqId];
  
          return this;
        }
      }, {
        key: '_onDmResponse',
        value: function _onDmResponse(type, id, payload) {
          payload = JSON.parse(payload);
          var reqId = payload.reqId;
          var rc = payload.rc;
  
          var request = this._deviceRequests[reqId];
          if (!(0, _utilUtilJs.isDefined)(request)) {
            throw new Error("unknown request : %s", reqId);
          }
  
          switch (request.action) {
            case MANAGE:
              if (rc == 200) {
                this.log.debug("[%s] Manage action completed for type : %s and id : %s with payload : %s", rc, type, id, request.payload);
              } else {
                this.log.error("[%s] Manage action failed for type : %s and id : %s with payload : %s", rc, type, id, request.payload);
              }
              break;
            case UNMANAGE:
              if (rc == 200) {
                this.log.debug("[%s] Unmanage action completed for type : %s and id : %s with payload : %s", rc, type, id, request.payload);
              } else {
                this.log.error("[%s] Unmanage action failed for type : %s and id : %s with payload : %s", rc, type, id, request.payload);
              }
              break;
            case UPDATE_LOCATION:
              if (rc == 200) {
                this.log.debug("[%s] Update location action completed for type : %s and id : %s with payload : %s", rc, type, id, request.payload);
              } else {
                this.log.error("[%s] Update location failed for type : %s and id : %s with payload : %s", rc, type, id, request.payload);
              }
              break;
            case ADD_LOG:
              if (rc == 200) {
                this.log.debug("[%s] Add log action completed for type : %s and id : %s with payload : %s", rc, type, id, request.payload);
              } else {
                this.log.error("[%s] Add log action failed for type : %s and id : %s with payload : %s", rc, type, id, request.payload);
              }
              break;
            case CLEAR_LOG:
              if (rc == 200) {
                this.log.debug("[%s] Clear logs action completed for type : %s and id : %s with payload : %s", rc, type, id, request.payload);
              } else {
                this.log.error("[%s] Clear logs action failed for type : %s and id : %s with payload : %s", rc, type, id, request.payload);
              }
              break;
            case ADD_ERROR:
              if (rc == 200) {
                this.log.debug("[%s] Add error code action completed for type : %s and id : %s with payload : %s", rc, type, id, request.payload);
              } else {
                this.log.error("[%s] Add error code action failed for type : %s and id : %s with payload : %s", rc, type, id, request.payload);
              }
              break;
            case CLEAR_ERROR:
              if (rc == 200) {
                this.log.debug("[%s] Clear error codes action completed for type : %s and id : %s with payload : %s", rc, type, id, request.payload);
              } else {
                this.log.error("[%s] Clear error codes action failed for type : %s and id : %s with payload : %s", rc, type, id, request.payload);
              }
              break;
            default:
              throw new Error("unknown action response");
          }
  
          this.emit('dmResponse', {
            reqId: reqId,
            type: type,
            id: id,
            action: request.action,
            rc: rc
          });
  
          delete this._deviceRequests[reqId];
  
          return this;
        }
      }, {
        key: '_onDmRequest',
        value: function _onDmRequest(topic, payload) {
          payload = JSON.parse(payload);
          var reqId = payload.reqId;
  
          this._dmRequests[reqId] = { topic: topic, payload: payload };
  
          var match = DM_ACTION_RE.exec(topic);
  
          if (match) {
            var type = match[1];
            var action = match[2];
  
            if (type == "firmware") {
              action = type + '_' + action;
            }
  
            this.emit('dmAction', {
              reqId: reqId,
              action: action
            });
          }
  
          return this;
        }
      }]);
  
      return ManagedGatewayClient;
    })(_GatewayClient2['default']);
  
    module.exports = ManagedGatewayClient;
  });
  },{"../util/util.js":9,"./GatewayClient.js":5,"format":27}],8:[function(require,module,exports){
  (function (global, factory) {
    if (typeof define === 'function' && define.amd) {
      define(['exports', 'module', './clients/DeviceClient.js', './clients/ManagedDeviceClient.js', './clients/GatewayClient.js', './clients/ManagedGatewayClient.js', './clients/ApplicationClient.js'], factory);
    } else if (typeof exports !== 'undefined' && typeof module !== 'undefined') {
      factory(exports, module, require('./clients/DeviceClient.js'), require('./clients/ManagedDeviceClient.js'), require('./clients/GatewayClient.js'), require('./clients/ManagedGatewayClient.js'), require('./clients/ApplicationClient.js'));
    } else {
      var mod = {
        exports: {}
      };
      factory(mod.exports, mod, global.DeviceClient, global.ManagedDeviceClient, global.GatewayClient, global.ManagedGatewayClient, global.ApplicationClient);
      global.iotfClient = mod.exports;
    }
  })(this, function (exports, module, _clientsDeviceClientJs, _clientsManagedDeviceClientJs, _clientsGatewayClientJs, _clientsManagedGatewayClientJs, _clientsApplicationClientJs) {
    /**
     *****************************************************************************
     Copyright (c) 2014, 2015 IBM Corporation and other Contributors.
     All rights reserved. This program and the accompanying materials
     are made available under the terms of the Eclipse Public License v1.0
     which accompanies this distribution, and is available at
     http://www.eclipse.org/legal/epl-v10.html
     Contributors:
     Tim-Daniel Jacobi - Initial Contribution
     Jeffrey Dare
     *****************************************************************************
     *
     */
    'use strict';
  
    function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  
    var _IotfDevice = _interopRequireDefault(_clientsDeviceClientJs);
  
    var _IotfManagedDevice = _interopRequireDefault(_clientsManagedDeviceClientJs);
  
    var _IotfGateway = _interopRequireDefault(_clientsGatewayClientJs);
  
    var _IotfManagedGateway = _interopRequireDefault(_clientsManagedGatewayClientJs);
  
    var _IotfApplication = _interopRequireDefault(_clientsApplicationClientJs);
  
    module.exports = {
      IotfDevice: _IotfDevice['default'],
      IotfManagedDevice: _IotfManagedDevice['default'],
      IotfGateway: _IotfGateway['default'],
      IotfManagedGateway: _IotfManagedGateway['default'],
      IotfApplication: _IotfApplication['default']
    };
  });
  },{"./clients/ApplicationClient.js":2,"./clients/DeviceClient.js":4,"./clients/GatewayClient.js":5,"./clients/ManagedDeviceClient.js":6,"./clients/ManagedGatewayClient.js":7}],9:[function(require,module,exports){
  (function (__dirname){
  (function (global, factory) {
     if (typeof define === 'function' && define.amd) {
        define(['exports', 'fs'], factory);
     } else if (typeof exports !== 'undefined') {
        factory(exports, require('fs'));
     } else {
        var mod = {
           exports: {}
        };
        factory(mod.exports, global.fs);
        global.util = mod.exports;
     }
  })(this, function (exports, _fs) {
     /**
      *****************************************************************************
      Copyright (c) 2014, 2015 IBM Corporation and other Contributors.
      All rights reserved. This program and the accompanying materials
      are made available under the terms of the Eclipse Public License v1.0
      which accompanies this distribution, and is available at
      http://www.eclipse.org/legal/epl-v10.html
      Contributors:
      Tim-Daniel Jacobi - Initial Contribution
      Lokesh Haralakatta - Added method initializeMqttConfig
      *****************************************************************************
      *
      */
     'use strict';
  
     Object.defineProperty(exports, '__esModule', {
        value: true
     });
     exports.isString = isString;
     exports.isNumber = isNumber;
     exports.isBoolean = isBoolean;
     exports.isDefined = isDefined;
     exports.generateUUID = generateUUID;
     exports.initializeMqttConfig = initializeMqttConfig;
  
     function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  
     var _fs2 = _interopRequireDefault(_fs);
  
     function isString(value) {
        return typeof value === 'string';
     }
  
     function isNumber(value) {
        return typeof value === 'number';
     }
  
     function isBoolean(value) {
        return typeof value === 'boolean';
     }
  
     function isDefined(value) {
        return value !== undefined && value !== null;
     }
  
     var isBrowser = new Function("try {return this===window;}catch(e){ return false;}");
  
     exports.isBrowser = isBrowser;
     var isNode = new Function("try {return this===global;}catch(e){return false;}");
  
     exports.isNode = isNode;
  
     function generateUUID() {
        return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
           var r = Math.random() * 16 | 0,
               v = c == 'x' ? r : r & 0x3 | 0x8;
           return v.toString(16);
        });
     }
  
     function initializeMqttConfig(config) {
        var mqttConfig = {
           password: config['auth-token'],
           rejectUnauthorized: true
        };
        if (config['use-client-certs'] == true || config['use-client-certs'] == "true") {
           var serverCA = _fs2['default'].readFileSync(__dirname + '/IoTFoundation.pem');
           if (config['read-certs'] == true) {
              mqttConfig.ca = [config['client-ca'], serverCA];
              mqttConfig.cert = config['client-cert'];
              mqttConfig.key = config['client-key'];
           } else {
              if (isDefined(config['server-ca'])) {
                 serverCA = _fs2['default'].readFileSync(config['server-ca']);
              }
              if (isDefined(config['client-ca'])) {
                 mqttConfig.ca = [_fs2['default'].readFileSync(config['client-ca']), serverCA];
              } else {
                 throw new Error('[initializeMqttConfig] config must specify path to self-signed CA certificate');
              }
              if (isDefined(config['client-cert'])) {
                 mqttConfig.cert = _fs2['default'].readFileSync(config['client-cert']);
              } else {
                 throw new Error('[initializeMqttConfig] config must specify path to self-signed client certificate');
              }
              if (isDefined(config['client-key'])) {
                 mqttConfig.key = _fs2['default'].readFileSync(config['client-key']);
              } else {
                 throw new Error('[initializeMqttConfig] config must specify path to client key');
              }
              if (isDefined(config['client-key-passphrase'])) {
                 mqttConfig.passphrase = config['client-key-passphrase'];
              }
           }
           mqttConfig.servername = config['mqtt-server'];
           mqttConfig.protocol = "mqtt";
        }
        return mqttConfig;
     }
  });
  }).call(this,"/node_modules/ibmiotf/dist/util")
  },{"fs":95}],10:[function(require,module,exports){
  module.exports = require('./lib/axios');
  },{"./lib/axios":12}],11:[function(require,module,exports){
  'use strict';
  
  /*global ActiveXObject:true*/
  
  var defaults = require('./../defaults');
  var utils = require('./../utils');
  var buildUrl = require('./../helpers/buildUrl');
  var cookies = require('./../helpers/cookies');
  var parseHeaders = require('./../helpers/parseHeaders');
  var transformData = require('./../helpers/transformData');
  var urlIsSameOrigin = require('./../helpers/urlIsSameOrigin');
  
  module.exports = function xhrAdapter(resolve, reject, config) {
    // Transform request data
    var data = transformData(
      config.data,
      config.headers,
      config.transformRequest
    );
  
    // Merge headers
    var requestHeaders = utils.merge(
      defaults.headers.common,
      defaults.headers[config.method] || {},
      config.headers || {}
    );
  
    if (utils.isFormData(data)) {
      delete requestHeaders['Content-Type']; // Let the browser set it
    }
  
    // Create the request
    var request = new (XMLHttpRequest || ActiveXObject)('Microsoft.XMLHTTP');
    request.open(config.method.toUpperCase(), buildUrl(config.url, config.params), true);
  
    // Listen for ready state
    request.onreadystatechange = function () {
      if (request && request.readyState === 4) {
        // Prepare the response
        var responseHeaders = parseHeaders(request.getAllResponseHeaders());
        var responseData = ['text', ''].indexOf(config.responseType || '') !== -1 ? request.responseText : request.response;
        var response = {
          data: transformData(
            responseData,
            responseHeaders,
            config.transformResponse
          ),
          status: request.status,
          statusText: request.statusText,
          headers: responseHeaders,
          config: config
        };
  
        // Resolve or reject the Promise based on the status
        (request.status >= 200 && request.status < 300 ?
          resolve :
          reject)(response);
  
        // Clean up request
        request = null;
      }
    };
  
    // Add xsrf header
    var xsrfValue = urlIsSameOrigin(config.url) ?
        cookies.read(config.xsrfCookieName || defaults.xsrfCookieName) :
        undefined;
    if (xsrfValue) {
      requestHeaders[config.xsrfHeaderName || defaults.xsrfHeaderName] = xsrfValue;
    }
  
    // Add headers to the request
    utils.forEach(requestHeaders, function (val, key) {
      // Remove Content-Type if data is undefined
      if (!data && key.toLowerCase() === 'content-type') {
        delete requestHeaders[key];
      }
      // Otherwise add header to the request
      else {
        request.setRequestHeader(key, val);
      }
    });
  
    // Add withCredentials to request if needed
    if (config.withCredentials) {
      request.withCredentials = true;
    }
  
    // Add responseType to request if needed
    if (config.responseType) {
      try {
        request.responseType = config.responseType;
      } catch (e) {
        if (request.responseType !== 'json') {
          throw e;
        }
      }
    }
  
    if (utils.isArrayBuffer(data)) {
      data = new DataView(data);
    }
  
    // Send the request
    request.send(data);
  };
  
  },{"./../defaults":15,"./../helpers/buildUrl":16,"./../helpers/cookies":17,"./../helpers/parseHeaders":19,"./../helpers/transformData":21,"./../helpers/urlIsSameOrigin":22,"./../utils":23}],12:[function(require,module,exports){
  'use strict';
  
  var defaults = require('./defaults');
  var utils = require('./utils');
  var deprecatedMethod = require('./helpers/deprecatedMethod');
  var dispatchRequest = require('./core/dispatchRequest');
  var InterceptorManager = require('./core/InterceptorManager');
  
  // Polyfill ES6 Promise if needed
  (function () {
    // webpack is being used to set es6-promise to the native Promise
    // for the standalone build. It's necessary to make sure polyfill exists.
    var P = require('es6-promise');
    if (P && typeof P.polyfill === 'function') {
      P.polyfill();
    }
  })();
  
  var axios = module.exports = function axios(config) {
    config = utils.merge({
      method: 'get',
      headers: {},
      transformRequest: defaults.transformRequest,
      transformResponse: defaults.transformResponse
    }, config);
  
    // Don't allow overriding defaults.withCredentials
    config.withCredentials = config.withCredentials || defaults.withCredentials;
  
    // Hook up interceptors middleware
    var chain = [dispatchRequest, undefined];
    var promise = Promise.resolve(config);
  
    axios.interceptors.request.forEach(function (interceptor) {
      chain.unshift(interceptor.fulfilled, interceptor.rejected);
    });
  
    axios.interceptors.response.forEach(function (interceptor) {
      chain.push(interceptor.fulfilled, interceptor.rejected);
    });
  
    while (chain.length) {
      promise = promise.then(chain.shift(), chain.shift());
    }
  
    // Provide alias for success
    promise.success = function success(fn) {
      deprecatedMethod('success', 'then', 'https://github.com/mzabriskie/axios/blob/master/README.md#response-api');
  
      promise.then(function(response) {
        fn(response.data, response.status, response.headers, response.config);
      });
      return promise;
    };
  
    // Provide alias for error
    promise.error = function error(fn) {
      deprecatedMethod('error', 'catch', 'https://github.com/mzabriskie/axios/blob/master/README.md#response-api');
  
      promise.then(null, function(response) {
        fn(response.data, response.status, response.headers, response.config);
      });
      return promise;
    };
  
    return promise;
  };
  
  // Expose defaults
  axios.defaults = defaults;
  
  // Expose all/spread
  axios.all = function (promises) {
    return Promise.all(promises);
  };
  axios.spread = require('./helpers/spread');
  
  // Expose interceptors
  axios.interceptors = {
    request: new InterceptorManager(),
    response: new InterceptorManager()
  };
  
  // Provide aliases for supported request methods
  (function () {
    function createShortMethods() {
      utils.forEach(arguments, function (method) {
        axios[method] = function (url, config) {
          return axios(utils.merge(config || {}, {
            method: method,
            url: url
          }));
        };
      });
    }
  
    function createShortMethodsWithData() {
      utils.forEach(arguments, function (method) {
        axios[method] = function (url, data, config) {
          return axios(utils.merge(config || {}, {
            method: method,
            url: url,
            data: data
          }));
        };
      });
    }
  
    createShortMethods('delete', 'get', 'head');
    createShortMethodsWithData('post', 'put', 'patch');
  })();
  
  },{"./core/InterceptorManager":13,"./core/dispatchRequest":14,"./defaults":15,"./helpers/deprecatedMethod":18,"./helpers/spread":20,"./utils":23,"es6-promise":24}],13:[function(require,module,exports){
  'use strict';
  
  var utils = require('./../utils');
  
  function InterceptorManager() {
    this.handlers = [];
  }
  
  /**
   * Add a new interceptor to the stack
   *
   * @param {Function} fulfilled The function to handle `then` for a `Promise`
   * @param {Function} rejected The function to handle `reject` for a `Promise`
   *
   * @return {Number} An ID used to remove interceptor later
   */
  InterceptorManager.prototype.use = function (fulfilled, rejected) {
    this.handlers.push({
      fulfilled: fulfilled,
      rejected: rejected
    });
    return this.handlers.length - 1;
  };
  
  /**
   * Remove an interceptor from the stack
   *
   * @param {Number} id The ID that was returned by `use`
   */
  InterceptorManager.prototype.eject = function (id) {
    if (this.handlers[id]) {
      this.handlers[id] = null;
    }
  };
  
  /**
   * Iterate over all the registered interceptors
   *
   * This method is particularly useful for skipping over any
   * interceptors that may have become `null` calling `remove`.
   *
   * @param {Function} fn The function to call for each interceptor
   */
  InterceptorManager.prototype.forEach = function (fn) {
    utils.forEach(this.handlers, function (h) {
      if (h !== null) {
        fn(h);
      }
    });
  };
  
  module.exports = InterceptorManager;
  
  },{"./../utils":23}],14:[function(require,module,exports){
  (function (process){
  'use strict';
  
  /**
   * Dispatch a request to the server using whichever adapter
   * is supported by the current environment.
   *
   * @param {object} config The config that is to be used for the request
   * @returns {Promise} The Promise to be fulfilled
   */
  module.exports = function dispatchRequest(config) {
    return new Promise(function (resolve, reject) {
      try {
        // For browsers use XHR adapter
        if (typeof window !== 'undefined') {
          require('../adapters/xhr')(resolve, reject, config);
        }
        // For node use HTTP adapter
        else if (typeof process !== 'undefined') {
          require('../adapters/http')(resolve, reject, config);
        }
      } catch (e) {
        reject(e);
      }
    });
  };
  
  
  }).call(this,require('_process'))
  },{"../adapters/http":11,"../adapters/xhr":11,"_process":103}],15:[function(require,module,exports){
  'use strict';
  
  var utils = require('./utils');
  
  var PROTECTION_PREFIX = /^\)\]\}',?\n/;
  var DEFAULT_CONTENT_TYPE = {
    'Content-Type': 'application/x-www-form-urlencoded'
  };
  
  module.exports = {
    transformRequest: [function (data, headers) {
      if(utils.isFormData(data)) {
        return data;
      }
      if (utils.isArrayBuffer(data)) {
        return data;
      }
      if (utils.isArrayBufferView(data)) {
        return data.buffer;
      }
      if (utils.isObject(data) && !utils.isFile(data) && !utils.isBlob(data)) {
        // Set application/json if no Content-Type has been specified
        if (!utils.isUndefined(headers) && utils.isUndefined(headers['Content-Type'])) {
          headers['Content-Type'] = 'application/json;charset=utf-8';
        }
        return JSON.stringify(data);
      }
      return data;
    }],
  
    transformResponse: [function (data) {
      if (typeof data === 'string') {
        data = data.replace(PROTECTION_PREFIX, '');
        try {
          data = JSON.parse(data);
        } catch (e) {}
      }
      return data;
    }],
  
    headers: {
      common: {
        'Accept': 'application/json, text/plain, */*'
      },
      patch: utils.merge(DEFAULT_CONTENT_TYPE),
      post: utils.merge(DEFAULT_CONTENT_TYPE),
      put: utils.merge(DEFAULT_CONTENT_TYPE)
    },
  
    xsrfCookieName: 'XSRF-TOKEN',
    xsrfHeaderName: 'X-XSRF-TOKEN'
  };
  
  },{"./utils":23}],16:[function(require,module,exports){
  'use strict';
  
  var utils = require('./../utils');
  
  function encode(val) {
    return encodeURIComponent(val).
      replace(/%40/gi, '@').
      replace(/%3A/gi, ':').
      replace(/%24/g, '$').
      replace(/%2C/gi, ',').
      replace(/%20/g, '+');
  }
  
  /**
   * Build a URL by appending params to the end
   *
   * @param {string} url The base of the url (e.g., http://www.google.com)
   * @param {object} [params] The params to be appended
   * @returns {string} The formatted url
   */
  module.exports = function buildUrl(url, params) {
    if (!params) {
      return url;
    }
  
    var parts = [];
  
    utils.forEach(params, function (val, key) {
      if (val === null || typeof val === 'undefined') {
        return;
      }
      if (!utils.isArray(val)) {
        val = [val];
      }
  
      utils.forEach(val, function (v) {
        if (utils.isDate(v)) {
          v = v.toISOString();
        }
        else if (utils.isObject(v)) {
          v = JSON.stringify(v);
        }
        parts.push(encode(key) + '=' + encode(v));
      });
    });
  
    if (parts.length > 0) {
      url += (url.indexOf('?') === -1 ? '?' : '&') + parts.join('&');
    }
  
    return url;
  };
  
  },{"./../utils":23}],17:[function(require,module,exports){
  'use strict';
  
  var utils = require('./../utils');
  
  module.exports = {
    write: function write(name, value, expires, path, domain, secure) {
      var cookie = [];
      cookie.push(name + '=' + encodeURIComponent(value));
  
      if (utils.isNumber(expires)) {
        cookie.push('expires=' + new Date(expires).toGMTString());
      }
  
      if (utils.isString(path)) {
        cookie.push('path=' + path);
      }
  
      if (utils.isString(domain)) {
        cookie.push('domain=' + domain);
      }
  
      if (secure === true) {
        cookie.push('secure');
      }
  
      document.cookie = cookie.join('; ');
    },
  
    read: function read(name) {
      var match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)'));
      return (match ? decodeURIComponent(match[3]) : null);
    },
  
    remove: function remove(name) {
      this.write(name, '', Date.now() - 86400000);
    }
  };
  
  },{"./../utils":23}],18:[function(require,module,exports){
  'use strict';
  
  /**
   * Supply a warning to the developer that a method they are using
   * has been deprecated.
   *
   * @param {string} method The name of the deprecated method
   * @param {string} [instead] The alternate method to use if applicable
   * @param {string} [docs] The documentation URL to get further details
   */
  module.exports = function deprecatedMethod(method, instead, docs) {
    try {
      console.warn(
        'DEPRECATED method `' + method + '`.' +
        (instead ? ' Use `' + instead + '` instead.' : '') +
        ' This method will be removed in a future release.');
  
      if (docs) {
        console.warn('For more information about usage see ' + docs);
      }
    } catch (e) {}
  };
  
  },{}],19:[function(require,module,exports){
  'use strict';
  
  var utils = require('./../utils');
  
  /**
   * Parse headers into an object
   *
   * ```
   * Date: Wed, 27 Aug 2014 08:58:49 GMT
   * Content-Type: application/json
   * Connection: keep-alive
   * Transfer-Encoding: chunked
   * ```
   *
   * @param {String} headers Headers needing to be parsed
   * @returns {Object} Headers parsed into an object
   */
  module.exports = function parseHeaders(headers) {
    var parsed = {}, key, val, i;
  
    if (!headers) { return parsed; }
  
    utils.forEach(headers.split('\n'), function(line) {
      i = line.indexOf(':');
      key = utils.trim(line.substr(0, i)).toLowerCase();
      val = utils.trim(line.substr(i + 1));
  
      if (key) {
        parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
      }
    });
  
    return parsed;
  };
  
  },{"./../utils":23}],20:[function(require,module,exports){
  'use strict';
  
  /**
   * Syntactic sugar for invoking a function and expanding an array for arguments.
   *
   * Common use case would be to use `Function.prototype.apply`.
   *
   *  ```js
   *  function f(x, y, z) {}
   *  var args = [1, 2, 3];
   *  f.apply(null, args);
   *  ```
   *
   * With `spread` this example can be re-written.
   *
   *  ```js
   *  spread(function(x, y, z) {})([1, 2, 3]);
   *  ```
   *
   * @param {Function} callback
   * @returns {Function}
   */
  module.exports = function spread(callback) {
    return function (arr) {
      callback.apply(null, arr);
    };
  };
  
  },{}],21:[function(require,module,exports){
  'use strict';
  
  var utils = require('./../utils');
  
  /**
   * Transform the data for a request or a response
   *
   * @param {Object|String} data The data to be transformed
   * @param {Array} headers The headers for the request or response
   * @param {Array|Function} fns A single function or Array of functions
   * @returns {*} The resulting transformed data
   */
  module.exports = function transformData(data, headers, fns) {
    utils.forEach(fns, function (fn) {
      data = fn(data, headers);
    });
  
    return data;
  };
  
  },{"./../utils":23}],22:[function(require,module,exports){
  'use strict';
  
  var utils = require('./../utils');
  var msie = /(msie|trident)/i.test(navigator.userAgent);
  var urlParsingNode = document.createElement('a');
  var originUrl;
  
  /**
   * Parse a URL to discover it's components
   *
   * @param {String} url The URL to be parsed
   * @returns {Object}
   */
  function urlResolve(url) {
    var href = url;
  
    if (msie) {
      // IE needs attribute set twice to normalize properties
      urlParsingNode.setAttribute('href', href);
      href = urlParsingNode.href;
    }
  
    urlParsingNode.setAttribute('href', href);
  
    // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
    return {
      href: urlParsingNode.href,
      protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
      host: urlParsingNode.host,
      search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
      hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
      hostname: urlParsingNode.hostname,
      port: urlParsingNode.port,
      pathname: (urlParsingNode.pathname.charAt(0) === '/') ?
                urlParsingNode.pathname :
                '/' + urlParsingNode.pathname
    };
  }
  
  originUrl = urlResolve(window.location.href);
  
  /**
   * Determine if a URL shares the same origin as the current location
   *
   * @param {String} requestUrl The URL to test
   * @returns {boolean} True if URL shares the same origin, otherwise false
   */
  module.exports = function urlIsSameOrigin(requestUrl) {
    var parsed = (utils.isString(requestUrl)) ? urlResolve(requestUrl) : requestUrl;
    return (parsed.protocol === originUrl.protocol &&
          parsed.host === originUrl.host);
  };
  
  },{"./../utils":23}],23:[function(require,module,exports){
  'use strict';
  
  /*global toString:true*/
  
  // utils is a library of generic helper functions non-specific to axios
  
  var toString = Object.prototype.toString;
  
  /**
   * Determine if a value is an Array
   *
   * @param {Object} val The value to test
   * @returns {boolean} True if value is an Array, otherwise false
   */
  function isArray(val) {
    return toString.call(val) === '[object Array]';
  }
  
  /**
   * Determine if a value is an ArrayBuffer
   *
   * @param {Object} val The value to test
   * @returns {boolean} True if value is an ArrayBuffer, otherwise false
   */
  function isArrayBuffer(val) {
    return toString.call(val) === '[object ArrayBuffer]';
  }
  
  /**
   * Determine if a value is a FormData
   *
   * @param {Object} val The value to test
   * @returns {boolean} True if value is an FormData, otherwise false
   */
  function isFormData(val) {
    return toString.call(val) === '[object FormData]';
  }
  
  /**
   * Determine if a value is a view on an ArrayBuffer
   *
   * @param {Object} val The value to test
   * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false
   */
  function isArrayBufferView(val) {
    if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) {
      return ArrayBuffer.isView(val);
    } else {
      return (val) && (val.buffer) && (val.buffer instanceof ArrayBuffer);
    }
  }
  
  /**
   * Determine if a value is a String
   *
   * @param {Object} val The value to test
   * @returns {boolean} True if value is a String, otherwise false
   */
  function isString(val) {
    return typeof val === 'string';
  }
  
  /**
   * Determine if a value is a Number
   *
   * @param {Object} val The value to test
   * @returns {boolean} True if value is a Number, otherwise false
   */
  function isNumber(val) {
    return typeof val === 'number';
  }
  
  /**
   * Determine if a value is undefined
   *
   * @param {Object} val The value to test
   * @returns {boolean} True if the value is undefined, otherwise false
   */
  function isUndefined(val) {
    return typeof val === 'undefined';
  }
  
  /**
   * Determine if a value is an Object
   *
   * @param {Object} val The value to test
   * @returns {boolean} True if value is an Object, otherwise false
   */
  function isObject(val) {
    return val !== null && typeof val === 'object';
  }
  
  /**
   * Determine if a value is a Date
   *
   * @param {Object} val The value to test
   * @returns {boolean} True if value is a Date, otherwise false
   */
  function isDate(val) {
    return toString.call(val) === '[object Date]';
  }
  
  /**
   * Determine if a value is a File
   *
   * @param {Object} val The value to test
   * @returns {boolean} True if value is a File, otherwise false
   */
  function isFile(val) {
    return toString.call(val) === '[object File]';
  }
  
  /**
   * Determine if a value is a Blob
   *
   * @param {Object} val The value to test
   * @returns {boolean} True if value is a Blob, otherwise false
   */
  function isBlob(val) {
    return toString.call(val) === '[object Blob]';
  }
  
  /**
   * Trim excess whitespace off the beginning and end of a string
   *
   * @param {String} str The String to trim
   * @returns {String} The String freed of excess whitespace
   */
  function trim(str) {
    return str.replace(/^\s*/, '').replace(/\s*$/, '');
  }
  
  /**
   * Iterate over an Array or an Object invoking a function for each item.
   *
   * If `obj` is an Array or arguments callback will be called passing
   * the value, index, and complete array for each item.
   *
   * If 'obj' is an Object callback will be called passing
   * the value, key, and complete object for each property.
   *
   * @param {Object|Array} obj The object to iterate
   * @param {Function} fn The callback to invoke for each item
   */
  function forEach(obj, fn) {
    // Don't bother if no value provided
    if (obj === null || typeof obj === 'undefined') {
      return;
    }
  
    // Check if obj is array-like
    var isArrayLike = isArray(obj) || (typeof obj === 'object' && !isNaN(obj.length));
  
    // Force an array if not already something iterable
    if (typeof obj !== 'object' && !isArrayLike) {
      obj = [obj];
    }
  
    // Iterate over array values
    if (isArrayLike) {
      for (var i = 0, l = obj.length; i < l; i++) {
        fn.call(null, obj[i], i, obj);
      }
    }
    // Iterate over object keys
    else {
      for (var key in obj) {
        if (obj.hasOwnProperty(key)) {
          fn.call(null, obj[key], key, obj);
        }
      }
    }
  }
  
  /**
   * Accepts varargs expecting each argument to be an object, then
   * immutably merges the properties of each object and returns result.
   *
   * When multiple objects contain the same key the later object in
   * the arguments list will take precedence.
   *
   * Example:
   *
   * ```js
   * var result = merge({foo: 123}, {foo: 456});
   * console.log(result.foo); // outputs 456
   * ```
   *
   * @param {Object} obj1 Object to merge
   * @returns {Object} Result of all merge properties
   */
  function merge(/*obj1, obj2, obj3, ...*/) {
    var result = {};
    forEach(arguments, function (obj) {
      forEach(obj, function (val, key) {
        result[key] = val;
      });
    });
    return result;
  }
  
  module.exports = {
    isArray: isArray,
    isArrayBuffer: isArrayBuffer,
    isFormData: isFormData,
    isArrayBufferView: isArrayBufferView,
    isString: isString,
    isNumber: isNumber,
    isObject: isObject,
    isUndefined: isUndefined,
    isDate: isDate,
    isFile: isFile,
    isBlob: isBlob,
    forEach: forEach,
    merge: merge,
    trim: trim
  };
  
  },{}],24:[function(require,module,exports){
  (function (process,global){
  /*!
   * @overview es6-promise - a tiny implementation of Promises/A+.
   * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)
   * @license   Licensed under MIT license
   *            See https://raw.githubusercontent.com/jakearchibald/es6-promise/master/LICENSE
   * @version   2.3.0
   */
  
  (function() {
      "use strict";
      function lib$es6$promise$utils$$objectOrFunction(x) {
        return typeof x === 'function' || (typeof x === 'object' && x !== null);
      }
  
      function lib$es6$promise$utils$$isFunction(x) {
        return typeof x === 'function';
      }
  
      function lib$es6$promise$utils$$isMaybeThenable(x) {
        return typeof x === 'object' && x !== null;
      }
  
      var lib$es6$promise$utils$$_isArray;
      if (!Array.isArray) {
        lib$es6$promise$utils$$_isArray = function (x) {
          return Object.prototype.toString.call(x) === '[object Array]';
        };
      } else {
        lib$es6$promise$utils$$_isArray = Array.isArray;
      }
  
      var lib$es6$promise$utils$$isArray = lib$es6$promise$utils$$_isArray;
      var lib$es6$promise$asap$$len = 0;
      var lib$es6$promise$asap$$toString = {}.toString;
      var lib$es6$promise$asap$$vertxNext;
      var lib$es6$promise$asap$$customSchedulerFn;
  
      var lib$es6$promise$asap$$asap = function asap(callback, arg) {
        lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len] = callback;
        lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len + 1] = arg;
        lib$es6$promise$asap$$len += 2;
        if (lib$es6$promise$asap$$len === 2) {
          // If len is 2, that means that we need to schedule an async flush.
          // If additional callbacks are queued before the queue is flushed, they
          // will be processed by this flush that we are scheduling.
          if (lib$es6$promise$asap$$customSchedulerFn) {
            lib$es6$promise$asap$$customSchedulerFn(lib$es6$promise$asap$$flush);
          } else {
            lib$es6$promise$asap$$scheduleFlush();
          }
        }
      }
  
      function lib$es6$promise$asap$$setScheduler(scheduleFn) {
        lib$es6$promise$asap$$customSchedulerFn = scheduleFn;
      }
  
      function lib$es6$promise$asap$$setAsap(asapFn) {
        lib$es6$promise$asap$$asap = asapFn;
      }
  
      var lib$es6$promise$asap$$browserWindow = (typeof window !== 'undefined') ? window : undefined;
      var lib$es6$promise$asap$$browserGlobal = lib$es6$promise$asap$$browserWindow || {};
      var lib$es6$promise$asap$$BrowserMutationObserver = lib$es6$promise$asap$$browserGlobal.MutationObserver || lib$es6$promise$asap$$browserGlobal.WebKitMutationObserver;
      var lib$es6$promise$asap$$isNode = typeof process !== 'undefined' && {}.toString.call(process) === '[object process]';
  
      // test for web worker but not in IE10
      var lib$es6$promise$asap$$isWorker = typeof Uint8ClampedArray !== 'undefined' &&
        typeof importScripts !== 'undefined' &&
        typeof MessageChannel !== 'undefined';
  
      // node
      function lib$es6$promise$asap$$useNextTick() {
        var nextTick = process.nextTick;
        // node version 0.10.x displays a deprecation warning when nextTick is used recursively
        // setImmediate should be used instead instead
        var version = process.versions.node.match(/^(?:(\d+)\.)?(?:(\d+)\.)?(\*|\d+)$/);
        if (Array.isArray(version) && version[1] === '0' && version[2] === '10') {
          nextTick = setImmediate;
        }
        return function() {
          nextTick(lib$es6$promise$asap$$flush);
        };
      }
  
      // vertx
      function lib$es6$promise$asap$$useVertxTimer() {
        return function() {
          lib$es6$promise$asap$$vertxNext(lib$es6$promise$asap$$flush);
        };
      }
  
      function lib$es6$promise$asap$$useMutationObserver() {
        var iterations = 0;
        var observer = new lib$es6$promise$asap$$BrowserMutationObserver(lib$es6$promise$asap$$flush);
        var node = document.createTextNode('');
        observer.observe(node, { characterData: true });
  
        return function() {
          node.data = (iterations = ++iterations % 2);
        };
      }
  
      // web worker
      function lib$es6$promise$asap$$useMessageChannel() {
        var channel = new MessageChannel();
        channel.port1.onmessage = lib$es6$promise$asap$$flush;
        return function () {
          channel.port2.postMessage(0);
        };
      }
  
      function lib$es6$promise$asap$$useSetTimeout() {
        return function() {
          setTimeout(lib$es6$promise$asap$$flush, 1);
        };
      }
  
      var lib$es6$promise$asap$$queue = new Array(1000);
      function lib$es6$promise$asap$$flush() {
        for (var i = 0; i < lib$es6$promise$asap$$len; i+=2) {
          var callback = lib$es6$promise$asap$$queue[i];
          var arg = lib$es6$promise$asap$$queue[i+1];
  
          callback(arg);
  
          lib$es6$promise$asap$$queue[i] = undefined;
          lib$es6$promise$asap$$queue[i+1] = undefined;
        }
  
        lib$es6$promise$asap$$len = 0;
      }
  
      function lib$es6$promise$asap$$attemptVertex() {
        try {
          var r = require;
          var vertx = r('vertx');
          lib$es6$promise$asap$$vertxNext = vertx.runOnLoop || vertx.runOnContext;
          return lib$es6$promise$asap$$useVertxTimer();
        } catch(e) {
          return lib$es6$promise$asap$$useSetTimeout();
        }
      }
  
      var lib$es6$promise$asap$$scheduleFlush;
      // Decide what async method to use to triggering processing of queued callbacks:
      if (lib$es6$promise$asap$$isNode) {
        lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useNextTick();
      } else if (lib$es6$promise$asap$$BrowserMutationObserver) {
        lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMutationObserver();
      } else if (lib$es6$promise$asap$$isWorker) {
        lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMessageChannel();
      } else if (lib$es6$promise$asap$$browserWindow === undefined && typeof require === 'function') {
        lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$attemptVertex();
      } else {
        lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useSetTimeout();
      }
  
      function lib$es6$promise$$internal$$noop() {}
  
      var lib$es6$promise$$internal$$PENDING   = void 0;
      var lib$es6$promise$$internal$$FULFILLED = 1;
      var lib$es6$promise$$internal$$REJECTED  = 2;
  
      var lib$es6$promise$$internal$$GET_THEN_ERROR = new lib$es6$promise$$internal$$ErrorObject();
  
      function lib$es6$promise$$internal$$selfFullfillment() {
        return new TypeError("You cannot resolve a promise with itself");
      }
  
      function lib$es6$promise$$internal$$cannotReturnOwn() {
        return new TypeError('A promises callback cannot return that same promise.');
      }
  
      function lib$es6$promise$$internal$$getThen(promise) {
        try {
          return promise.then;
        } catch(error) {
          lib$es6$promise$$internal$$GET_THEN_ERROR.error = error;
          return lib$es6$promise$$internal$$GET_THEN_ERROR;
        }
      }
  
      function lib$es6$promise$$internal$$tryThen(then, value, fulfillmentHandler, rejectionHandler) {
        try {
          then.call(value, fulfillmentHandler, rejectionHandler);
        } catch(e) {
          return e;
        }
      }
  
      function lib$es6$promise$$internal$$handleForeignThenable(promise, thenable, then) {
         lib$es6$promise$asap$$asap(function(promise) {
          var sealed = false;
          var error = lib$es6$promise$$internal$$tryThen(then, thenable, function(value) {
            if (sealed) { return; }
            sealed = true;
            if (thenable !== value) {
              lib$es6$promise$$internal$$resolve(promise, value);
            } else {
              lib$es6$promise$$internal$$fulfill(promise, value);
            }
          }, function(reason) {
            if (sealed) { return; }
            sealed = true;
  
            lib$es6$promise$$internal$$reject(promise, reason);
          }, 'Settle: ' + (promise._label || ' unknown promise'));
  
          if (!sealed && error) {
            sealed = true;
            lib$es6$promise$$internal$$reject(promise, error);
          }
        }, promise);
      }
  
      function lib$es6$promise$$internal$$handleOwnThenable(promise, thenable) {
        if (thenable._state === lib$es6$promise$$internal$$FULFILLED) {
          lib$es6$promise$$internal$$fulfill(promise, thenable._result);
        } else if (thenable._state === lib$es6$promise$$internal$$REJECTED) {
          lib$es6$promise$$internal$$reject(promise, thenable._result);
        } else {
          lib$es6$promise$$internal$$subscribe(thenable, undefined, function(value) {
            lib$es6$promise$$internal$$resolve(promise, value);
          }, function(reason) {
            lib$es6$promise$$internal$$reject(promise, reason);
          });
        }
      }
  
      function lib$es6$promise$$internal$$handleMaybeThenable(promise, maybeThenable) {
        if (maybeThenable.constructor === promise.constructor) {
          lib$es6$promise$$internal$$handleOwnThenable(promise, maybeThenable);
        } else {
          var then = lib$es6$promise$$internal$$getThen(maybeThenable);
  
          if (then === lib$es6$promise$$internal$$GET_THEN_ERROR) {
            lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$GET_THEN_ERROR.error);
          } else if (then === undefined) {
            lib$es6$promise$$internal$$fulfill(promise, maybeThenable);
          } else if (lib$es6$promise$utils$$isFunction(then)) {
            lib$es6$promise$$internal$$handleForeignThenable(promise, maybeThenable, then);
          } else {
            lib$es6$promise$$internal$$fulfill(promise, maybeThenable);
          }
        }
      }
  
      function lib$es6$promise$$internal$$resolve(promise, value) {
        if (promise === value) {
          lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$selfFullfillment());
        } else if (lib$es6$promise$utils$$objectOrFunction(value)) {
          lib$es6$promise$$internal$$handleMaybeThenable(promise, value);
        } else {
          lib$es6$promise$$internal$$fulfill(promise, value);
        }
      }
  
      function lib$es6$promise$$internal$$publishRejection(promise) {
        if (promise._onerror) {
          promise._onerror(promise._result);
        }
  
        lib$es6$promise$$internal$$publish(promise);
      }
  
      function lib$es6$promise$$internal$$fulfill(promise, value) {
        if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; }
  
        promise._result = value;
        promise._state = lib$es6$promise$$internal$$FULFILLED;
  
        if (promise._subscribers.length !== 0) {
          lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, promise);
        }
      }
  
      function lib$es6$promise$$internal$$reject(promise, reason) {
        if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; }
        promise._state = lib$es6$promise$$internal$$REJECTED;
        promise._result = reason;
  
        lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publishRejection, promise);
      }
  
      function lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection) {
        var subscribers = parent._subscribers;
        var length = subscribers.length;
  
        parent._onerror = null;
  
        subscribers[length] = child;
        subscribers[length + lib$es6$promise$$internal$$FULFILLED] = onFulfillment;
        subscribers[length + lib$es6$promise$$internal$$REJECTED]  = onRejection;
  
        if (length === 0 && parent._state) {
          lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, parent);
        }
      }
  
      function lib$es6$promise$$internal$$publish(promise) {
        var subscribers = promise._subscribers;
        var settled = promise._state;
  
        if (subscribers.length === 0) { return; }
  
        var child, callback, detail = promise._result;
  
        for (var i = 0; i < subscribers.length; i += 3) {
          child = subscribers[i];
          callback = subscribers[i + settled];
  
          if (child) {
            lib$es6$promise$$internal$$invokeCallback(settled, child, callback, detail);
          } else {
            callback(detail);
          }
        }
  
        promise._subscribers.length = 0;
      }
  
      function lib$es6$promise$$internal$$ErrorObject() {
        this.error = null;
      }
  
      var lib$es6$promise$$internal$$TRY_CATCH_ERROR = new lib$es6$promise$$internal$$ErrorObject();
  
      function lib$es6$promise$$internal$$tryCatch(callback, detail) {
        try {
          return callback(detail);
        } catch(e) {
          lib$es6$promise$$internal$$TRY_CATCH_ERROR.error = e;
          return lib$es6$promise$$internal$$TRY_CATCH_ERROR;
        }
      }
  
      function lib$es6$promise$$internal$$invokeCallback(settled, promise, callback, detail) {
        var hasCallback = lib$es6$promise$utils$$isFunction(callback),
            value, error, succeeded, failed;
  
        if (hasCallback) {
          value = lib$es6$promise$$internal$$tryCatch(callback, detail);
  
          if (value === lib$es6$promise$$internal$$TRY_CATCH_ERROR) {
            failed = true;
            error = value.error;
            value = null;
          } else {
            succeeded = true;
          }
  
          if (promise === value) {
            lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$cannotReturnOwn());
            return;
          }
  
        } else {
          value = detail;
          succeeded = true;
        }
  
        if (promise._state !== lib$es6$promise$$internal$$PENDING) {
          // noop
        } else if (hasCallback && succeeded) {
          lib$es6$promise$$internal$$resolve(promise, value);
        } else if (failed) {
          lib$es6$promise$$internal$$reject(promise, error);
        } else if (settled === lib$es6$promise$$internal$$FULFILLED) {
          lib$es6$promise$$internal$$fulfill(promise, value);
        } else if (settled === lib$es6$promise$$internal$$REJECTED) {
          lib$es6$promise$$internal$$reject(promise, value);
        }
      }
  
      function lib$es6$promise$$internal$$initializePromise(promise, resolver) {
        try {
          resolver(function resolvePromise(value){
            lib$es6$promise$$internal$$resolve(promise, value);
          }, function rejectPromise(reason) {
            lib$es6$promise$$internal$$reject(promise, reason);
          });
        } catch(e) {
          lib$es6$promise$$internal$$reject(promise, e);
        }
      }
  
      function lib$es6$promise$enumerator$$Enumerator(Constructor, input) {
        var enumerator = this;
  
        enumerator._instanceConstructor = Constructor;
        enumerator.promise = new Constructor(lib$es6$promise$$internal$$noop);
  
        if (enumerator._validateInput(input)) {
          enumerator._input     = input;
          enumerator.length     = input.length;
          enumerator._remaining = input.length;
  
          enumerator._init();
  
          if (enumerator.length === 0) {
            lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result);
          } else {
            enumerator.length = enumerator.length || 0;
            enumerator._enumerate();
            if (enumerator._remaining === 0) {
              lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result);
            }
          }
        } else {
          lib$es6$promise$$internal$$reject(enumerator.promise, enumerator._validationError());
        }
      }
  
      lib$es6$promise$enumerator$$Enumerator.prototype._validateInput = function(input) {
        return lib$es6$promise$utils$$isArray(input);
      };
  
      lib$es6$promise$enumerator$$Enumerator.prototype._validationError = function() {
        return new Error('Array Methods must be provided an Array');
      };
  
      lib$es6$promise$enumerator$$Enumerator.prototype._init = function() {
        this._result = new Array(this.length);
      };
  
      var lib$es6$promise$enumerator$$default = lib$es6$promise$enumerator$$Enumerator;
  
      lib$es6$promise$enumerator$$Enumerator.prototype._enumerate = function() {
        var enumerator = this;
  
        var length  = enumerator.length;
        var promise = enumerator.promise;
        var input   = enumerator._input;
  
        for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) {
          enumerator._eachEntry(input[i], i);
        }
      };
  
      lib$es6$promise$enumerator$$Enumerator.prototype._eachEntry = function(entry, i) {
        var enumerator = this;
        var c = enumerator._instanceConstructor;
  
        if (lib$es6$promise$utils$$isMaybeThenable(entry)) {
          if (entry.constructor === c && entry._state !== lib$es6$promise$$internal$$PENDING) {
            entry._onerror = null;
            enumerator._settledAt(entry._state, i, entry._result);
          } else {
            enumerator._willSettleAt(c.resolve(entry), i);
          }
        } else {
          enumerator._remaining--;
          enumerator._result[i] = entry;
        }
      };
  
      lib$es6$promise$enumerator$$Enumerator.prototype._settledAt = function(state, i, value) {
        var enumerator = this;
        var promise = enumerator.promise;
  
        if (promise._state === lib$es6$promise$$internal$$PENDING) {
          enumerator._remaining--;
  
          if (state === lib$es6$promise$$internal$$REJECTED) {
            lib$es6$promise$$internal$$reject(promise, value);
          } else {
            enumerator._result[i] = value;
          }
        }
  
        if (enumerator._remaining === 0) {
          lib$es6$promise$$internal$$fulfill(promise, enumerator._result);
        }
      };
  
      lib$es6$promise$enumerator$$Enumerator.prototype._willSettleAt = function(promise, i) {
        var enumerator = this;
  
        lib$es6$promise$$internal$$subscribe(promise, undefined, function(value) {
          enumerator._settledAt(lib$es6$promise$$internal$$FULFILLED, i, value);
        }, function(reason) {
          enumerator._settledAt(lib$es6$promise$$internal$$REJECTED, i, reason);
        });
      };
      function lib$es6$promise$promise$all$$all(entries) {
        return new lib$es6$promise$enumerator$$default(this, entries).promise;
      }
      var lib$es6$promise$promise$all$$default = lib$es6$promise$promise$all$$all;
      function lib$es6$promise$promise$race$$race(entries) {
        /*jshint validthis:true */
        var Constructor = this;
  
        var promise = new Constructor(lib$es6$promise$$internal$$noop);
  
        if (!lib$es6$promise$utils$$isArray(entries)) {
          lib$es6$promise$$internal$$reject(promise, new TypeError('You must pass an array to race.'));
          return promise;
        }
  
        var length = entries.length;
  
        function onFulfillment(value) {
          lib$es6$promise$$internal$$resolve(promise, value);
        }
  
        function onRejection(reason) {
          lib$es6$promise$$internal$$reject(promise, reason);
        }
  
        for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) {
          lib$es6$promise$$internal$$subscribe(Constructor.resolve(entries[i]), undefined, onFulfillment, onRejection);
        }
  
        return promise;
      }
      var lib$es6$promise$promise$race$$default = lib$es6$promise$promise$race$$race;
      function lib$es6$promise$promise$resolve$$resolve(object) {
        /*jshint validthis:true */
        var Constructor = this;
  
        if (object && typeof object === 'object' && object.constructor === Constructor) {
          return object;
        }
  
        var promise = new Constructor(lib$es6$promise$$internal$$noop);
        lib$es6$promise$$internal$$resolve(promise, object);
        return promise;
      }
      var lib$es6$promise$promise$resolve$$default = lib$es6$promise$promise$resolve$$resolve;
      function lib$es6$promise$promise$reject$$reject(reason) {
        /*jshint validthis:true */
        var Constructor = this;
        var promise = new Constructor(lib$es6$promise$$internal$$noop);
        lib$es6$promise$$internal$$reject(promise, reason);
        return promise;
      }
      var lib$es6$promise$promise$reject$$default = lib$es6$promise$promise$reject$$reject;
  
      var lib$es6$promise$promise$$counter = 0;
  
      function lib$es6$promise$promise$$needsResolver() {
        throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
      }
  
      function lib$es6$promise$promise$$needsNew() {
        throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");
      }
  
      var lib$es6$promise$promise$$default = lib$es6$promise$promise$$Promise;
      /**
        Promise objects represent the eventual result of an asynchronous operation. The
        primary way of interacting with a promise is through its `then` method, which
        registers callbacks to receive either a promise's eventual value or the reason
        why the promise cannot be fulfilled.
  
        Terminology
        -----------
  
        - `promise` is an object or function with a `then` method whose behavior conforms to this specification.
        - `thenable` is an object or function that defines a `then` method.
        - `value` is any legal JavaScript value (including undefined, a thenable, or a promise).
        - `exception` is a value that is thrown using the throw statement.
        - `reason` is a value that indicates why a promise was rejected.
        - `settled` the final resting state of a promise, fulfilled or rejected.
  
        A promise can be in one of three states: pending, fulfilled, or rejected.
  
        Promises that are fulfilled have a fulfillment value and are in the fulfilled
        state.  Promises that are rejected have a rejection reason and are in the
        rejected state.  A fulfillment value is never a thenable.
  
        Promises can also be said to *resolve* a value.  If this value is also a
        promise, then the original promise's settled state will match the value's
        settled state.  So a promise that *resolves* a promise that rejects will
        itself reject, and a promise that *resolves* a promise that fulfills will
        itself fulfill.
  
  
        Basic Usage:
        ------------
  
        ```js
        var promise = new Promise(function(resolve, reject) {
          // on success
          resolve(value);
  
          // on failure
          reject(reason);
        });
  
        promise.then(function(value) {
          // on fulfillment
        }, function(reason) {
          // on rejection
        });
        ```
  
        Advanced Usage:
        ---------------
  
        Promises shine when abstracting away asynchronous interactions such as
        `XMLHttpRequest`s.
  
        ```js
        function getJSON(url) {
          return new Promise(function(resolve, reject){
            var xhr = new XMLHttpRequest();
  
            xhr.open('GET', url);
            xhr.onreadystatechange = handler;
            xhr.responseType = 'json';
            xhr.setRequestHeader('Accept', 'application/json');
            xhr.send();
  
            function handler() {
              if (this.readyState === this.DONE) {
                if (this.status === 200) {
                  resolve(this.response);
                } else {
                  reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));
                }
              }
            };
          });
        }
  
        getJSON('/posts.json').then(function(json) {
          // on fulfillment
        }, function(reason) {
          // on rejection
        });
        ```
  
        Unlike callbacks, promises are great composable primitives.
  
        ```js
        Promise.all([
          getJSON('/posts'),
          getJSON('/comments')
        ]).then(function(values){
          values[0] // => postsJSON
          values[1] // => commentsJSON
  
          return values;
        });
        ```
  
        @class Promise
        @param {function} resolver
        Useful for tooling.
        @constructor
      */
      function lib$es6$promise$promise$$Promise(resolver) {
        this._id = lib$es6$promise$promise$$counter++;
        this._state = undefined;
        this._result = undefined;
        this._subscribers = [];
  
        if (lib$es6$promise$$internal$$noop !== resolver) {
          if (!lib$es6$promise$utils$$isFunction(resolver)) {
            lib$es6$promise$promise$$needsResolver();
          }
  
          if (!(this instanceof lib$es6$promise$promise$$Promise)) {
            lib$es6$promise$promise$$needsNew();
          }
  
          lib$es6$promise$$internal$$initializePromise(this, resolver);
        }
      }
  
      lib$es6$promise$promise$$Promise.all = lib$es6$promise$promise$all$$default;
      lib$es6$promise$promise$$Promise.race = lib$es6$promise$promise$race$$default;
      lib$es6$promise$promise$$Promise.resolve = lib$es6$promise$promise$resolve$$default;
      lib$es6$promise$promise$$Promise.reject = lib$es6$promise$promise$reject$$default;
      lib$es6$promise$promise$$Promise._setScheduler = lib$es6$promise$asap$$setScheduler;
      lib$es6$promise$promise$$Promise._setAsap = lib$es6$promise$asap$$setAsap;
      lib$es6$promise$promise$$Promise._asap = lib$es6$promise$asap$$asap;
  
      lib$es6$promise$promise$$Promise.prototype = {
        constructor: lib$es6$promise$promise$$Promise,
  
      /**
        The primary way of interacting with a promise is through its `then` method,
        which registers callbacks to receive either a promise's eventual value or the
        reason why the promise cannot be fulfilled.
  
        ```js
        findUser().then(function(user){
          // user is available
        }, function(reason){
          // user is unavailable, and you are given the reason why
        });
        ```
  
        Chaining
        --------
  
        The return value of `then` is itself a promise.  This second, 'downstream'
        promise is resolved with the return value of the first promise's fulfillment
        or rejection handler, or rejected if the handler throws an exception.
  
        ```js
        findUser().then(function (user) {
          return user.name;
        }, function (reason) {
          return 'default name';
        }).then(function (userName) {
          // If `findUser` fulfilled, `userName` will be the user's name, otherwise it
          // will be `'default name'`
        });
  
        findUser().then(function (user) {
          throw new Error('Found user, but still unhappy');
        }, function (reason) {
          throw new Error('`findUser` rejected and we're unhappy');
        }).then(function (value) {
          // never reached
        }, function (reason) {
          // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.
          // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'.
        });
        ```
        If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.
  
        ```js
        findUser().then(function (user) {
          throw new PedagogicalException('Upstream error');
        }).then(function (value) {
          // never reached
        }).then(function (value) {
          // never reached
        }, function (reason) {
          // The `PedgagocialException` is propagated all the way down to here
        });
        ```
  
        Assimilation
        ------------
  
        Sometimes the value you want to propagate to a downstream promise can only be
        retrieved asynchronously. This can be achieved by returning a promise in the
        fulfillment or rejection handler. The downstream promise will then be pending
        until the returned promise is settled. This is called *assimilation*.
  
        ```js
        findUser().then(function (user) {
          return findCommentsByAuthor(user);
        }).then(function (comments) {
          // The user's comments are now available
        });
        ```
  
        If the assimliated promise rejects, then the downstream promise will also reject.
  
        ```js
        findUser().then(function (user) {
          return findCommentsByAuthor(user);
        }).then(function (comments) {
          // If `findCommentsByAuthor` fulfills, we'll have the value here
        }, function (reason) {
          // If `findCommentsByAuthor` rejects, we'll have the reason here
        });
        ```
  
        Simple Example
        --------------
  
        Synchronous Example
  
        ```javascript
        var result;
  
        try {
          result = findResult();
          // success
        } catch(reason) {
          // failure
        }
        ```
  
        Errback Example
  
        ```js
        findResult(function(result, err){
          if (err) {
            // failure
          } else {
            // success
          }
        });
        ```
  
        Promise Example;
  
        ```javascript
        findResult().then(function(result){
          // success
        }, function(reason){
          // failure
        });
        ```
  
        Advanced Example
        --------------
  
        Synchronous Example
  
        ```javascript
        var author, books;
  
        try {
          author = findAuthor();
          books  = findBooksByAuthor(author);
          // success
        } catch(reason) {
          // failure
        }
        ```
  
        Errback Example
  
        ```js
  
        function foundBooks(books) {
  
        }
  
        function failure(reason) {
  
        }
  
        findAuthor(function(author, err){
          if (err) {
            failure(err);
            // failure
          } else {
            try {
              findBoooksByAuthor(author, function(books, err) {
                if (err) {
                  failure(err);
                } else {
                  try {
                    foundBooks(books);
                  } catch(reason) {
                    failure(reason);
                  }
                }
              });
            } catch(error) {
              failure(err);
            }
            // success
          }
        });
        ```
  
        Promise Example;
  
        ```javascript
        findAuthor().
          then(findBooksByAuthor).
          then(function(books){
            // found books
        }).catch(function(reason){
          // something went wrong
        });
        ```
  
        @method then
        @param {Function} onFulfilled
        @param {Function} onRejected
        Useful for tooling.
        @return {Promise}
      */
        then: function(onFulfillment, onRejection) {
          var parent = this;
          var state = parent._state;
  
          if (state === lib$es6$promise$$internal$$FULFILLED && !onFulfillment || state === lib$es6$promise$$internal$$REJECTED && !onRejection) {
            return this;
          }
  
          var child = new this.constructor(lib$es6$promise$$internal$$noop);
          var result = parent._result;
  
          if (state) {
            var callback = arguments[state - 1];
            lib$es6$promise$asap$$asap(function(){
              lib$es6$promise$$internal$$invokeCallback(state, child, callback, result);
            });
          } else {
            lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection);
          }
  
          return child;
        },
  
      /**
        `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same
        as the catch block of a try/catch statement.
  
        ```js
        function findAuthor(){
          throw new Error('couldn't find that author');
        }
  
        // synchronous
        try {
          findAuthor();
        } catch(reason) {
          // something went wrong
        }
  
        // async with promises
        findAuthor().catch(function(reason){
          // something went wrong
        });
        ```
  
        @method catch
        @param {Function} onRejection
        Useful for tooling.
        @return {Promise}
      */
        'catch': function(onRejection) {
          return this.then(null, onRejection);
        }
      };
      function lib$es6$promise$polyfill$$polyfill() {
        var local;
  
        if (typeof global !== 'undefined') {
            local = global;
        } else if (typeof self !== 'undefined') {
            local = self;
        } else {
            try {
                local = Function('return this')();
            } catch (e) {
                throw new Error('polyfill failed because global object is unavailable in this environment');
            }
        }
  
        var P = local.Promise;
  
        if (P && Object.prototype.toString.call(P.resolve()) === '[object Promise]' && !P.cast) {
          return;
        }
  
        local.Promise = lib$es6$promise$promise$$default;
      }
      var lib$es6$promise$polyfill$$default = lib$es6$promise$polyfill$$polyfill;
  
      var lib$es6$promise$umd$$ES6Promise = {
        'Promise': lib$es6$promise$promise$$default,
        'polyfill': lib$es6$promise$polyfill$$default
      };
  
      /* global define:true module:true window: true */
      if (typeof define === 'function' && define['amd']) {
        define(function() { return lib$es6$promise$umd$$ES6Promise; });
      } else if (typeof module !== 'undefined' && module['exports']) {
        module['exports'] = lib$es6$promise$umd$$ES6Promise;
      } else if (typeof this !== 'undefined') {
        this['ES6Promise'] = lib$es6$promise$umd$$ES6Promise;
      }
  
      lib$es6$promise$polyfill$$default();
  }).call(this);
  
  
  }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  },{"_process":103}],25:[function(require,module,exports){
  (function (process,global){
  /* @preserve
   * The MIT License (MIT)
   * 
   * Copyright (c) 2013-2015 Petka Antonov
   * 
   * 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.
   * 
   */
  /**
   * bluebird build version 2.11.0
   * Features enabled: core, race, call_get, generators, map, nodeify, promisify, props, reduce, settle, some, cancel, using, filter, any, each, timers
  */
  !function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.Promise=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof _dereq_=="function"&&_dereq_;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 _dereq_=="function"&&_dereq_;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
  "use strict";
  module.exports = function(Promise) {
  var SomePromiseArray = Promise._SomePromiseArray;
  function any(promises) {
      var ret = new SomePromiseArray(promises);
      var promise = ret.promise();
      ret.setHowMany(1);
      ret.setUnwrap();
      ret.init();
      return promise;
  }
  
  Promise.any = function (promises) {
      return any(promises);
  };
  
  Promise.prototype.any = function () {
      return any(this);
  };
  
  };
  
  },{}],2:[function(_dereq_,module,exports){
  "use strict";
  var firstLineError;
  try {throw new Error(); } catch (e) {firstLineError = e;}
  var schedule = _dereq_("./schedule.js");
  var Queue = _dereq_("./queue.js");
  var util = _dereq_("./util.js");
  
  function Async() {
      this._isTickUsed = false;
      this._lateQueue = new Queue(16);
      this._normalQueue = new Queue(16);
      this._trampolineEnabled = true;
      var self = this;
      this.drainQueues = function () {
          self._drainQueues();
      };
      this._schedule =
          schedule.isStatic ? schedule(this.drainQueues) : schedule;
  }
  
  Async.prototype.disableTrampolineIfNecessary = function() {
      if (util.hasDevTools) {
          this._trampolineEnabled = false;
      }
  };
  
  Async.prototype.enableTrampoline = function() {
      if (!this._trampolineEnabled) {
          this._trampolineEnabled = true;
          this._schedule = function(fn) {
              setTimeout(fn, 0);
          };
      }
  };
  
  Async.prototype.haveItemsQueued = function () {
      return this._normalQueue.length() > 0;
  };
  
  Async.prototype.throwLater = function(fn, arg) {
      if (arguments.length === 1) {
          arg = fn;
          fn = function () { throw arg; };
      }
      if (typeof setTimeout !== "undefined") {
          setTimeout(function() {
              fn(arg);
          }, 0);
      } else try {
          this._schedule(function() {
              fn(arg);
          });
      } catch (e) {
          throw new Error("No async scheduler available\u000a\u000a    See http://goo.gl/m3OTXk\u000a");
      }
  };
  
  function AsyncInvokeLater(fn, receiver, arg) {
      this._lateQueue.push(fn, receiver, arg);
      this._queueTick();
  }
  
  function AsyncInvoke(fn, receiver, arg) {
      this._normalQueue.push(fn, receiver, arg);
      this._queueTick();
  }
  
  function AsyncSettlePromises(promise) {
      this._normalQueue._pushOne(promise);
      this._queueTick();
  }
  
  if (!util.hasDevTools) {
      Async.prototype.invokeLater = AsyncInvokeLater;
      Async.prototype.invoke = AsyncInvoke;
      Async.prototype.settlePromises = AsyncSettlePromises;
  } else {
      if (schedule.isStatic) {
          schedule = function(fn) { setTimeout(fn, 0); };
      }
      Async.prototype.invokeLater = function (fn, receiver, arg) {
          if (this._trampolineEnabled) {
              AsyncInvokeLater.call(this, fn, receiver, arg);
          } else {
              this._schedule(function() {
                  setTimeout(function() {
                      fn.call(receiver, arg);
                  }, 100);
              });
          }
      };
  
      Async.prototype.invoke = function (fn, receiver, arg) {
          if (this._trampolineEnabled) {
              AsyncInvoke.call(this, fn, receiver, arg);
          } else {
              this._schedule(function() {
                  fn.call(receiver, arg);
              });
          }
      };
  
      Async.prototype.settlePromises = function(promise) {
          if (this._trampolineEnabled) {
              AsyncSettlePromises.call(this, promise);
          } else {
              this._schedule(function() {
                  promise._settlePromises();
              });
          }
      };
  }
  
  Async.prototype.invokeFirst = function (fn, receiver, arg) {
      this._normalQueue.unshift(fn, receiver, arg);
      this._queueTick();
  };
  
  Async.prototype._drainQueue = function(queue) {
      while (queue.length() > 0) {
          var fn = queue.shift();
          if (typeof fn !== "function") {
              fn._settlePromises();
              continue;
          }
          var receiver = queue.shift();
          var arg = queue.shift();
          fn.call(receiver, arg);
      }
  };
  
  Async.prototype._drainQueues = function () {
      this._drainQueue(this._normalQueue);
      this._reset();
      this._drainQueue(this._lateQueue);
  };
  
  Async.prototype._queueTick = function () {
      if (!this._isTickUsed) {
          this._isTickUsed = true;
          this._schedule(this.drainQueues);
      }
  };
  
  Async.prototype._reset = function () {
      this._isTickUsed = false;
  };
  
  module.exports = new Async();
  module.exports.firstLineError = firstLineError;
  
  },{"./queue.js":28,"./schedule.js":31,"./util.js":38}],3:[function(_dereq_,module,exports){
  "use strict";
  module.exports = function(Promise, INTERNAL, tryConvertToPromise) {
  var rejectThis = function(_, e) {
      this._reject(e);
  };
  
  var targetRejected = function(e, context) {
      context.promiseRejectionQueued = true;
      context.bindingPromise._then(rejectThis, rejectThis, null, this, e);
  };
  
  var bindingResolved = function(thisArg, context) {
      if (this._isPending()) {
          this._resolveCallback(context.target);
      }
  };
  
  var bindingRejected = function(e, context) {
      if (!context.promiseRejectionQueued) this._reject(e);
  };
  
  Promise.prototype.bind = function (thisArg) {
      var maybePromise = tryConvertToPromise(thisArg);
      var ret = new Promise(INTERNAL);
      ret._propagateFrom(this, 1);
      var target = this._target();
  
      ret._setBoundTo(maybePromise);
      if (maybePromise instanceof Promise) {
          var context = {
              promiseRejectionQueued: false,
              promise: ret,
              target: target,
              bindingPromise: maybePromise
          };
          target._then(INTERNAL, targetRejected, ret._progress, ret, context);
          maybePromise._then(
              bindingResolved, bindingRejected, ret._progress, ret, context);
      } else {
          ret._resolveCallback(target);
      }
      return ret;
  };
  
  Promise.prototype._setBoundTo = function (obj) {
      if (obj !== undefined) {
          this._bitField = this._bitField | 131072;
          this._boundTo = obj;
      } else {
          this._bitField = this._bitField & (~131072);
      }
  };
  
  Promise.prototype._isBound = function () {
      return (this._bitField & 131072) === 131072;
  };
  
  Promise.bind = function (thisArg, value) {
      var maybePromise = tryConvertToPromise(thisArg);
      var ret = new Promise(INTERNAL);
  
      ret._setBoundTo(maybePromise);
      if (maybePromise instanceof Promise) {
          maybePromise._then(function() {
              ret._resolveCallback(value);
          }, ret._reject, ret._progress, ret, null);
      } else {
          ret._resolveCallback(value);
      }
      return ret;
  };
  };
  
  },{}],4:[function(_dereq_,module,exports){
  "use strict";
  var old;
  if (typeof Promise !== "undefined") old = Promise;
  function noConflict() {
      try { if (Promise === bluebird) Promise = old; }
      catch (e) {}
      return bluebird;
  }
  var bluebird = _dereq_("./promise.js")();
  bluebird.noConflict = noConflict;
  module.exports = bluebird;
  
  },{"./promise.js":23}],5:[function(_dereq_,module,exports){
  "use strict";
  var cr = Object.create;
  if (cr) {
      var callerCache = cr(null);
      var getterCache = cr(null);
      callerCache[" size"] = getterCache[" size"] = 0;
  }
  
  module.exports = function(Promise) {
  var util = _dereq_("./util.js");
  var canEvaluate = util.canEvaluate;
  var isIdentifier = util.isIdentifier;
  
  var getMethodCaller;
  var getGetter;
  if (!true) {
  var makeMethodCaller = function (methodName) {
      return new Function("ensureMethod", "                                    \n\
          return function(obj) {                                               \n\
              'use strict'                                                     \n\
              var len = this.length;                                           \n\
              ensureMethod(obj, 'methodName');                                 \n\
              switch(len) {                                                    \n\
                  case 1: return obj.methodName(this[0]);                      \n\
                  case 2: return obj.methodName(this[0], this[1]);             \n\
                  case 3: return obj.methodName(this[0], this[1], this[2]);    \n\
                  case 0: return obj.methodName();                             \n\
                  default:                                                     \n\
                      return obj.methodName.apply(obj, this);                  \n\
              }                                                                \n\
          };                                                                   \n\
          ".replace(/methodName/g, methodName))(ensureMethod);
  };
  
  var makeGetter = function (propertyName) {
      return new Function("obj", "                                             \n\
          'use strict';                                                        \n\
          return obj.propertyName;                                             \n\
          ".replace("propertyName", propertyName));
  };
  
  var getCompiled = function(name, compiler, cache) {
      var ret = cache[name];
      if (typeof ret !== "function") {
          if (!isIdentifier(name)) {
              return null;
          }
          ret = compiler(name);
          cache[name] = ret;
          cache[" size"]++;
          if (cache[" size"] > 512) {
              var keys = Object.keys(cache);
              for (var i = 0; i < 256; ++i) delete cache[keys[i]];
              cache[" size"] = keys.length - 256;
          }
      }
      return ret;
  };
  
  getMethodCaller = function(name) {
      return getCompiled(name, makeMethodCaller, callerCache);
  };
  
  getGetter = function(name) {
      return getCompiled(name, makeGetter, getterCache);
  };
  }
  
  function ensureMethod(obj, methodName) {
      var fn;
      if (obj != null) fn = obj[methodName];
      if (typeof fn !== "function") {
          var message = "Object " + util.classString(obj) + " has no method '" +
              util.toString(methodName) + "'";
          throw new Promise.TypeError(message);
      }
      return fn;
  }
  
  function caller(obj) {
      var methodName = this.pop();
      var fn = ensureMethod(obj, methodName);
      return fn.apply(obj, this);
  }
  Promise.prototype.call = function (methodName) {
      var $_len = arguments.length;var args = new Array($_len - 1); for(var $_i = 1; $_i < $_len; ++$_i) {args[$_i - 1] = arguments[$_i];}
      if (!true) {
          if (canEvaluate) {
              var maybeCaller = getMethodCaller(methodName);
              if (maybeCaller !== null) {
                  return this._then(
                      maybeCaller, undefined, undefined, args, undefined);
              }
          }
      }
      args.push(methodName);
      return this._then(caller, undefined, undefined, args, undefined);
  };
  
  function namedGetter(obj) {
      return obj[this];
  }
  function indexedGetter(obj) {
      var index = +this;
      if (index < 0) index = Math.max(0, index + obj.length);
      return obj[index];
  }
  Promise.prototype.get = function (propertyName) {
      var isIndex = (typeof propertyName === "number");
      var getter;
      if (!isIndex) {
          if (canEvaluate) {
              var maybeGetter = getGetter(propertyName);
              getter = maybeGetter !== null ? maybeGetter : namedGetter;
          } else {
              getter = namedGetter;
          }
      } else {
          getter = indexedGetter;
      }
      return this._then(getter, undefined, undefined, propertyName, undefined);
  };
  };
  
  },{"./util.js":38}],6:[function(_dereq_,module,exports){
  "use strict";
  module.exports = function(Promise) {
  var errors = _dereq_("./errors.js");
  var async = _dereq_("./async.js");
  var CancellationError = errors.CancellationError;
  
  Promise.prototype._cancel = function (reason) {
      if (!this.isCancellable()) return this;
      var parent;
      var promiseToReject = this;
      while ((parent = promiseToReject._cancellationParent) !== undefined &&
          parent.isCancellable()) {
          promiseToReject = parent;
      }
      this._unsetCancellable();
      promiseToReject._target()._rejectCallback(reason, false, true);
  };
  
  Promise.prototype.cancel = function (reason) {
      if (!this.isCancellable()) return this;
      if (reason === undefined) reason = new CancellationError();
      async.invokeLater(this._cancel, this, reason);
      return this;
  };
  
  Promise.prototype.cancellable = function () {
      if (this._cancellable()) return this;
      async.enableTrampoline();
      this._setCancellable();
      this._cancellationParent = undefined;
      return this;
  };
  
  Promise.prototype.uncancellable = function () {
      var ret = this.then();
      ret._unsetCancellable();
      return ret;
  };
  
  Promise.prototype.fork = function (didFulfill, didReject, didProgress) {
      var ret = this._then(didFulfill, didReject, didProgress,
                           undefined, undefined);
  
      ret._setCancellable();
      ret._cancellationParent = undefined;
      return ret;
  };
  };
  
  },{"./async.js":2,"./errors.js":13}],7:[function(_dereq_,module,exports){
  "use strict";
  module.exports = function() {
  var async = _dereq_("./async.js");
  var util = _dereq_("./util.js");
  var bluebirdFramePattern =
      /[\\\/]bluebird[\\\/]js[\\\/](main|debug|zalgo|instrumented)/;
  var stackFramePattern = null;
  var formatStack = null;
  var indentStackFrames = false;
  var warn;
  
  function CapturedTrace(parent) {
      this._parent = parent;
      var length = this._length = 1 + (parent === undefined ? 0 : parent._length);
      captureStackTrace(this, CapturedTrace);
      if (length > 32) this.uncycle();
  }
  util.inherits(CapturedTrace, Error);
  
  CapturedTrace.prototype.uncycle = function() {
      var length = this._length;
      if (length < 2) return;
      var nodes = [];
      var stackToIndex = {};
  
      for (var i = 0, node = this; node !== undefined; ++i) {
          nodes.push(node);
          node = node._parent;
      }
      length = this._length = i;
      for (var i = length - 1; i >= 0; --i) {
          var stack = nodes[i].stack;
          if (stackToIndex[stack] === undefined) {
              stackToIndex[stack] = i;
          }
      }
      for (var i = 0; i < length; ++i) {
          var currentStack = nodes[i].stack;
          var index = stackToIndex[currentStack];
          if (index !== undefined && index !== i) {
              if (index > 0) {
                  nodes[index - 1]._parent = undefined;
                  nodes[index - 1]._length = 1;
              }
              nodes[i]._parent = undefined;
              nodes[i]._length = 1;
              var cycleEdgeNode = i > 0 ? nodes[i - 1] : this;
  
              if (index < length - 1) {
                  cycleEdgeNode._parent = nodes[index + 1];
                  cycleEdgeNode._parent.uncycle();
                  cycleEdgeNode._length =
                      cycleEdgeNode._parent._length + 1;
              } else {
                  cycleEdgeNode._parent = undefined;
                  cycleEdgeNode._length = 1;
              }
              var currentChildLength = cycleEdgeNode._length + 1;
              for (var j = i - 2; j >= 0; --j) {
                  nodes[j]._length = currentChildLength;
                  currentChildLength++;
              }
              return;
          }
      }
  };
  
  CapturedTrace.prototype.parent = function() {
      return this._parent;
  };
  
  CapturedTrace.prototype.hasParent = function() {
      return this._parent !== undefined;
  };
  
  CapturedTrace.prototype.attachExtraTrace = function(error) {
      if (error.__stackCleaned__) return;
      this.uncycle();
      var parsed = CapturedTrace.parseStackAndMessage(error);
      var message = parsed.message;
      var stacks = [parsed.stack];
  
      var trace = this;
      while (trace !== undefined) {
          stacks.push(cleanStack(trace.stack.split("\n")));
          trace = trace._parent;
      }
      removeCommonRoots(stacks);
      removeDuplicateOrEmptyJumps(stacks);
      util.notEnumerableProp(error, "stack", reconstructStack(message, stacks));
      util.notEnumerableProp(error, "__stackCleaned__", true);
  };
  
  function reconstructStack(message, stacks) {
      for (var i = 0; i < stacks.length - 1; ++i) {
          stacks[i].push("From previous event:");
          stacks[i] = stacks[i].join("\n");
      }
      if (i < stacks.length) {
          stacks[i] = stacks[i].join("\n");
      }
      return message + "\n" + stacks.join("\n");
  }
  
  function removeDuplicateOrEmptyJumps(stacks) {
      for (var i = 0; i < stacks.length; ++i) {
          if (stacks[i].length === 0 ||
              ((i + 1 < stacks.length) && stacks[i][0] === stacks[i+1][0])) {
              stacks.splice(i, 1);
              i--;
          }
      }
  }
  
  function removeCommonRoots(stacks) {
      var current = stacks[0];
      for (var i = 1; i < stacks.length; ++i) {
          var prev = stacks[i];
          var currentLastIndex = current.length - 1;
          var currentLastLine = current[currentLastIndex];
          var commonRootMeetPoint = -1;
  
          for (var j = prev.length - 1; j >= 0; --j) {
              if (prev[j] === currentLastLine) {
                  commonRootMeetPoint = j;
                  break;
              }
          }
  
          for (var j = commonRootMeetPoint; j >= 0; --j) {
              var line = prev[j];
              if (current[currentLastIndex] === line) {
                  current.pop();
                  currentLastIndex--;
              } else {
                  break;
              }
          }
          current = prev;
      }
  }
  
  function cleanStack(stack) {
      var ret = [];
      for (var i = 0; i < stack.length; ++i) {
          var line = stack[i];
          var isTraceLine = stackFramePattern.test(line) ||
              "    (No stack trace)" === line;
          var isInternalFrame = isTraceLine && shouldIgnore(line);
          if (isTraceLine && !isInternalFrame) {
              if (indentStackFrames && line.charAt(0) !== " ") {
                  line = "    " + line;
              }
              ret.push(line);
          }
      }
      return ret;
  }
  
  function stackFramesAsArray(error) {
      var stack = error.stack.replace(/\s+$/g, "").split("\n");
      for (var i = 0; i < stack.length; ++i) {
          var line = stack[i];
          if ("    (No stack trace)" === line || stackFramePattern.test(line)) {
              break;
          }
      }
      if (i > 0) {
          stack = stack.slice(i);
      }
      return stack;
  }
  
  CapturedTrace.parseStackAndMessage = function(error) {
      var stack = error.stack;
      var message = error.toString();
      stack = typeof stack === "string" && stack.length > 0
                  ? stackFramesAsArray(error) : ["    (No stack trace)"];
      return {
          message: message,
          stack: cleanStack(stack)
      };
  };
  
  CapturedTrace.formatAndLogError = function(error, title) {
      if (typeof console !== "undefined") {
          var message;
          if (typeof error === "object" || typeof error === "function") {
              var stack = error.stack;
              message = title + formatStack(stack, error);
          } else {
              message = title + String(error);
          }
          if (typeof warn === "function") {
              warn(message);
          } else if (typeof console.log === "function" ||
              typeof console.log === "object") {
              console.log(message);
          }
      }
  };
  
  CapturedTrace.unhandledRejection = function (reason) {
      CapturedTrace.formatAndLogError(reason, "^--- With additional stack trace: ");
  };
  
  CapturedTrace.isSupported = function () {
      return typeof captureStackTrace === "function";
  };
  
  CapturedTrace.fireRejectionEvent =
  function(name, localHandler, reason, promise) {
      var localEventFired = false;
      try {
          if (typeof localHandler === "function") {
              localEventFired = true;
              if (name === "rejectionHandled") {
                  localHandler(promise);
              } else {
                  localHandler(reason, promise);
              }
          }
      } catch (e) {
          async.throwLater(e);
      }
  
      var globalEventFired = false;
      try {
          globalEventFired = fireGlobalEvent(name, reason, promise);
      } catch (e) {
          globalEventFired = true;
          async.throwLater(e);
      }
  
      var domEventFired = false;
      if (fireDomEvent) {
          try {
              domEventFired = fireDomEvent(name.toLowerCase(), {
                  reason: reason,
                  promise: promise
              });
          } catch (e) {
              domEventFired = true;
              async.throwLater(e);
          }
      }
  
      if (!globalEventFired && !localEventFired && !domEventFired &&
          name === "unhandledRejection") {
          CapturedTrace.formatAndLogError(reason, "Unhandled rejection ");
      }
  };
  
  function formatNonError(obj) {
      var str;
      if (typeof obj === "function") {
          str = "[function " +
              (obj.name || "anonymous") +
              "]";
      } else {
          str = obj.toString();
          var ruselessToString = /\[object [a-zA-Z0-9$_]+\]/;
          if (ruselessToString.test(str)) {
              try {
                  var newStr = JSON.stringify(obj);
                  str = newStr;
              }
              catch(e) {
  
              }
          }
          if (str.length === 0) {
              str = "(empty array)";
          }
      }
      return ("(<" + snip(str) + ">, no stack trace)");
  }
  
  function snip(str) {
      var maxChars = 41;
      if (str.length < maxChars) {
          return str;
      }
      return str.substr(0, maxChars - 3) + "...";
  }
  
  var shouldIgnore = function() { return false; };
  var parseLineInfoRegex = /[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/;
  function parseLineInfo(line) {
      var matches = line.match(parseLineInfoRegex);
      if (matches) {
          return {
              fileName: matches[1],
              line: parseInt(matches[2], 10)
          };
      }
  }
  CapturedTrace.setBounds = function(firstLineError, lastLineError) {
      if (!CapturedTrace.isSupported()) return;
      var firstStackLines = firstLineError.stack.split("\n");
      var lastStackLines = lastLineError.stack.split("\n");
      var firstIndex = -1;
      var lastIndex = -1;
      var firstFileName;
      var lastFileName;
      for (var i = 0; i < firstStackLines.length; ++i) {
          var result = parseLineInfo(firstStackLines[i]);
          if (result) {
              firstFileName = result.fileName;
              firstIndex = result.line;
              break;
          }
      }
      for (var i = 0; i < lastStackLines.length; ++i) {
          var result = parseLineInfo(lastStackLines[i]);
          if (result) {
              lastFileName = result.fileName;
              lastIndex = result.line;
              break;
          }
      }
      if (firstIndex < 0 || lastIndex < 0 || !firstFileName || !lastFileName ||
          firstFileName !== lastFileName || firstIndex >= lastIndex) {
          return;
      }
  
      shouldIgnore = function(line) {
          if (bluebirdFramePattern.test(line)) return true;
          var info = parseLineInfo(line);
          if (info) {
              if (info.fileName === firstFileName &&
                  (firstIndex <= info.line && info.line <= lastIndex)) {
                  return true;
              }
          }
          return false;
      };
  };
  
  var captureStackTrace = (function stackDetection() {
      var v8stackFramePattern = /^\s*at\s*/;
      var v8stackFormatter = function(stack, error) {
          if (typeof stack === "string") return stack;
  
          if (error.name !== undefined &&
              error.message !== undefined) {
              return error.toString();
          }
          return formatNonError(error);
      };
  
      if (typeof Error.stackTraceLimit === "number" &&
          typeof Error.captureStackTrace === "function") {
          Error.stackTraceLimit = Error.stackTraceLimit + 6;
          stackFramePattern = v8stackFramePattern;
          formatStack = v8stackFormatter;
          var captureStackTrace = Error.captureStackTrace;
  
          shouldIgnore = function(line) {
              return bluebirdFramePattern.test(line);
          };
          return function(receiver, ignoreUntil) {
              Error.stackTraceLimit = Error.stackTraceLimit + 6;
              captureStackTrace(receiver, ignoreUntil);
              Error.stackTraceLimit = Error.stackTraceLimit - 6;
          };
      }
      var err = new Error();
  
      if (typeof err.stack === "string" &&
          err.stack.split("\n")[0].indexOf("stackDetection@") >= 0) {
          stackFramePattern = /@/;
          formatStack = v8stackFormatter;
          indentStackFrames = true;
          return function captureStackTrace(o) {
              o.stack = new Error().stack;
          };
      }
  
      var hasStackAfterThrow;
      try { throw new Error(); }
      catch(e) {
          hasStackAfterThrow = ("stack" in e);
      }
      if (!("stack" in err) && hasStackAfterThrow &&
          typeof Error.stackTraceLimit === "number") {
          stackFramePattern = v8stackFramePattern;
          formatStack = v8stackFormatter;
          return function captureStackTrace(o) {
              Error.stackTraceLimit = Error.stackTraceLimit + 6;
              try { throw new Error(); }
              catch(e) { o.stack = e.stack; }
              Error.stackTraceLimit = Error.stackTraceLimit - 6;
          };
      }
  
      formatStack = function(stack, error) {
          if (typeof stack === "string") return stack;
  
          if ((typeof error === "object" ||
              typeof error === "function") &&
              error.name !== undefined &&
              error.message !== undefined) {
              return error.toString();
          }
          return formatNonError(error);
      };
  
      return null;
  
  })([]);
  
  var fireDomEvent;
  var fireGlobalEvent = (function() {
      if (util.isNode) {
          return function(name, reason, promise) {
              if (name === "rejectionHandled") {
                  return process.emit(name, promise);
              } else {
                  return process.emit(name, reason, promise);
              }
          };
      } else {
          var customEventWorks = false;
          var anyEventWorks = true;
          try {
              var ev = new self.CustomEvent("test");
              customEventWorks = ev instanceof CustomEvent;
          } catch (e) {}
          if (!customEventWorks) {
              try {
                  var event = document.createEvent("CustomEvent");
                  event.initCustomEvent("testingtheevent", false, true, {});
                  self.dispatchEvent(event);
              } catch (e) {
                  anyEventWorks = false;
              }
          }
          if (anyEventWorks) {
              fireDomEvent = function(type, detail) {
                  var event;
                  if (customEventWorks) {
                      event = new self.CustomEvent(type, {
                          detail: detail,
                          bubbles: false,
                          cancelable: true
                      });
                  } else if (self.dispatchEvent) {
                      event = document.createEvent("CustomEvent");
                      event.initCustomEvent(type, false, true, detail);
                  }
  
                  return event ? !self.dispatchEvent(event) : false;
              };
          }
  
          var toWindowMethodNameMap = {};
          toWindowMethodNameMap["unhandledRejection"] = ("on" +
              "unhandledRejection").toLowerCase();
          toWindowMethodNameMap["rejectionHandled"] = ("on" +
              "rejectionHandled").toLowerCase();
  
          return function(name, reason, promise) {
              var methodName = toWindowMethodNameMap[name];
              var method = self[methodName];
              if (!method) return false;
              if (name === "rejectionHandled") {
                  method.call(self, promise);
              } else {
                  method.call(self, reason, promise);
              }
              return true;
          };
      }
  })();
  
  if (typeof console !== "undefined" && typeof console.warn !== "undefined") {
      warn = function (message) {
          console.warn(message);
      };
      if (util.isNode && process.stderr.isTTY) {
          warn = function(message) {
              process.stderr.write("\u001b[31m" + message + "\u001b[39m\n");
          };
      } else if (!util.isNode && typeof (new Error().stack) === "string") {
          warn = function(message) {
              console.warn("%c" + message, "color: red");
          };
      }
  }
  
  return CapturedTrace;
  };
  
  },{"./async.js":2,"./util.js":38}],8:[function(_dereq_,module,exports){
  "use strict";
  module.exports = function(NEXT_FILTER) {
  var util = _dereq_("./util.js");
  var errors = _dereq_("./errors.js");
  var tryCatch = util.tryCatch;
  var errorObj = util.errorObj;
  var keys = _dereq_("./es5.js").keys;
  var TypeError = errors.TypeError;
  
  function CatchFilter(instances, callback, promise) {
      this._instances = instances;
      this._callback = callback;
      this._promise = promise;
  }
  
  function safePredicate(predicate, e) {
      var safeObject = {};
      var retfilter = tryCatch(predicate).call(safeObject, e);
  
      if (retfilter === errorObj) return retfilter;
  
      var safeKeys = keys(safeObject);
      if (safeKeys.length) {
          errorObj.e = new TypeError("Catch filter must inherit from Error or be a simple predicate function\u000a\u000a    See http://goo.gl/o84o68\u000a");
          return errorObj;
      }
      return retfilter;
  }
  
  CatchFilter.prototype.doFilter = function (e) {
      var cb = this._callback;
      var promise = this._promise;
      var boundTo = promise._boundValue();
      for (var i = 0, len = this._instances.length; i < len; ++i) {
          var item = this._instances[i];
          var itemIsErrorType = item === Error ||
              (item != null && item.prototype instanceof Error);
  
          if (itemIsErrorType && e instanceof item) {
              var ret = tryCatch(cb).call(boundTo, e);
              if (ret === errorObj) {
                  NEXT_FILTER.e = ret.e;
                  return NEXT_FILTER;
              }
              return ret;
          } else if (typeof item === "function" && !itemIsErrorType) {
              var shouldHandle = safePredicate(item, e);
              if (shouldHandle === errorObj) {
                  e = errorObj.e;
                  break;
              } else if (shouldHandle) {
                  var ret = tryCatch(cb).call(boundTo, e);
                  if (ret === errorObj) {
                      NEXT_FILTER.e = ret.e;
                      return NEXT_FILTER;
                  }
                  return ret;
              }
          }
      }
      NEXT_FILTER.e = e;
      return NEXT_FILTER;
  };
  
  return CatchFilter;
  };
  
  },{"./errors.js":13,"./es5.js":14,"./util.js":38}],9:[function(_dereq_,module,exports){
  "use strict";
  module.exports = function(Promise, CapturedTrace, isDebugging) {
  var contextStack = [];
  function Context() {
      this._trace = new CapturedTrace(peekContext());
  }
  Context.prototype._pushContext = function () {
      if (!isDebugging()) return;
      if (this._trace !== undefined) {
          contextStack.push(this._trace);
      }
  };
  
  Context.prototype._popContext = function () {
      if (!isDebugging()) return;
      if (this._trace !== undefined) {
          contextStack.pop();
      }
  };
  
  function createContext() {
      if (isDebugging()) return new Context();
  }
  
  function peekContext() {
      var lastIndex = contextStack.length - 1;
      if (lastIndex >= 0) {
          return contextStack[lastIndex];
      }
      return undefined;
  }
  
  Promise.prototype._peekContext = peekContext;
  Promise.prototype._pushContext = Context.prototype._pushContext;
  Promise.prototype._popContext = Context.prototype._popContext;
  
  return createContext;
  };
  
  },{}],10:[function(_dereq_,module,exports){
  "use strict";
  module.exports = function(Promise, CapturedTrace) {
  var getDomain = Promise._getDomain;
  var async = _dereq_("./async.js");
  var Warning = _dereq_("./errors.js").Warning;
  var util = _dereq_("./util.js");
  var canAttachTrace = util.canAttachTrace;
  var unhandledRejectionHandled;
  var possiblyUnhandledRejection;
  var debugging = false || (util.isNode &&
                      (!!process.env["BLUEBIRD_DEBUG"] ||
                       process.env["NODE_ENV"] === "development"));
  
  if (util.isNode && process.env["BLUEBIRD_DEBUG"] == 0) debugging = false;
  
  if (debugging) {
      async.disableTrampolineIfNecessary();
  }
  
  Promise.prototype._ignoreRejections = function() {
      this._unsetRejectionIsUnhandled();
      this._bitField = this._bitField | 16777216;
  };
  
  Promise.prototype._ensurePossibleRejectionHandled = function () {
      if ((this._bitField & 16777216) !== 0) return;
      this._setRejectionIsUnhandled();
      async.invokeLater(this._notifyUnhandledRejection, this, undefined);
  };
  
  Promise.prototype._notifyUnhandledRejectionIsHandled = function () {
      CapturedTrace.fireRejectionEvent("rejectionHandled",
                                    unhandledRejectionHandled, undefined, this);
  };
  
  Promise.prototype._notifyUnhandledRejection = function () {
      if (this._isRejectionUnhandled()) {
          var reason = this._getCarriedStackTrace() || this._settledValue;
          this._setUnhandledRejectionIsNotified();
          CapturedTrace.fireRejectionEvent("unhandledRejection",
                                        possiblyUnhandledRejection, reason, this);
      }
  };
  
  Promise.prototype._setUnhandledRejectionIsNotified = function () {
      this._bitField = this._bitField | 524288;
  };
  
  Promise.prototype._unsetUnhandledRejectionIsNotified = function () {
      this._bitField = this._bitField & (~524288);
  };
  
  Promise.prototype._isUnhandledRejectionNotified = function () {
      return (this._bitField & 524288) > 0;
  };
  
  Promise.prototype._setRejectionIsUnhandled = function () {
      this._bitField = this._bitField | 2097152;
  };
  
  Promise.prototype._unsetRejectionIsUnhandled = function () {
      this._bitField = this._bitField & (~2097152);
      if (this._isUnhandledRejectionNotified()) {
          this._unsetUnhandledRejectionIsNotified();
          this._notifyUnhandledRejectionIsHandled();
      }
  };
  
  Promise.prototype._isRejectionUnhandled = function () {
      return (this._bitField & 2097152) > 0;
  };
  
  Promise.prototype._setCarriedStackTrace = function (capturedTrace) {
      this._bitField = this._bitField | 1048576;
      this._fulfillmentHandler0 = capturedTrace;
  };
  
  Promise.prototype._isCarryingStackTrace = function () {
      return (this._bitField & 1048576) > 0;
  };
  
  Promise.prototype._getCarriedStackTrace = function () {
      return this._isCarryingStackTrace()
          ? this._fulfillmentHandler0
          : undefined;
  };
  
  Promise.prototype._captureStackTrace = function () {
      if (debugging) {
          this._trace = new CapturedTrace(this._peekContext());
      }
      return this;
  };
  
  Promise.prototype._attachExtraTrace = function (error, ignoreSelf) {
      if (debugging && canAttachTrace(error)) {
          var trace = this._trace;
          if (trace !== undefined) {
              if (ignoreSelf) trace = trace._parent;
          }
          if (trace !== undefined) {
              trace.attachExtraTrace(error);
          } else if (!error.__stackCleaned__) {
              var parsed = CapturedTrace.parseStackAndMessage(error);
              util.notEnumerableProp(error, "stack",
                  parsed.message + "\n" + parsed.stack.join("\n"));
              util.notEnumerableProp(error, "__stackCleaned__", true);
          }
      }
  };
  
  Promise.prototype._warn = function(message) {
      var warning = new Warning(message);
      var ctx = this._peekContext();
      if (ctx) {
          ctx.attachExtraTrace(warning);
      } else {
          var parsed = CapturedTrace.parseStackAndMessage(warning);
          warning.stack = parsed.message + "\n" + parsed.stack.join("\n");
      }
      CapturedTrace.formatAndLogError(warning, "");
  };
  
  Promise.onPossiblyUnhandledRejection = function (fn) {
      var domain = getDomain();
      possiblyUnhandledRejection =
          typeof fn === "function" ? (domain === null ? fn : domain.bind(fn))
                                   : undefined;
  };
  
  Promise.onUnhandledRejectionHandled = function (fn) {
      var domain = getDomain();
      unhandledRejectionHandled =
          typeof fn === "function" ? (domain === null ? fn : domain.bind(fn))
                                   : undefined;
  };
  
  Promise.longStackTraces = function () {
      if (async.haveItemsQueued() &&
          debugging === false
     ) {
          throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a    See http://goo.gl/DT1qyG\u000a");
      }
      debugging = CapturedTrace.isSupported();
      if (debugging) {
          async.disableTrampolineIfNecessary();
      }
  };
  
  Promise.hasLongStackTraces = function () {
      return debugging && CapturedTrace.isSupported();
  };
  
  if (!CapturedTrace.isSupported()) {
      Promise.longStackTraces = function(){};
      debugging = false;
  }
  
  return function() {
      return debugging;
  };
  };
  
  },{"./async.js":2,"./errors.js":13,"./util.js":38}],11:[function(_dereq_,module,exports){
  "use strict";
  var util = _dereq_("./util.js");
  var isPrimitive = util.isPrimitive;
  
  module.exports = function(Promise) {
  var returner = function () {
      return this;
  };
  var thrower = function () {
      throw this;
  };
  var returnUndefined = function() {};
  var throwUndefined = function() {
      throw undefined;
  };
  
  var wrapper = function (value, action) {
      if (action === 1) {
          return function () {
              throw value;
          };
      } else if (action === 2) {
          return function () {
              return value;
          };
      }
  };
  
  
  Promise.prototype["return"] =
  Promise.prototype.thenReturn = function (value) {
      if (value === undefined) return this.then(returnUndefined);
  
      if (isPrimitive(value)) {
          return this._then(
              wrapper(value, 2),
              undefined,
              undefined,
              undefined,
              undefined
         );
      } else if (value instanceof Promise) {
          value._ignoreRejections();
      }
      return this._then(returner, undefined, undefined, value, undefined);
  };
  
  Promise.prototype["throw"] =
  Promise.prototype.thenThrow = function (reason) {
      if (reason === undefined) return this.then(throwUndefined);
  
      if (isPrimitive(reason)) {
          return this._then(
              wrapper(reason, 1),
              undefined,
              undefined,
              undefined,
              undefined
         );
      }
      return this._then(thrower, undefined, undefined, reason, undefined);
  };
  };
  
  },{"./util.js":38}],12:[function(_dereq_,module,exports){
  "use strict";
  module.exports = function(Promise, INTERNAL) {
  var PromiseReduce = Promise.reduce;
  
  Promise.prototype.each = function (fn) {
      return PromiseReduce(this, fn, null, INTERNAL);
  };
  
  Promise.each = function (promises, fn) {
      return PromiseReduce(promises, fn, null, INTERNAL);
  };
  };
  
  },{}],13:[function(_dereq_,module,exports){
  "use strict";
  var es5 = _dereq_("./es5.js");
  var Objectfreeze = es5.freeze;
  var util = _dereq_("./util.js");
  var inherits = util.inherits;
  var notEnumerableProp = util.notEnumerableProp;
  
  function subError(nameProperty, defaultMessage) {
      function SubError(message) {
          if (!(this instanceof SubError)) return new SubError(message);
          notEnumerableProp(this, "message",
              typeof message === "string" ? message : defaultMessage);
          notEnumerableProp(this, "name", nameProperty);
          if (Error.captureStackTrace) {
              Error.captureStackTrace(this, this.constructor);
          } else {
              Error.call(this);
          }
      }
      inherits(SubError, Error);
      return SubError;
  }
  
  var _TypeError, _RangeError;
  var Warning = subError("Warning", "warning");
  var CancellationError = subError("CancellationError", "cancellation error");
  var TimeoutError = subError("TimeoutError", "timeout error");
  var AggregateError = subError("AggregateError", "aggregate error");
  try {
      _TypeError = TypeError;
      _RangeError = RangeError;
  } catch(e) {
      _TypeError = subError("TypeError", "type error");
      _RangeError = subError("RangeError", "range error");
  }
  
  var methods = ("join pop push shift unshift slice filter forEach some " +
      "every map indexOf lastIndexOf reduce reduceRight sort reverse").split(" ");
  
  for (var i = 0; i < methods.length; ++i) {
      if (typeof Array.prototype[methods[i]] === "function") {
          AggregateError.prototype[methods[i]] = Array.prototype[methods[i]];
      }
  }
  
  es5.defineProperty(AggregateError.prototype, "length", {
      value: 0,
      configurable: false,
      writable: true,
      enumerable: true
  });
  AggregateError.prototype["isOperational"] = true;
  var level = 0;
  AggregateError.prototype.toString = function() {
      var indent = Array(level * 4 + 1).join(" ");
      var ret = "\n" + indent + "AggregateError of:" + "\n";
      level++;
      indent = Array(level * 4 + 1).join(" ");
      for (var i = 0; i < this.length; ++i) {
          var str = this[i] === this ? "[Circular AggregateError]" : this[i] + "";
          var lines = str.split("\n");
          for (var j = 0; j < lines.length; ++j) {
              lines[j] = indent + lines[j];
          }
          str = lines.join("\n");
          ret += str + "\n";
      }
      level--;
      return ret;
  };
  
  function OperationalError(message) {
      if (!(this instanceof OperationalError))
          return new OperationalError(message);
      notEnumerableProp(this, "name", "OperationalError");
      notEnumerableProp(this, "message", message);
      this.cause = message;
      this["isOperational"] = true;
  
      if (message instanceof Error) {
          notEnumerableProp(this, "message", message.message);
          notEnumerableProp(this, "stack", message.stack);
      } else if (Error.captureStackTrace) {
          Error.captureStackTrace(this, this.constructor);
      }
  
  }
  inherits(OperationalError, Error);
  
  var errorTypes = Error["__BluebirdErrorTypes__"];
  if (!errorTypes) {
      errorTypes = Objectfreeze({
          CancellationError: CancellationError,
          TimeoutError: TimeoutError,
          OperationalError: OperationalError,
          RejectionError: OperationalError,
          AggregateError: AggregateError
      });
      notEnumerableProp(Error, "__BluebirdErrorTypes__", errorTypes);
  }
  
  module.exports = {
      Error: Error,
      TypeError: _TypeError,
      RangeError: _RangeError,
      CancellationError: errorTypes.CancellationError,
      OperationalError: errorTypes.OperationalError,
      TimeoutError: errorTypes.TimeoutError,
      AggregateError: errorTypes.AggregateError,
      Warning: Warning
  };
  
  },{"./es5.js":14,"./util.js":38}],14:[function(_dereq_,module,exports){
  var isES5 = (function(){
      "use strict";
      return this === undefined;
  })();
  
  if (isES5) {
      module.exports = {
          freeze: Object.freeze,
          defineProperty: Object.defineProperty,
          getDescriptor: Object.getOwnPropertyDescriptor,
          keys: Object.keys,
          names: Object.getOwnPropertyNames,
          getPrototypeOf: Object.getPrototypeOf,
          isArray: Array.isArray,
          isES5: isES5,
          propertyIsWritable: function(obj, prop) {
              var descriptor = Object.getOwnPropertyDescriptor(obj, prop);
              return !!(!descriptor || descriptor.writable || descriptor.set);
          }
      };
  } else {
      var has = {}.hasOwnProperty;
      var str = {}.toString;
      var proto = {}.constructor.prototype;
  
      var ObjectKeys = function (o) {
          var ret = [];
          for (var key in o) {
              if (has.call(o, key)) {
                  ret.push(key);
              }
          }
          return ret;
      };
  
      var ObjectGetDescriptor = function(o, key) {
          return {value: o[key]};
      };
  
      var ObjectDefineProperty = function (o, key, desc) {
          o[key] = desc.value;
          return o;
      };
  
      var ObjectFreeze = function (obj) {
          return obj;
      };
  
      var ObjectGetPrototypeOf = function (obj) {
          try {
              return Object(obj).constructor.prototype;
          }
          catch (e) {
              return proto;
          }
      };
  
      var ArrayIsArray = function (obj) {
          try {
              return str.call(obj) === "[object Array]";
          }
          catch(e) {
              return false;
          }
      };
  
      module.exports = {
          isArray: ArrayIsArray,
          keys: ObjectKeys,
          names: ObjectKeys,
          defineProperty: ObjectDefineProperty,
          getDescriptor: ObjectGetDescriptor,
          freeze: ObjectFreeze,
          getPrototypeOf: ObjectGetPrototypeOf,
          isES5: isES5,
          propertyIsWritable: function() {
              return true;
          }
      };
  }
  
  },{}],15:[function(_dereq_,module,exports){
  "use strict";
  module.exports = function(Promise, INTERNAL) {
  var PromiseMap = Promise.map;
  
  Promise.prototype.filter = function (fn, options) {
      return PromiseMap(this, fn, options, INTERNAL);
  };
  
  Promise.filter = function (promises, fn, options) {
      return PromiseMap(promises, fn, options, INTERNAL);
  };
  };
  
  },{}],16:[function(_dereq_,module,exports){
  "use strict";
  module.exports = function(Promise, NEXT_FILTER, tryConvertToPromise) {
  var util = _dereq_("./util.js");
  var isPrimitive = util.isPrimitive;
  var thrower = util.thrower;
  
  function returnThis() {
      return this;
  }
  function throwThis() {
      throw this;
  }
  function return$(r) {
      return function() {
          return r;
      };
  }
  function throw$(r) {
      return function() {
          throw r;
      };
  }
  function promisedFinally(ret, reasonOrValue, isFulfilled) {
      var then;
      if (isPrimitive(reasonOrValue)) {
          then = isFulfilled ? return$(reasonOrValue) : throw$(reasonOrValue);
      } else {
          then = isFulfilled ? returnThis : throwThis;
      }
      return ret._then(then, thrower, undefined, reasonOrValue, undefined);
  }
  
  function finallyHandler(reasonOrValue) {
      var promise = this.promise;
      var handler = this.handler;
  
      var ret = promise._isBound()
                      ? handler.call(promise._boundValue())
                      : handler();
  
      if (ret !== undefined) {
          var maybePromise = tryConvertToPromise(ret, promise);
          if (maybePromise instanceof Promise) {
              maybePromise = maybePromise._target();
              return promisedFinally(maybePromise, reasonOrValue,
                                      promise.isFulfilled());
          }
      }
  
      if (promise.isRejected()) {
          NEXT_FILTER.e = reasonOrValue;
          return NEXT_FILTER;
      } else {
          return reasonOrValue;
      }
  }
  
  function tapHandler(value) {
      var promise = this.promise;
      var handler = this.handler;
  
      var ret = promise._isBound()
                      ? handler.call(promise._boundValue(), value)
                      : handler(value);
  
      if (ret !== undefined) {
          var maybePromise = tryConvertToPromise(ret, promise);
          if (maybePromise instanceof Promise) {
              maybePromise = maybePromise._target();
              return promisedFinally(maybePromise, value, true);
          }
      }
      return value;
  }
  
  Promise.prototype._passThroughHandler = function (handler, isFinally) {
      if (typeof handler !== "function") return this.then();
  
      var promiseAndHandler = {
          promise: this,
          handler: handler
      };
  
      return this._then(
              isFinally ? finallyHandler : tapHandler,
              isFinally ? finallyHandler : undefined, undefined,
              promiseAndHandler, undefined);
  };
  
  Promise.prototype.lastly =
  Promise.prototype["finally"] = function (handler) {
      return this._passThroughHandler(handler, true);
  };
  
  Promise.prototype.tap = function (handler) {
      return this._passThroughHandler(handler, false);
  };
  };
  
  },{"./util.js":38}],17:[function(_dereq_,module,exports){
  "use strict";
  module.exports = function(Promise,
                            apiRejection,
                            INTERNAL,
                            tryConvertToPromise) {
  var errors = _dereq_("./errors.js");
  var TypeError = errors.TypeError;
  var util = _dereq_("./util.js");
  var errorObj = util.errorObj;
  var tryCatch = util.tryCatch;
  var yieldHandlers = [];
  
  function promiseFromYieldHandler(value, yieldHandlers, traceParent) {
      for (var i = 0; i < yieldHandlers.length; ++i) {
          traceParent._pushContext();
          var result = tryCatch(yieldHandlers[i])(value);
          traceParent._popContext();
          if (result === errorObj) {
              traceParent._pushContext();
              var ret = Promise.reject(errorObj.e);
              traceParent._popContext();
              return ret;
          }
          var maybePromise = tryConvertToPromise(result, traceParent);
          if (maybePromise instanceof Promise) return maybePromise;
      }
      return null;
  }
  
  function PromiseSpawn(generatorFunction, receiver, yieldHandler, stack) {
      var promise = this._promise = new Promise(INTERNAL);
      promise._captureStackTrace();
      this._stack = stack;
      this._generatorFunction = generatorFunction;
      this._receiver = receiver;
      this._generator = undefined;
      this._yieldHandlers = typeof yieldHandler === "function"
          ? [yieldHandler].concat(yieldHandlers)
          : yieldHandlers;
  }
  
  PromiseSpawn.prototype.promise = function () {
      return this._promise;
  };
  
  PromiseSpawn.prototype._run = function () {
      this._generator = this._generatorFunction.call(this._receiver);
      this._receiver =
          this._generatorFunction = undefined;
      this._next(undefined);
  };
  
  PromiseSpawn.prototype._continue = function (result) {
      if (result === errorObj) {
          return this._promise._rejectCallback(result.e, false, true);
      }
  
      var value = result.value;
      if (result.done === true) {
          this._promise._resolveCallback(value);
      } else {
          var maybePromise = tryConvertToPromise(value, this._promise);
          if (!(maybePromise instanceof Promise)) {
              maybePromise =
                  promiseFromYieldHandler(maybePromise,
                                          this._yieldHandlers,
                                          this._promise);
              if (maybePromise === null) {
                  this._throw(
                      new TypeError(
                          "A value %s was yielded that could not be treated as a promise\u000a\u000a    See http://goo.gl/4Y4pDk\u000a\u000a".replace("%s", value) +
                          "From coroutine:\u000a" +
                          this._stack.split("\n").slice(1, -7).join("\n")
                      )
                  );
                  return;
              }
          }
          maybePromise._then(
              this._next,
              this._throw,
              undefined,
              this,
              null
         );
      }
  };
  
  PromiseSpawn.prototype._throw = function (reason) {
      this._promise._attachExtraTrace(reason);
      this._promise._pushContext();
      var result = tryCatch(this._generator["throw"])
          .call(this._generator, reason);
      this._promise._popContext();
      this._continue(result);
  };
  
  PromiseSpawn.prototype._next = function (value) {
      this._promise._pushContext();
      var result = tryCatch(this._generator.next).call(this._generator, value);
      this._promise._popContext();
      this._continue(result);
  };
  
  Promise.coroutine = function (generatorFunction, options) {
      if (typeof generatorFunction !== "function") {
          throw new TypeError("generatorFunction must be a function\u000a\u000a    See http://goo.gl/6Vqhm0\u000a");
      }
      var yieldHandler = Object(options).yieldHandler;
      var PromiseSpawn$ = PromiseSpawn;
      var stack = new Error().stack;
      return function () {
          var generator = generatorFunction.apply(this, arguments);
          var spawn = new PromiseSpawn$(undefined, undefined, yieldHandler,
                                        stack);
          spawn._generator = generator;
          spawn._next(undefined);
          return spawn.promise();
      };
  };
  
  Promise.coroutine.addYieldHandler = function(fn) {
      if (typeof fn !== "function") throw new TypeError("fn must be a function\u000a\u000a    See http://goo.gl/916lJJ\u000a");
      yieldHandlers.push(fn);
  };
  
  Promise.spawn = function (generatorFunction) {
      if (typeof generatorFunction !== "function") {
          return apiRejection("generatorFunction must be a function\u000a\u000a    See http://goo.gl/6Vqhm0\u000a");
      }
      var spawn = new PromiseSpawn(generatorFunction, this);
      var ret = spawn.promise();
      spawn._run(Promise.spawn);
      return ret;
  };
  };
  
  },{"./errors.js":13,"./util.js":38}],18:[function(_dereq_,module,exports){
  "use strict";
  module.exports =
  function(Promise, PromiseArray, tryConvertToPromise, INTERNAL) {
  var util = _dereq_("./util.js");
  var canEvaluate = util.canEvaluate;
  var tryCatch = util.tryCatch;
  var errorObj = util.errorObj;
  var reject;
  
  if (!true) {
  if (canEvaluate) {
      var thenCallback = function(i) {
          return new Function("value", "holder", "                             \n\
              'use strict';                                                    \n\
              holder.pIndex = value;                                           \n\
              holder.checkFulfillment(this);                                   \n\
              ".replace(/Index/g, i));
      };
  
      var caller = function(count) {
          var values = [];
          for (var i = 1; i <= count; ++i) values.push("holder.p" + i);
          return new Function("holder", "                                      \n\
              'use strict';                                                    \n\
              var callback = holder.fn;                                        \n\
              return callback(values);                                         \n\
              ".replace(/values/g, values.join(", ")));
      };
      var thenCallbacks = [];
      var callers = [undefined];
      for (var i = 1; i <= 5; ++i) {
          thenCallbacks.push(thenCallback(i));
          callers.push(caller(i));
      }
  
      var Holder = function(total, fn) {
          this.p1 = this.p2 = this.p3 = this.p4 = this.p5 = null;
          this.fn = fn;
          this.total = total;
          this.now = 0;
      };
  
      Holder.prototype.callers = callers;
      Holder.prototype.checkFulfillment = function(promise) {
          var now = this.now;
          now++;
          var total = this.total;
          if (now >= total) {
              var handler = this.callers[total];
              promise._pushContext();
              var ret = tryCatch(handler)(this);
              promise._popContext();
              if (ret === errorObj) {
                  promise._rejectCallback(ret.e, false, true);
              } else {
                  promise._resolveCallback(ret);
              }
          } else {
              this.now = now;
          }
      };
  
      var reject = function (reason) {
          this._reject(reason);
      };
  }
  }
  
  Promise.join = function () {
      var last = arguments.length - 1;
      var fn;
      if (last > 0 && typeof arguments[last] === "function") {
          fn = arguments[last];
          if (!true) {
              if (last < 6 && canEvaluate) {
                  var ret = new Promise(INTERNAL);
                  ret._captureStackTrace();
                  var holder = new Holder(last, fn);
                  var callbacks = thenCallbacks;
                  for (var i = 0; i < last; ++i) {
                      var maybePromise = tryConvertToPromise(arguments[i], ret);
                      if (maybePromise instanceof Promise) {
                          maybePromise = maybePromise._target();
                          if (maybePromise._isPending()) {
                              maybePromise._then(callbacks[i], reject,
                                                 undefined, ret, holder);
                          } else if (maybePromise._isFulfilled()) {
                              callbacks[i].call(ret,
                                                maybePromise._value(), holder);
                          } else {
                              ret._reject(maybePromise._reason());
                          }
                      } else {
                          callbacks[i].call(ret, maybePromise, holder);
                      }
                  }
                  return ret;
              }
          }
      }
      var $_len = arguments.length;var args = new Array($_len); for(var $_i = 0; $_i < $_len; ++$_i) {args[$_i] = arguments[$_i];}
      if (fn) args.pop();
      var ret = new PromiseArray(args).promise();
      return fn !== undefined ? ret.spread(fn) : ret;
  };
  
  };
  
  },{"./util.js":38}],19:[function(_dereq_,module,exports){
  "use strict";
  module.exports = function(Promise,
                            PromiseArray,
                            apiRejection,
                            tryConvertToPromise,
                            INTERNAL) {
  var getDomain = Promise._getDomain;
  var async = _dereq_("./async.js");
  var util = _dereq_("./util.js");
  var tryCatch = util.tryCatch;
  var errorObj = util.errorObj;
  var PENDING = {};
  var EMPTY_ARRAY = [];
  
  function MappingPromiseArray(promises, fn, limit, _filter) {
      this.constructor$(promises);
      this._promise._captureStackTrace();
      var domain = getDomain();
      this._callback = domain === null ? fn : domain.bind(fn);
      this._preservedValues = _filter === INTERNAL
          ? new Array(this.length())
          : null;
      this._limit = limit;
      this._inFlight = 0;
      this._queue = limit >= 1 ? [] : EMPTY_ARRAY;
      async.invoke(init, this, undefined);
  }
  util.inherits(MappingPromiseArray, PromiseArray);
  function init() {this._init$(undefined, -2);}
  
  MappingPromiseArray.prototype._init = function () {};
  
  MappingPromiseArray.prototype._promiseFulfilled = function (value, index) {
      var values = this._values;
      var length = this.length();
      var preservedValues = this._preservedValues;
      var limit = this._limit;
      if (values[index] === PENDING) {
          values[index] = value;
          if (limit >= 1) {
              this._inFlight--;
              this._drainQueue();
              if (this._isResolved()) return;
          }
      } else {
          if (limit >= 1 && this._inFlight >= limit) {
              values[index] = value;
              this._queue.push(index);
              return;
          }
          if (preservedValues !== null) preservedValues[index] = value;
  
          var callback = this._callback;
          var receiver = this._promise._boundValue();
          this._promise._pushContext();
          var ret = tryCatch(callback).call(receiver, value, index, length);
          this._promise._popContext();
          if (ret === errorObj) return this._reject(ret.e);
  
          var maybePromise = tryConvertToPromise(ret, this._promise);
          if (maybePromise instanceof Promise) {
              maybePromise = maybePromise._target();
              if (maybePromise._isPending()) {
                  if (limit >= 1) this._inFlight++;
                  values[index] = PENDING;
                  return maybePromise._proxyPromiseArray(this, index);
              } else if (maybePromise._isFulfilled()) {
                  ret = maybePromise._value();
              } else {
                  return this._reject(maybePromise._reason());
              }
          }
          values[index] = ret;
      }
      var totalResolved = ++this._totalResolved;
      if (totalResolved >= length) {
          if (preservedValues !== null) {
              this._filter(values, preservedValues);
          } else {
              this._resolve(values);
          }
  
      }
  };
  
  MappingPromiseArray.prototype._drainQueue = function () {
      var queue = this._queue;
      var limit = this._limit;
      var values = this._values;
      while (queue.length > 0 && this._inFlight < limit) {
          if (this._isResolved()) return;
          var index = queue.pop();
          this._promiseFulfilled(values[index], index);
      }
  };
  
  MappingPromiseArray.prototype._filter = function (booleans, values) {
      var len = values.length;
      var ret = new Array(len);
      var j = 0;
      for (var i = 0; i < len; ++i) {
          if (booleans[i]) ret[j++] = values[i];
      }
      ret.length = j;
      this._resolve(ret);
  };
  
  MappingPromiseArray.prototype.preservedValues = function () {
      return this._preservedValues;
  };
  
  function map(promises, fn, options, _filter) {
      var limit = typeof options === "object" && options !== null
          ? options.concurrency
          : 0;
      limit = typeof limit === "number" &&
          isFinite(limit) && limit >= 1 ? limit : 0;
      return new MappingPromiseArray(promises, fn, limit, _filter);
  }
  
  Promise.prototype.map = function (fn, options) {
      if (typeof fn !== "function") return apiRejection("fn must be a function\u000a\u000a    See http://goo.gl/916lJJ\u000a");
  
      return map(this, fn, options, null).promise();
  };
  
  Promise.map = function (promises, fn, options, _filter) {
      if (typeof fn !== "function") return apiRejection("fn must be a function\u000a\u000a    See http://goo.gl/916lJJ\u000a");
      return map(promises, fn, options, _filter).promise();
  };
  
  
  };
  
  },{"./async.js":2,"./util.js":38}],20:[function(_dereq_,module,exports){
  "use strict";
  module.exports =
  function(Promise, INTERNAL, tryConvertToPromise, apiRejection) {
  var util = _dereq_("./util.js");
  var tryCatch = util.tryCatch;
  
  Promise.method = function (fn) {
      if (typeof fn !== "function") {
          throw new Promise.TypeError("fn must be a function\u000a\u000a    See http://goo.gl/916lJJ\u000a");
      }
      return function () {
          var ret = new Promise(INTERNAL);
          ret._captureStackTrace();
          ret._pushContext();
          var value = tryCatch(fn).apply(this, arguments);
          ret._popContext();
          ret._resolveFromSyncValue(value);
          return ret;
      };
  };
  
  Promise.attempt = Promise["try"] = function (fn, args, ctx) {
      if (typeof fn !== "function") {
          return apiRejection("fn must be a function\u000a\u000a    See http://goo.gl/916lJJ\u000a");
      }
      var ret = new Promise(INTERNAL);
      ret._captureStackTrace();
      ret._pushContext();
      var value = util.isArray(args)
          ? tryCatch(fn).apply(ctx, args)
          : tryCatch(fn).call(ctx, args);
      ret._popContext();
      ret._resolveFromSyncValue(value);
      return ret;
  };
  
  Promise.prototype._resolveFromSyncValue = function (value) {
      if (value === util.errorObj) {
          this._rejectCallback(value.e, false, true);
      } else {
          this._resolveCallback(value, true);
      }
  };
  };
  
  },{"./util.js":38}],21:[function(_dereq_,module,exports){
  "use strict";
  module.exports = function(Promise) {
  var util = _dereq_("./util.js");
  var async = _dereq_("./async.js");
  var tryCatch = util.tryCatch;
  var errorObj = util.errorObj;
  
  function spreadAdapter(val, nodeback) {
      var promise = this;
      if (!util.isArray(val)) return successAdapter.call(promise, val, nodeback);
      var ret =
          tryCatch(nodeback).apply(promise._boundValue(), [null].concat(val));
      if (ret === errorObj) {
          async.throwLater(ret.e);
      }
  }
  
  function successAdapter(val, nodeback) {
      var promise = this;
      var receiver = promise._boundValue();
      var ret = val === undefined
          ? tryCatch(nodeback).call(receiver, null)
          : tryCatch(nodeback).call(receiver, null, val);
      if (ret === errorObj) {
          async.throwLater(ret.e);
      }
  }
  function errorAdapter(reason, nodeback) {
      var promise = this;
      if (!reason) {
          var target = promise._target();
          var newReason = target._getCarriedStackTrace();
          newReason.cause = reason;
          reason = newReason;
      }
      var ret = tryCatch(nodeback).call(promise._boundValue(), reason);
      if (ret === errorObj) {
          async.throwLater(ret.e);
      }
  }
  
  Promise.prototype.asCallback =
  Promise.prototype.nodeify = function (nodeback, options) {
      if (typeof nodeback == "function") {
          var adapter = successAdapter;
          if (options !== undefined && Object(options).spread) {
              adapter = spreadAdapter;
          }
          this._then(
              adapter,
              errorAdapter,
              undefined,
              this,
              nodeback
          );
      }
      return this;
  };
  };
  
  },{"./async.js":2,"./util.js":38}],22:[function(_dereq_,module,exports){
  "use strict";
  module.exports = function(Promise, PromiseArray) {
  var util = _dereq_("./util.js");
  var async = _dereq_("./async.js");
  var tryCatch = util.tryCatch;
  var errorObj = util.errorObj;
  
  Promise.prototype.progressed = function (handler) {
      return this._then(undefined, undefined, handler, undefined, undefined);
  };
  
  Promise.prototype._progress = function (progressValue) {
      if (this._isFollowingOrFulfilledOrRejected()) return;
      this._target()._progressUnchecked(progressValue);
  
  };
  
  Promise.prototype._progressHandlerAt = function (index) {
      return index === 0
          ? this._progressHandler0
          : this[(index << 2) + index - 5 + 2];
  };
  
  Promise.prototype._doProgressWith = function (progression) {
      var progressValue = progression.value;
      var handler = progression.handler;
      var promise = progression.promise;
      var receiver = progression.receiver;
  
      var ret = tryCatch(handler).call(receiver, progressValue);
      if (ret === errorObj) {
          if (ret.e != null &&
              ret.e.name !== "StopProgressPropagation") {
              var trace = util.canAttachTrace(ret.e)
                  ? ret.e : new Error(util.toString(ret.e));
              promise._attachExtraTrace(trace);
              promise._progress(ret.e);
          }
      } else if (ret instanceof Promise) {
          ret._then(promise._progress, null, null, promise, undefined);
      } else {
          promise._progress(ret);
      }
  };
  
  
  Promise.prototype._progressUnchecked = function (progressValue) {
      var len = this._length();
      var progress = this._progress;
      for (var i = 0; i < len; i++) {
          var handler = this._progressHandlerAt(i);
          var promise = this._promiseAt(i);
          if (!(promise instanceof Promise)) {
              var receiver = this._receiverAt(i);
              if (typeof handler === "function") {
                  handler.call(receiver, progressValue, promise);
              } else if (receiver instanceof PromiseArray &&
                         !receiver._isResolved()) {
                  receiver._promiseProgressed(progressValue, promise);
              }
              continue;
          }
  
          if (typeof handler === "function") {
              async.invoke(this._doProgressWith, this, {
                  handler: handler,
                  promise: promise,
                  receiver: this._receiverAt(i),
                  value: progressValue
              });
          } else {
              async.invoke(progress, promise, progressValue);
          }
      }
  };
  };
  
  },{"./async.js":2,"./util.js":38}],23:[function(_dereq_,module,exports){
  "use strict";
  module.exports = function() {
  var makeSelfResolutionError = function () {
      return new TypeError("circular promise resolution chain\u000a\u000a    See http://goo.gl/LhFpo0\u000a");
  };
  var reflect = function() {
      return new Promise.PromiseInspection(this._target());
  };
  var apiRejection = function(msg) {
      return Promise.reject(new TypeError(msg));
  };
  
  var util = _dereq_("./util.js");
  
  var getDomain;
  if (util.isNode) {
      getDomain = function() {
          var ret = process.domain;
          if (ret === undefined) ret = null;
          return ret;
      };
  } else {
      getDomain = function() {
          return null;
      };
  }
  util.notEnumerableProp(Promise, "_getDomain", getDomain);
  
  var UNDEFINED_BINDING = {};
  var async = _dereq_("./async.js");
  var errors = _dereq_("./errors.js");
  var TypeError = Promise.TypeError = errors.TypeError;
  Promise.RangeError = errors.RangeError;
  Promise.CancellationError = errors.CancellationError;
  Promise.TimeoutError = errors.TimeoutError;
  Promise.OperationalError = errors.OperationalError;
  Promise.RejectionError = errors.OperationalError;
  Promise.AggregateError = errors.AggregateError;
  var INTERNAL = function(){};
  var APPLY = {};
  var NEXT_FILTER = {e: null};
  var tryConvertToPromise = _dereq_("./thenables.js")(Promise, INTERNAL);
  var PromiseArray =
      _dereq_("./promise_array.js")(Promise, INTERNAL,
                                      tryConvertToPromise, apiRejection);
  var CapturedTrace = _dereq_("./captured_trace.js")();
  var isDebugging = _dereq_("./debuggability.js")(Promise, CapturedTrace);
   /*jshint unused:false*/
  var createContext =
      _dereq_("./context.js")(Promise, CapturedTrace, isDebugging);
  var CatchFilter = _dereq_("./catch_filter.js")(NEXT_FILTER);
  var PromiseResolver = _dereq_("./promise_resolver.js");
  var nodebackForPromise = PromiseResolver._nodebackForPromise;
  var errorObj = util.errorObj;
  var tryCatch = util.tryCatch;
  
  function Promise(resolver) {
      if (typeof resolver !== "function") {
          throw new TypeError("the promise constructor requires a resolver function\u000a\u000a    See http://goo.gl/EC22Yn\u000a");
      }
      if (this.constructor !== Promise) {
          throw new TypeError("the promise constructor cannot be invoked directly\u000a\u000a    See http://goo.gl/KsIlge\u000a");
      }
      this._bitField = 0;
      this._fulfillmentHandler0 = undefined;
      this._rejectionHandler0 = undefined;
      this._progressHandler0 = undefined;
      this._promise0 = undefined;
      this._receiver0 = undefined;
      this._settledValue = undefined;
      if (resolver !== INTERNAL) this._resolveFromResolver(resolver);
  }
  
  Promise.prototype.toString = function () {
      return "[object Promise]";
  };
  
  Promise.prototype.caught = Promise.prototype["catch"] = function (fn) {
      var len = arguments.length;
      if (len > 1) {
          var catchInstances = new Array(len - 1),
              j = 0, i;
          for (i = 0; i < len - 1; ++i) {
              var item = arguments[i];
              if (typeof item === "function") {
                  catchInstances[j++] = item;
              } else {
                  return Promise.reject(
                      new TypeError("Catch filter must inherit from Error or be a simple predicate function\u000a\u000a    See http://goo.gl/o84o68\u000a"));
              }
          }
          catchInstances.length = j;
          fn = arguments[i];
          var catchFilter = new CatchFilter(catchInstances, fn, this);
          return this._then(undefined, catchFilter.doFilter, undefined,
              catchFilter, undefined);
      }
      return this._then(undefined, fn, undefined, undefined, undefined);
  };
  
  Promise.prototype.reflect = function () {
      return this._then(reflect, reflect, undefined, this, undefined);
  };
  
  Promise.prototype.then = function (didFulfill, didReject, didProgress) {
      if (isDebugging() && arguments.length > 0 &&
          typeof didFulfill !== "function" &&
          typeof didReject !== "function") {
          var msg = ".then() only accepts functions but was passed: " +
                  util.classString(didFulfill);
          if (arguments.length > 1) {
              msg += ", " + util.classString(didReject);
          }
          this._warn(msg);
      }
      return this._then(didFulfill, didReject, didProgress,
          undefined, undefined);
  };
  
  Promise.prototype.done = function (didFulfill, didReject, didProgress) {
      var promise = this._then(didFulfill, didReject, didProgress,
          undefined, undefined);
      promise._setIsFinal();
  };
  
  Promise.prototype.spread = function (didFulfill, didReject) {
      return this.all()._then(didFulfill, didReject, undefined, APPLY, undefined);
  };
  
  Promise.prototype.isCancellable = function () {
      return !this.isResolved() &&
          this._cancellable();
  };
  
  Promise.prototype.toJSON = function () {
      var ret = {
          isFulfilled: false,
          isRejected: false,
          fulfillmentValue: undefined,
          rejectionReason: undefined
      };
      if (this.isFulfilled()) {
          ret.fulfillmentValue = this.value();
          ret.isFulfilled = true;
      } else if (this.isRejected()) {
          ret.rejectionReason = this.reason();
          ret.isRejected = true;
      }
      return ret;
  };
  
  Promise.prototype.all = function () {
      return new PromiseArray(this).promise();
  };
  
  Promise.prototype.error = function (fn) {
      return this.caught(util.originatesFromRejection, fn);
  };
  
  Promise.getNewLibraryCopy = module.exports;
  
  Promise.is = function (val) {
      return val instanceof Promise;
  };
  
  Promise.fromNode = function(fn) {
      var ret = new Promise(INTERNAL);
      var result = tryCatch(fn)(nodebackForPromise(ret));
      if (result === errorObj) {
          ret._rejectCallback(result.e, true, true);
      }
      return ret;
  };
  
  Promise.all = function (promises) {
      return new PromiseArray(promises).promise();
  };
  
  Promise.defer = Promise.pending = function () {
      var promise = new Promise(INTERNAL);
      return new PromiseResolver(promise);
  };
  
  Promise.cast = function (obj) {
      var ret = tryConvertToPromise(obj);
      if (!(ret instanceof Promise)) {
          var val = ret;
          ret = new Promise(INTERNAL);
          ret._fulfillUnchecked(val);
      }
      return ret;
  };
  
  Promise.resolve = Promise.fulfilled = Promise.cast;
  
  Promise.reject = Promise.rejected = function (reason) {
      var ret = new Promise(INTERNAL);
      ret._captureStackTrace();
      ret._rejectCallback(reason, true);
      return ret;
  };
  
  Promise.setScheduler = function(fn) {
      if (typeof fn !== "function") throw new TypeError("fn must be a function\u000a\u000a    See http://goo.gl/916lJJ\u000a");
      var prev = async._schedule;
      async._schedule = fn;
      return prev;
  };
  
  Promise.prototype._then = function (
      didFulfill,
      didReject,
      didProgress,
      receiver,
      internalData
  ) {
      var haveInternalData = internalData !== undefined;
      var ret = haveInternalData ? internalData : new Promise(INTERNAL);
  
      if (!haveInternalData) {
          ret._propagateFrom(this, 4 | 1);
          ret._captureStackTrace();
      }
  
      var target = this._target();
      if (target !== this) {
          if (receiver === undefined) receiver = this._boundTo;
          if (!haveInternalData) ret._setIsMigrated();
      }
  
      var callbackIndex = target._addCallbacks(didFulfill,
                                               didReject,
                                               didProgress,
                                               ret,
                                               receiver,
                                               getDomain());
  
      if (target._isResolved() && !target._isSettlePromisesQueued()) {
          async.invoke(
              target._settlePromiseAtPostResolution, target, callbackIndex);
      }
  
      return ret;
  };
  
  Promise.prototype._settlePromiseAtPostResolution = function (index) {
      if (this._isRejectionUnhandled()) this._unsetRejectionIsUnhandled();
      this._settlePromiseAt(index);
  };
  
  Promise.prototype._length = function () {
      return this._bitField & 131071;
  };
  
  Promise.prototype._isFollowingOrFulfilledOrRejected = function () {
      return (this._bitField & 939524096) > 0;
  };
  
  Promise.prototype._isFollowing = function () {
      return (this._bitField & 536870912) === 536870912;
  };
  
  Promise.prototype._setLength = function (len) {
      this._bitField = (this._bitField & -131072) |
          (len & 131071);
  };
  
  Promise.prototype._setFulfilled = function () {
      this._bitField = this._bitField | 268435456;
  };
  
  Promise.prototype._setRejected = function () {
      this._bitField = this._bitField | 134217728;
  };
  
  Promise.prototype._setFollowing = function () {
      this._bitField = this._bitField | 536870912;
  };
  
  Promise.prototype._setIsFinal = function () {
      this._bitField = this._bitField | 33554432;
  };
  
  Promise.prototype._isFinal = function () {
      return (this._bitField & 33554432) > 0;
  };
  
  Promise.prototype._cancellable = function () {
      return (this._bitField & 67108864) > 0;
  };
  
  Promise.prototype._setCancellable = function () {
      this._bitField = this._bitField | 67108864;
  };
  
  Promise.prototype._unsetCancellable = function () {
      this._bitField = this._bitField & (~67108864);
  };
  
  Promise.prototype._setIsMigrated = function () {
      this._bitField = this._bitField | 4194304;
  };
  
  Promise.prototype._unsetIsMigrated = function () {
      this._bitField = this._bitField & (~4194304);
  };
  
  Promise.prototype._isMigrated = function () {
      return (this._bitField & 4194304) > 0;
  };
  
  Promise.prototype._receiverAt = function (index) {
      var ret = index === 0
          ? this._receiver0
          : this[
              index * 5 - 5 + 4];
      if (ret === UNDEFINED_BINDING) {
          return undefined;
      } else if (ret === undefined && this._isBound()) {
          return this._boundValue();
      }
      return ret;
  };
  
  Promise.prototype._promiseAt = function (index) {
      return index === 0
          ? this._promise0
          : this[index * 5 - 5 + 3];
  };
  
  Promise.prototype._fulfillmentHandlerAt = function (index) {
      return index === 0
          ? this._fulfillmentHandler0
          : this[index * 5 - 5 + 0];
  };
  
  Promise.prototype._rejectionHandlerAt = function (index) {
      return index === 0
          ? this._rejectionHandler0
          : this[index * 5 - 5 + 1];
  };
  
  Promise.prototype._boundValue = function() {
      var ret = this._boundTo;
      if (ret !== undefined) {
          if (ret instanceof Promise) {
              if (ret.isFulfilled()) {
                  return ret.value();
              } else {
                  return undefined;
              }
          }
      }
      return ret;
  };
  
  Promise.prototype._migrateCallbacks = function (follower, index) {
      var fulfill = follower._fulfillmentHandlerAt(index);
      var reject = follower._rejectionHandlerAt(index);
      var progress = follower._progressHandlerAt(index);
      var promise = follower._promiseAt(index);
      var receiver = follower._receiverAt(index);
      if (promise instanceof Promise) promise._setIsMigrated();
      if (receiver === undefined) receiver = UNDEFINED_BINDING;
      this._addCallbacks(fulfill, reject, progress, promise, receiver, null);
  };
  
  Promise.prototype._addCallbacks = function (
      fulfill,
      reject,
      progress,
      promise,
      receiver,
      domain
  ) {
      var index = this._length();
  
      if (index >= 131071 - 5) {
          index = 0;
          this._setLength(0);
      }
  
      if (index === 0) {
          this._promise0 = promise;
          if (receiver !== undefined) this._receiver0 = receiver;
          if (typeof fulfill === "function" && !this._isCarryingStackTrace()) {
              this._fulfillmentHandler0 =
                  domain === null ? fulfill : domain.bind(fulfill);
          }
          if (typeof reject === "function") {
              this._rejectionHandler0 =
                  domain === null ? reject : domain.bind(reject);
          }
          if (typeof progress === "function") {
              this._progressHandler0 =
                  domain === null ? progress : domain.bind(progress);
          }
      } else {
          var base = index * 5 - 5;
          this[base + 3] = promise;
          this[base + 4] = receiver;
          if (typeof fulfill === "function") {
              this[base + 0] =
                  domain === null ? fulfill : domain.bind(fulfill);
          }
          if (typeof reject === "function") {
              this[base + 1] =
                  domain === null ? reject : domain.bind(reject);
          }
          if (typeof progress === "function") {
              this[base + 2] =
                  domain === null ? progress : domain.bind(progress);
          }
      }
      this._setLength(index + 1);
      return index;
  };
  
  Promise.prototype._setProxyHandlers = function (receiver, promiseSlotValue) {
      var index = this._length();
  
      if (index >= 131071 - 5) {
          index = 0;
          this._setLength(0);
      }
      if (index === 0) {
          this._promise0 = promiseSlotValue;
          this._receiver0 = receiver;
      } else {
          var base = index * 5 - 5;
          this[base + 3] = promiseSlotValue;
          this[base + 4] = receiver;
      }
      this._setLength(index + 1);
  };
  
  Promise.prototype._proxyPromiseArray = function (promiseArray, index) {
      this._setProxyHandlers(promiseArray, index);
  };
  
  Promise.prototype._resolveCallback = function(value, shouldBind) {
      if (this._isFollowingOrFulfilledOrRejected()) return;
      if (value === this)
          return this._rejectCallback(makeSelfResolutionError(), false, true);
      var maybePromise = tryConvertToPromise(value, this);
      if (!(maybePromise instanceof Promise)) return this._fulfill(value);
  
      var propagationFlags = 1 | (shouldBind ? 4 : 0);
      this._propagateFrom(maybePromise, propagationFlags);
      var promise = maybePromise._target();
      if (promise._isPending()) {
          var len = this._length();
          for (var i = 0; i < len; ++i) {
              promise._migrateCallbacks(this, i);
          }
          this._setFollowing();
          this._setLength(0);
          this._setFollowee(promise);
      } else if (promise._isFulfilled()) {
          this._fulfillUnchecked(promise._value());
      } else {
          this._rejectUnchecked(promise._reason(),
              promise._getCarriedStackTrace());
      }
  };
  
  Promise.prototype._rejectCallback =
  function(reason, synchronous, shouldNotMarkOriginatingFromRejection) {
      if (!shouldNotMarkOriginatingFromRejection) {
          util.markAsOriginatingFromRejection(reason);
      }
      var trace = util.ensureErrorObject(reason);
      var hasStack = trace === reason;
      this._attachExtraTrace(trace, synchronous ? hasStack : false);
      this._reject(reason, hasStack ? undefined : trace);
  };
  
  Promise.prototype._resolveFromResolver = function (resolver) {
      var promise = this;
      this._captureStackTrace();
      this._pushContext();
      var synchronous = true;
      var r = tryCatch(resolver)(function(value) {
          if (promise === null) return;
          promise._resolveCallback(value);
          promise = null;
      }, function (reason) {
          if (promise === null) return;
          promise._rejectCallback(reason, synchronous);
          promise = null;
      });
      synchronous = false;
      this._popContext();
  
      if (r !== undefined && r === errorObj && promise !== null) {
          promise._rejectCallback(r.e, true, true);
          promise = null;
      }
  };
  
  Promise.prototype._settlePromiseFromHandler = function (
      handler, receiver, value, promise
  ) {
      if (promise._isRejected()) return;
      promise._pushContext();
      var x;
      if (receiver === APPLY && !this._isRejected()) {
          x = tryCatch(handler).apply(this._boundValue(), value);
      } else {
          x = tryCatch(handler).call(receiver, value);
      }
      promise._popContext();
  
      if (x === errorObj || x === promise || x === NEXT_FILTER) {
          var err = x === promise ? makeSelfResolutionError() : x.e;
          promise._rejectCallback(err, false, true);
      } else {
          promise._resolveCallback(x);
      }
  };
  
  Promise.prototype._target = function() {
      var ret = this;
      while (ret._isFollowing()) ret = ret._followee();
      return ret;
  };
  
  Promise.prototype._followee = function() {
      return this._rejectionHandler0;
  };
  
  Promise.prototype._setFollowee = function(promise) {
      this._rejectionHandler0 = promise;
  };
  
  Promise.prototype._cleanValues = function () {
      if (this._cancellable()) {
          this._cancellationParent = undefined;
      }
  };
  
  Promise.prototype._propagateFrom = function (parent, flags) {
      if ((flags & 1) > 0 && parent._cancellable()) {
          this._setCancellable();
          this._cancellationParent = parent;
      }
      if ((flags & 4) > 0 && parent._isBound()) {
          this._setBoundTo(parent._boundTo);
      }
  };
  
  Promise.prototype._fulfill = function (value) {
      if (this._isFollowingOrFulfilledOrRejected()) return;
      this._fulfillUnchecked(value);
  };
  
  Promise.prototype._reject = function (reason, carriedStackTrace) {
      if (this._isFollowingOrFulfilledOrRejected()) return;
      this._rejectUnchecked(reason, carriedStackTrace);
  };
  
  Promise.prototype._settlePromiseAt = function (index) {
      var promise = this._promiseAt(index);
      var isPromise = promise instanceof Promise;
  
      if (isPromise && promise._isMigrated()) {
          promise._unsetIsMigrated();
          return async.invoke(this._settlePromiseAt, this, index);
      }
      var handler = this._isFulfilled()
          ? this._fulfillmentHandlerAt(index)
          : this._rejectionHandlerAt(index);
  
      var carriedStackTrace =
          this._isCarryingStackTrace() ? this._getCarriedStackTrace() : undefined;
      var value = this._settledValue;
      var receiver = this._receiverAt(index);
      this._clearCallbackDataAtIndex(index);
  
      if (typeof handler === "function") {
          if (!isPromise) {
              handler.call(receiver, value, promise);
          } else {
              this._settlePromiseFromHandler(handler, receiver, value, promise);
          }
      } else if (receiver instanceof PromiseArray) {
          if (!receiver._isResolved()) {
              if (this._isFulfilled()) {
                  receiver._promiseFulfilled(value, promise);
              }
              else {
                  receiver._promiseRejected(value, promise);
              }
          }
      } else if (isPromise) {
          if (this._isFulfilled()) {
              promise._fulfill(value);
          } else {
              promise._reject(value, carriedStackTrace);
          }
      }
  
      if (index >= 4 && (index & 31) === 4)
          async.invokeLater(this._setLength, this, 0);
  };
  
  Promise.prototype._clearCallbackDataAtIndex = function(index) {
      if (index === 0) {
          if (!this._isCarryingStackTrace()) {
              this._fulfillmentHandler0 = undefined;
          }
          this._rejectionHandler0 =
          this._progressHandler0 =
          this._receiver0 =
          this._promise0 = undefined;
      } else {
          var base = index * 5 - 5;
          this[base + 3] =
          this[base + 4] =
          this[base + 0] =
          this[base + 1] =
          this[base + 2] = undefined;
      }
  };
  
  Promise.prototype._isSettlePromisesQueued = function () {
      return (this._bitField &
              -1073741824) === -1073741824;
  };
  
  Promise.prototype._setSettlePromisesQueued = function () {
      this._bitField = this._bitField | -1073741824;
  };
  
  Promise.prototype._unsetSettlePromisesQueued = function () {
      this._bitField = this._bitField & (~-1073741824);
  };
  
  Promise.prototype._queueSettlePromises = function() {
      async.settlePromises(this);
      this._setSettlePromisesQueued();
  };
  
  Promise.prototype._fulfillUnchecked = function (value) {
      if (value === this) {
          var err = makeSelfResolutionError();
          this._attachExtraTrace(err);
          return this._rejectUnchecked(err, undefined);
      }
      this._setFulfilled();
      this._settledValue = value;
      this._cleanValues();
  
      if (this._length() > 0) {
          this._queueSettlePromises();
      }
  };
  
  Promise.prototype._rejectUncheckedCheckError = function (reason) {
      var trace = util.ensureErrorObject(reason);
      this._rejectUnchecked(reason, trace === reason ? undefined : trace);
  };
  
  Promise.prototype._rejectUnchecked = function (reason, trace) {
      if (reason === this) {
          var err = makeSelfResolutionError();
          this._attachExtraTrace(err);
          return this._rejectUnchecked(err);
      }
      this._setRejected();
      this._settledValue = reason;
      this._cleanValues();
  
      if (this._isFinal()) {
          async.throwLater(function(e) {
              if ("stack" in e) {
                  async.invokeFirst(
                      CapturedTrace.unhandledRejection, undefined, e);
              }
              throw e;
          }, trace === undefined ? reason : trace);
          return;
      }
  
      if (trace !== undefined && trace !== reason) {
          this._setCarriedStackTrace(trace);
      }
  
      if (this._length() > 0) {
          this._queueSettlePromises();
      } else {
          this._ensurePossibleRejectionHandled();
      }
  };
  
  Promise.prototype._settlePromises = function () {
      this._unsetSettlePromisesQueued();
      var len = this._length();
      for (var i = 0; i < len; i++) {
          this._settlePromiseAt(i);
      }
  };
  
  
  util.notEnumerableProp(Promise,
                         "_makeSelfResolutionError",
                         makeSelfResolutionError);
  
  _dereq_("./progress.js")(Promise, PromiseArray);
  _dereq_("./method.js")(Promise, INTERNAL, tryConvertToPromise, apiRejection);
  _dereq_("./bind.js")(Promise, INTERNAL, tryConvertToPromise);
  _dereq_("./finally.js")(Promise, NEXT_FILTER, tryConvertToPromise);
  _dereq_("./direct_resolve.js")(Promise);
  _dereq_("./synchronous_inspection.js")(Promise);
  _dereq_("./join.js")(Promise, PromiseArray, tryConvertToPromise, INTERNAL);
  Promise.version = "2.11.0";
  Promise.Promise = Promise;
  _dereq_('./map.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL);
  _dereq_('./cancel.js')(Promise);
  _dereq_('./using.js')(Promise, apiRejection, tryConvertToPromise, createContext);
  _dereq_('./generators.js')(Promise, apiRejection, INTERNAL, tryConvertToPromise);
  _dereq_('./nodeify.js')(Promise);
  _dereq_('./call_get.js')(Promise);
  _dereq_('./props.js')(Promise, PromiseArray, tryConvertToPromise, apiRejection);
  _dereq_('./race.js')(Promise, INTERNAL, tryConvertToPromise, apiRejection);
  _dereq_('./reduce.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL);
  _dereq_('./settle.js')(Promise, PromiseArray);
  _dereq_('./some.js')(Promise, PromiseArray, apiRejection);
  _dereq_('./promisify.js')(Promise, INTERNAL);
  _dereq_('./any.js')(Promise);
  _dereq_('./each.js')(Promise, INTERNAL);
  _dereq_('./timers.js')(Promise, INTERNAL);
  _dereq_('./filter.js')(Promise, INTERNAL);
                                                           
      util.toFastProperties(Promise);                                          
      util.toFastProperties(Promise.prototype);                                
      function fillTypes(value) {                                              
          var p = new Promise(INTERNAL);                                       
          p._fulfillmentHandler0 = value;                                      
          p._rejectionHandler0 = value;                                        
          p._progressHandler0 = value;                                         
          p._promise0 = value;                                                 
          p._receiver0 = value;                                                
          p._settledValue = value;                                             
      }                                                                        
      // Complete slack tracking, opt out of field-type tracking and           
      // stabilize map                                                         
      fillTypes({a: 1});                                                       
      fillTypes({b: 2});                                                       
      fillTypes({c: 3});                                                       
      fillTypes(1);                                                            
      fillTypes(function(){});                                                 
      fillTypes(undefined);                                                    
      fillTypes(false);                                                        
      fillTypes(new Promise(INTERNAL));                                        
      CapturedTrace.setBounds(async.firstLineError, util.lastLineError);       
      return Promise;                                                          
  
  };
  
  },{"./any.js":1,"./async.js":2,"./bind.js":3,"./call_get.js":5,"./cancel.js":6,"./captured_trace.js":7,"./catch_filter.js":8,"./context.js":9,"./debuggability.js":10,"./direct_resolve.js":11,"./each.js":12,"./errors.js":13,"./filter.js":15,"./finally.js":16,"./generators.js":17,"./join.js":18,"./map.js":19,"./method.js":20,"./nodeify.js":21,"./progress.js":22,"./promise_array.js":24,"./promise_resolver.js":25,"./promisify.js":26,"./props.js":27,"./race.js":29,"./reduce.js":30,"./settle.js":32,"./some.js":33,"./synchronous_inspection.js":34,"./thenables.js":35,"./timers.js":36,"./using.js":37,"./util.js":38}],24:[function(_dereq_,module,exports){
  "use strict";
  module.exports = function(Promise, INTERNAL, tryConvertToPromise,
      apiRejection) {
  var util = _dereq_("./util.js");
  var isArray = util.isArray;
  
  function toResolutionValue(val) {
      switch(val) {
      case -2: return [];
      case -3: return {};
      }
  }
  
  function PromiseArray(values) {
      var promise = this._promise = new Promise(INTERNAL);
      var parent;
      if (values instanceof Promise) {
          parent = values;
          promise._propagateFrom(parent, 1 | 4);
      }
      this._values = values;
      this._length = 0;
      this._totalResolved = 0;
      this._init(undefined, -2);
  }
  PromiseArray.prototype.length = function () {
      return this._length;
  };
  
  PromiseArray.prototype.promise = function () {
      return this._promise;
  };
  
  PromiseArray.prototype._init = function init(_, resolveValueIfEmpty) {
      var values = tryConvertToPromise(this._values, this._promise);
      if (values instanceof Promise) {
          values = values._target();
          this._values = values;
          if (values._isFulfilled()) {
              values = values._value();
              if (!isArray(values)) {
                  var err = new Promise.TypeError("expecting an array, a promise or a thenable\u000a\u000a    See http://goo.gl/s8MMhc\u000a");
                  this.__hardReject__(err);
                  return;
              }
          } else if (values._isPending()) {
              values._then(
                  init,
                  this._reject,
                  undefined,
                  this,
                  resolveValueIfEmpty
             );
              return;
          } else {
              this._reject(values._reason());
              return;
          }
      } else if (!isArray(values)) {
          this._promise._reject(apiRejection("expecting an array, a promise or a thenable\u000a\u000a    See http://goo.gl/s8MMhc\u000a")._reason());
          return;
      }
  
      if (values.length === 0) {
          if (resolveValueIfEmpty === -5) {
              this._resolveEmptyArray();
          }
          else {
              this._resolve(toResolutionValue(resolveValueIfEmpty));
          }
          return;
      }
      var len = this.getActualLength(values.length);
      this._length = len;
      this._values = this.shouldCopyValues() ? new Array(len) : this._values;
      var promise = this._promise;
      for (var i = 0; i < len; ++i) {
          var isResolved = this._isResolved();
          var maybePromise = tryConvertToPromise(values[i], promise);
          if (maybePromise instanceof Promise) {
              maybePromise = maybePromise._target();
              if (isResolved) {
                  maybePromise._ignoreRejections();
              } else if (maybePromise._isPending()) {
                  maybePromise._proxyPromiseArray(this, i);
              } else if (maybePromise._isFulfilled()) {
                  this._promiseFulfilled(maybePromise._value(), i);
              } else {
                  this._promiseRejected(maybePromise._reason(), i);
              }
          } else if (!isResolved) {
              this._promiseFulfilled(maybePromise, i);
          }
      }
  };
  
  PromiseArray.prototype._isResolved = function () {
      return this._values === null;
  };
  
  PromiseArray.prototype._resolve = function (value) {
      this._values = null;
      this._promise._fulfill(value);
  };
  
  PromiseArray.prototype.__hardReject__ =
  PromiseArray.prototype._reject = function (reason) {
      this._values = null;
      this._promise._rejectCallback(reason, false, true);
  };
  
  PromiseArray.prototype._promiseProgressed = function (progressValue, index) {
      this._promise._progress({
          index: index,
          value: progressValue
      });
  };
  
  
  PromiseArray.prototype._promiseFulfilled = function (value, index) {
      this._values[index] = value;
      var totalResolved = ++this._totalResolved;
      if (totalResolved >= this._length) {
          this._resolve(this._values);
      }
  };
  
  PromiseArray.prototype._promiseRejected = function (reason, index) {
      this._totalResolved++;
      this._reject(reason);
  };
  
  PromiseArray.prototype.shouldCopyValues = function () {
      return true;
  };
  
  PromiseArray.prototype.getActualLength = function (len) {
      return len;
  };
  
  return PromiseArray;
  };
  
  },{"./util.js":38}],25:[function(_dereq_,module,exports){
  "use strict";
  var util = _dereq_("./util.js");
  var maybeWrapAsError = util.maybeWrapAsError;
  var errors = _dereq_("./errors.js");
  var TimeoutError = errors.TimeoutError;
  var OperationalError = errors.OperationalError;
  var haveGetters = util.haveGetters;
  var es5 = _dereq_("./es5.js");
  
  function isUntypedError(obj) {
      return obj instanceof Error &&
          es5.getPrototypeOf(obj) === Error.prototype;
  }
  
  var rErrorKey = /^(?:name|message|stack|cause)$/;
  function wrapAsOperationalError(obj) {
      var ret;
      if (isUntypedError(obj)) {
          ret = new OperationalError(obj);
          ret.name = obj.name;
          ret.message = obj.message;
          ret.stack = obj.stack;
          var keys = es5.keys(obj);
          for (var i = 0; i < keys.length; ++i) {
              var key = keys[i];
              if (!rErrorKey.test(key)) {
                  ret[key] = obj[key];
              }
          }
          return ret;
      }
      util.markAsOriginatingFromRejection(obj);
      return obj;
  }
  
  function nodebackForPromise(promise) {
      return function(err, value) {
          if (promise === null) return;
  
          if (err) {
              var wrapped = wrapAsOperationalError(maybeWrapAsError(err));
              promise._attachExtraTrace(wrapped);
              promise._reject(wrapped);
          } else if (arguments.length > 2) {
              var $_len = arguments.length;var args = new Array($_len - 1); for(var $_i = 1; $_i < $_len; ++$_i) {args[$_i - 1] = arguments[$_i];}
              promise._fulfill(args);
          } else {
              promise._fulfill(value);
          }
  
          promise = null;
      };
  }
  
  
  var PromiseResolver;
  if (!haveGetters) {
      PromiseResolver = function (promise) {
          this.promise = promise;
          this.asCallback = nodebackForPromise(promise);
          this.callback = this.asCallback;
      };
  }
  else {
      PromiseResolver = function (promise) {
          this.promise = promise;
      };
  }
  if (haveGetters) {
      var prop = {
          get: function() {
              return nodebackForPromise(this.promise);
          }
      };
      es5.defineProperty(PromiseResolver.prototype, "asCallback", prop);
      es5.defineProperty(PromiseResolver.prototype, "callback", prop);
  }
  
  PromiseResolver._nodebackForPromise = nodebackForPromise;
  
  PromiseResolver.prototype.toString = function () {
      return "[object PromiseResolver]";
  };
  
  PromiseResolver.prototype.resolve =
  PromiseResolver.prototype.fulfill = function (value) {
      if (!(this instanceof PromiseResolver)) {
          throw new TypeError("Illegal invocation, resolver resolve/reject must be called within a resolver context. Consider using the promise constructor instead.\u000a\u000a    See http://goo.gl/sdkXL9\u000a");
      }
      this.promise._resolveCallback(value);
  };
  
  PromiseResolver.prototype.reject = function (reason) {
      if (!(this instanceof PromiseResolver)) {
          throw new TypeError("Illegal invocation, resolver resolve/reject must be called within a resolver context. Consider using the promise constructor instead.\u000a\u000a    See http://goo.gl/sdkXL9\u000a");
      }
      this.promise._rejectCallback(reason);
  };
  
  PromiseResolver.prototype.progress = function (value) {
      if (!(this instanceof PromiseResolver)) {
          throw new TypeError("Illegal invocation, resolver resolve/reject must be called within a resolver context. Consider using the promise constructor instead.\u000a\u000a    See http://goo.gl/sdkXL9\u000a");
      }
      this.promise._progress(value);
  };
  
  PromiseResolver.prototype.cancel = function (err) {
      this.promise.cancel(err);
  };
  
  PromiseResolver.prototype.timeout = function () {
      this.reject(new TimeoutError("timeout"));
  };
  
  PromiseResolver.prototype.isResolved = function () {
      return this.promise.isResolved();
  };
  
  PromiseResolver.prototype.toJSON = function () {
      return this.promise.toJSON();
  };
  
  module.exports = PromiseResolver;
  
  },{"./errors.js":13,"./es5.js":14,"./util.js":38}],26:[function(_dereq_,module,exports){
  "use strict";
  module.exports = function(Promise, INTERNAL) {
  var THIS = {};
  var util = _dereq_("./util.js");
  var nodebackForPromise = _dereq_("./promise_resolver.js")
      ._nodebackForPromise;
  var withAppended = util.withAppended;
  var maybeWrapAsError = util.maybeWrapAsError;
  var canEvaluate = util.canEvaluate;
  var TypeError = _dereq_("./errors").TypeError;
  var defaultSuffix = "Async";
  var defaultPromisified = {__isPromisified__: true};
  var noCopyProps = [
      "arity",    "length",
      "name",
      "arguments",
      "caller",
      "callee",
      "prototype",
      "__isPromisified__"
  ];
  var noCopyPropsPattern = new RegExp("^(?:" + noCopyProps.join("|") + ")$");
  
  var defaultFilter = function(name) {
      return util.isIdentifier(name) &&
          name.charAt(0) !== "_" &&
          name !== "constructor";
  };
  
  function propsFilter(key) {
      return !noCopyPropsPattern.test(key);
  }
  
  function isPromisified(fn) {
      try {
          return fn.__isPromisified__ === true;
      }
      catch (e) {
          return false;
      }
  }
  
  function hasPromisified(obj, key, suffix) {
      var val = util.getDataPropertyOrDefault(obj, key + suffix,
                                              defaultPromisified);
      return val ? isPromisified(val) : false;
  }
  function checkValid(ret, suffix, suffixRegexp) {
      for (var i = 0; i < ret.length; i += 2) {
          var key = ret[i];
          if (suffixRegexp.test(key)) {
              var keyWithoutAsyncSuffix = key.replace(suffixRegexp, "");
              for (var j = 0; j < ret.length; j += 2) {
                  if (ret[j] === keyWithoutAsyncSuffix) {
                      throw new TypeError("Cannot promisify an API that has normal methods with '%s'-suffix\u000a\u000a    See http://goo.gl/iWrZbw\u000a"
                          .replace("%s", suffix));
                  }
              }
          }
      }
  }
  
  function promisifiableMethods(obj, suffix, suffixRegexp, filter) {
      var keys = util.inheritedDataKeys(obj);
      var ret = [];
      for (var i = 0; i < keys.length; ++i) {
          var key = keys[i];
          var value = obj[key];
          var passesDefaultFilter = filter === defaultFilter
              ? true : defaultFilter(key, value, obj);
          if (typeof value === "function" &&
              !isPromisified(value) &&
              !hasPromisified(obj, key, suffix) &&
              filter(key, value, obj, passesDefaultFilter)) {
              ret.push(key, value);
          }
      }
      checkValid(ret, suffix, suffixRegexp);
      return ret;
  }
  
  var escapeIdentRegex = function(str) {
      return str.replace(/([$])/, "\\$");
  };
  
  var makeNodePromisifiedEval;
  if (!true) {
  var switchCaseArgumentOrder = function(likelyArgumentCount) {
      var ret = [likelyArgumentCount];
      var min = Math.max(0, likelyArgumentCount - 1 - 3);
      for(var i = likelyArgumentCount - 1; i >= min; --i) {
          ret.push(i);
      }
      for(var i = likelyArgumentCount + 1; i <= 3; ++i) {
          ret.push(i);
      }
      return ret;
  };
  
  var argumentSequence = function(argumentCount) {
      return util.filledRange(argumentCount, "_arg", "");
  };
  
  var parameterDeclaration = function(parameterCount) {
      return util.filledRange(
          Math.max(parameterCount, 3), "_arg", "");
  };
  
  var parameterCount = function(fn) {
      if (typeof fn.length === "number") {
          return Math.max(Math.min(fn.length, 1023 + 1), 0);
      }
      return 0;
  };
  
  makeNodePromisifiedEval =
  function(callback, receiver, originalName, fn) {
      var newParameterCount = Math.max(0, parameterCount(fn) - 1);
      var argumentOrder = switchCaseArgumentOrder(newParameterCount);
      var shouldProxyThis = typeof callback === "string" || receiver === THIS;
  
      function generateCallForArgumentCount(count) {
          var args = argumentSequence(count).join(", ");
          var comma = count > 0 ? ", " : "";
          var ret;
          if (shouldProxyThis) {
              ret = "ret = callback.call(this, {{args}}, nodeback); break;\n";
          } else {
              ret = receiver === undefined
                  ? "ret = callback({{args}}, nodeback); break;\n"
                  : "ret = callback.call(receiver, {{args}}, nodeback); break;\n";
          }
          return ret.replace("{{args}}", args).replace(", ", comma);
      }
  
      function generateArgumentSwitchCase() {
          var ret = "";
          for (var i = 0; i < argumentOrder.length; ++i) {
              ret += "case " + argumentOrder[i] +":" +
                  generateCallForArgumentCount(argumentOrder[i]);
          }
  
          ret += "                                                             \n\
          default:                                                             \n\
              var args = new Array(len + 1);                                   \n\
              var i = 0;                                                       \n\
              for (var i = 0; i < len; ++i) {                                  \n\
                 args[i] = arguments[i];                                       \n\
              }                                                                \n\
              args[i] = nodeback;                                              \n\
              [CodeForCall]                                                    \n\
              break;                                                           \n\
          ".replace("[CodeForCall]", (shouldProxyThis
                                  ? "ret = callback.apply(this, args);\n"
                                  : "ret = callback.apply(receiver, args);\n"));
          return ret;
      }
  
      var getFunctionCode = typeof callback === "string"
                                  ? ("this != null ? this['"+callback+"'] : fn")
                                  : "fn";
  
      return new Function("Promise",
                          "fn",
                          "receiver",
                          "withAppended",
                          "maybeWrapAsError",
                          "nodebackForPromise",
                          "tryCatch",
                          "errorObj",
                          "notEnumerableProp",
                          "INTERNAL","'use strict';                            \n\
          var ret = function (Parameters) {                                    \n\
              'use strict';                                                    \n\
              var len = arguments.length;                                      \n\
              var promise = new Promise(INTERNAL);                             \n\
              promise._captureStackTrace();                                    \n\
              var nodeback = nodebackForPromise(promise);                      \n\
              var ret;                                                         \n\
              var callback = tryCatch([GetFunctionCode]);                      \n\
              switch(len) {                                                    \n\
                  [CodeForSwitchCase]                                          \n\
              }                                                                \n\
              if (ret === errorObj) {                                          \n\
                  promise._rejectCallback(maybeWrapAsError(ret.e), true, true);\n\
              }                                                                \n\
              return promise;                                                  \n\
          };                                                                   \n\
          notEnumerableProp(ret, '__isPromisified__', true);                   \n\
          return ret;                                                          \n\
          "
          .replace("Parameters", parameterDeclaration(newParameterCount))
          .replace("[CodeForSwitchCase]", generateArgumentSwitchCase())
          .replace("[GetFunctionCode]", getFunctionCode))(
              Promise,
              fn,
              receiver,
              withAppended,
              maybeWrapAsError,
              nodebackForPromise,
              util.tryCatch,
              util.errorObj,
              util.notEnumerableProp,
              INTERNAL
          );
  };
  }
  
  function makeNodePromisifiedClosure(callback, receiver, _, fn) {
      var defaultThis = (function() {return this;})();
      var method = callback;
      if (typeof method === "string") {
          callback = fn;
      }
      function promisified() {
          var _receiver = receiver;
          if (receiver === THIS) _receiver = this;
          var promise = new Promise(INTERNAL);
          promise._captureStackTrace();
          var cb = typeof method === "string" && this !== defaultThis
              ? this[method] : callback;
          var fn = nodebackForPromise(promise);
          try {
              cb.apply(_receiver, withAppended(arguments, fn));
          } catch(e) {
              promise._rejectCallback(maybeWrapAsError(e), true, true);
          }
          return promise;
      }
      util.notEnumerableProp(promisified, "__isPromisified__", true);
      return promisified;
  }
  
  var makeNodePromisified = canEvaluate
      ? makeNodePromisifiedEval
      : makeNodePromisifiedClosure;
  
  function promisifyAll(obj, suffix, filter, promisifier) {
      var suffixRegexp = new RegExp(escapeIdentRegex(suffix) + "$");
      var methods =
          promisifiableMethods(obj, suffix, suffixRegexp, filter);
  
      for (var i = 0, len = methods.length; i < len; i+= 2) {
          var key = methods[i];
          var fn = methods[i+1];
          var promisifiedKey = key + suffix;
          if (promisifier === makeNodePromisified) {
              obj[promisifiedKey] =
                  makeNodePromisified(key, THIS, key, fn, suffix);
          } else {
              var promisified = promisifier(fn, function() {
                  return makeNodePromisified(key, THIS, key, fn, suffix);
              });
              util.notEnumerableProp(promisified, "__isPromisified__", true);
              obj[promisifiedKey] = promisified;
          }
      }
      util.toFastProperties(obj);
      return obj;
  }
  
  function promisify(callback, receiver) {
      return makeNodePromisified(callback, receiver, undefined, callback);
  }
  
  Promise.promisify = function (fn, receiver) {
      if (typeof fn !== "function") {
          throw new TypeError("fn must be a function\u000a\u000a    See http://goo.gl/916lJJ\u000a");
      }
      if (isPromisified(fn)) {
          return fn;
      }
      var ret = promisify(fn, arguments.length < 2 ? THIS : receiver);
      util.copyDescriptors(fn, ret, propsFilter);
      return ret;
  };
  
  Promise.promisifyAll = function (target, options) {
      if (typeof target !== "function" && typeof target !== "object") {
          throw new TypeError("the target of promisifyAll must be an object or a function\u000a\u000a    See http://goo.gl/9ITlV0\u000a");
      }
      options = Object(options);
      var suffix = options.suffix;
      if (typeof suffix !== "string") suffix = defaultSuffix;
      var filter = options.filter;
      if (typeof filter !== "function") filter = defaultFilter;
      var promisifier = options.promisifier;
      if (typeof promisifier !== "function") promisifier = makeNodePromisified;
  
      if (!util.isIdentifier(suffix)) {
          throw new RangeError("suffix must be a valid identifier\u000a\u000a    See http://goo.gl/8FZo5V\u000a");
      }
  
      var keys = util.inheritedDataKeys(target);
      for (var i = 0; i < keys.length; ++i) {
          var value = target[keys[i]];
          if (keys[i] !== "constructor" &&
              util.isClass(value)) {
              promisifyAll(value.prototype, suffix, filter, promisifier);
              promisifyAll(value, suffix, filter, promisifier);
          }
      }
  
      return promisifyAll(target, suffix, filter, promisifier);
  };
  };
  
  
  },{"./errors":13,"./promise_resolver.js":25,"./util.js":38}],27:[function(_dereq_,module,exports){
  "use strict";
  module.exports = function(
      Promise, PromiseArray, tryConvertToPromise, apiRejection) {
  var util = _dereq_("./util.js");
  var isObject = util.isObject;
  var es5 = _dereq_("./es5.js");
  
  function PropertiesPromiseArray(obj) {
      var keys = es5.keys(obj);
      var len = keys.length;
      var values = new Array(len * 2);
      for (var i = 0; i < len; ++i) {
          var key = keys[i];
          values[i] = obj[key];
          values[i + len] = key;
      }
      this.constructor$(values);
  }
  util.inherits(PropertiesPromiseArray, PromiseArray);
  
  PropertiesPromiseArray.prototype._init = function () {
      this._init$(undefined, -3) ;
  };
  
  PropertiesPromiseArray.prototype._promiseFulfilled = function (value, index) {
      this._values[index] = value;
      var totalResolved = ++this._totalResolved;
      if (totalResolved >= this._length) {
          var val = {};
          var keyOffset = this.length();
          for (var i = 0, len = this.length(); i < len; ++i) {
              val[this._values[i + keyOffset]] = this._values[i];
          }
          this._resolve(val);
      }
  };
  
  PropertiesPromiseArray.prototype._promiseProgressed = function (value, index) {
      this._promise._progress({
          key: this._values[index + this.length()],
          value: value
      });
  };
  
  PropertiesPromiseArray.prototype.shouldCopyValues = function () {
      return false;
  };
  
  PropertiesPromiseArray.prototype.getActualLength = function (len) {
      return len >> 1;
  };
  
  function props(promises) {
      var ret;
      var castValue = tryConvertToPromise(promises);
  
      if (!isObject(castValue)) {
          return apiRejection("cannot await properties of a non-object\u000a\u000a    See http://goo.gl/OsFKC8\u000a");
      } else if (castValue instanceof Promise) {
          ret = castValue._then(
              Promise.props, undefined, undefined, undefined, undefined);
      } else {
          ret = new PropertiesPromiseArray(castValue).promise();
      }
  
      if (castValue instanceof Promise) {
          ret._propagateFrom(castValue, 4);
      }
      return ret;
  }
  
  Promise.prototype.props = function () {
      return props(this);
  };
  
  Promise.props = function (promises) {
      return props(promises);
  };
  };
  
  },{"./es5.js":14,"./util.js":38}],28:[function(_dereq_,module,exports){
  "use strict";
  function arrayMove(src, srcIndex, dst, dstIndex, len) {
      for (var j = 0; j < len; ++j) {
          dst[j + dstIndex] = src[j + srcIndex];
          src[j + srcIndex] = void 0;
      }
  }
  
  function Queue(capacity) {
      this._capacity = capacity;
      this._length = 0;
      this._front = 0;
  }
  
  Queue.prototype._willBeOverCapacity = function (size) {
      return this._capacity < size;
  };
  
  Queue.prototype._pushOne = function (arg) {
      var length = this.length();
      this._checkCapacity(length + 1);
      var i = (this._front + length) & (this._capacity - 1);
      this[i] = arg;
      this._length = length + 1;
  };
  
  Queue.prototype._unshiftOne = function(value) {
      var capacity = this._capacity;
      this._checkCapacity(this.length() + 1);
      var front = this._front;
      var i = (((( front - 1 ) &
                      ( capacity - 1) ) ^ capacity ) - capacity );
      this[i] = value;
      this._front = i;
      this._length = this.length() + 1;
  };
  
  Queue.prototype.unshift = function(fn, receiver, arg) {
      this._unshiftOne(arg);
      this._unshiftOne(receiver);
      this._unshiftOne(fn);
  };
  
  Queue.prototype.push = function (fn, receiver, arg) {
      var length = this.length() + 3;
      if (this._willBeOverCapacity(length)) {
          this._pushOne(fn);
          this._pushOne(receiver);
          this._pushOne(arg);
          return;
      }
      var j = this._front + length - 3;
      this._checkCapacity(length);
      var wrapMask = this._capacity - 1;
      this[(j + 0) & wrapMask] = fn;
      this[(j + 1) & wrapMask] = receiver;
      this[(j + 2) & wrapMask] = arg;
      this._length = length;
  };
  
  Queue.prototype.shift = function () {
      var front = this._front,
          ret = this[front];
  
      this[front] = undefined;
      this._front = (front + 1) & (this._capacity - 1);
      this._length--;
      return ret;
  };
  
  Queue.prototype.length = function () {
      return this._length;
  };
  
  Queue.prototype._checkCapacity = function (size) {
      if (this._capacity < size) {
          this._resizeTo(this._capacity << 1);
      }
  };
  
  Queue.prototype._resizeTo = function (capacity) {
      var oldCapacity = this._capacity;
      this._capacity = capacity;
      var front = this._front;
      var length = this._length;
      var moveItemsCount = (front + length) & (oldCapacity - 1);
      arrayMove(this, 0, this, oldCapacity, moveItemsCount);
  };
  
  module.exports = Queue;
  
  },{}],29:[function(_dereq_,module,exports){
  "use strict";
  module.exports = function(
      Promise, INTERNAL, tryConvertToPromise, apiRejection) {
  var isArray = _dereq_("./util.js").isArray;
  
  var raceLater = function (promise) {
      return promise.then(function(array) {
          return race(array, promise);
      });
  };
  
  function race(promises, parent) {
      var maybePromise = tryConvertToPromise(promises);
  
      if (maybePromise instanceof Promise) {
          return raceLater(maybePromise);
      } else if (!isArray(promises)) {
          return apiRejection("expecting an array, a promise or a thenable\u000a\u000a    See http://goo.gl/s8MMhc\u000a");
      }
  
      var ret = new Promise(INTERNAL);
      if (parent !== undefined) {
          ret._propagateFrom(parent, 4 | 1);
      }
      var fulfill = ret._fulfill;
      var reject = ret._reject;
      for (var i = 0, len = promises.length; i < len; ++i) {
          var val = promises[i];
  
          if (val === undefined && !(i in promises)) {
              continue;
          }
  
          Promise.cast(val)._then(fulfill, reject, undefined, ret, null);
      }
      return ret;
  }
  
  Promise.race = function (promises) {
      return race(promises, undefined);
  };
  
  Promise.prototype.race = function () {
      return race(this, undefined);
  };
  
  };
  
  },{"./util.js":38}],30:[function(_dereq_,module,exports){
  "use strict";
  module.exports = function(Promise,
                            PromiseArray,
                            apiRejection,
                            tryConvertToPromise,
                            INTERNAL) {
  var getDomain = Promise._getDomain;
  var async = _dereq_("./async.js");
  var util = _dereq_("./util.js");
  var tryCatch = util.tryCatch;
  var errorObj = util.errorObj;
  function ReductionPromiseArray(promises, fn, accum, _each) {
      this.constructor$(promises);
      this._promise._captureStackTrace();
      this._preservedValues = _each === INTERNAL ? [] : null;
      this._zerothIsAccum = (accum === undefined);
      this._gotAccum = false;
      this._reducingIndex = (this._zerothIsAccum ? 1 : 0);
      this._valuesPhase = undefined;
      var maybePromise = tryConvertToPromise(accum, this._promise);
      var rejected = false;
      var isPromise = maybePromise instanceof Promise;
      if (isPromise) {
          maybePromise = maybePromise._target();
          if (maybePromise._isPending()) {
              maybePromise._proxyPromiseArray(this, -1);
          } else if (maybePromise._isFulfilled()) {
              accum = maybePromise._value();
              this._gotAccum = true;
          } else {
              this._reject(maybePromise._reason());
              rejected = true;
          }
      }
      if (!(isPromise || this._zerothIsAccum)) this._gotAccum = true;
      var domain = getDomain();
      this._callback = domain === null ? fn : domain.bind(fn);
      this._accum = accum;
      if (!rejected) async.invoke(init, this, undefined);
  }
  function init() {
      this._init$(undefined, -5);
  }
  util.inherits(ReductionPromiseArray, PromiseArray);
  
  ReductionPromiseArray.prototype._init = function () {};
  
  ReductionPromiseArray.prototype._resolveEmptyArray = function () {
      if (this._gotAccum || this._zerothIsAccum) {
          this._resolve(this._preservedValues !== null
                          ? [] : this._accum);
      }
  };
  
  ReductionPromiseArray.prototype._promiseFulfilled = function (value, index) {
      var values = this._values;
      values[index] = value;
      var length = this.length();
      var preservedValues = this._preservedValues;
      var isEach = preservedValues !== null;
      var gotAccum = this._gotAccum;
      var valuesPhase = this._valuesPhase;
      var valuesPhaseIndex;
      if (!valuesPhase) {
          valuesPhase = this._valuesPhase = new Array(length);
          for (valuesPhaseIndex=0; valuesPhaseIndex<length; ++valuesPhaseIndex) {
              valuesPhase[valuesPhaseIndex] = 0;
          }
      }
      valuesPhaseIndex = valuesPhase[index];
  
      if (index === 0 && this._zerothIsAccum) {
          this._accum = value;
          this._gotAccum = gotAccum = true;
          valuesPhase[index] = ((valuesPhaseIndex === 0)
              ? 1 : 2);
      } else if (index === -1) {
          this._accum = value;
          this._gotAccum = gotAccum = true;
      } else {
          if (valuesPhaseIndex === 0) {
              valuesPhase[index] = 1;
          } else {
              valuesPhase[index] = 2;
              this._accum = value;
          }
      }
      if (!gotAccum) return;
  
      var callback = this._callback;
      var receiver = this._promise._boundValue();
      var ret;
  
      for (var i = this._reducingIndex; i < length; ++i) {
          valuesPhaseIndex = valuesPhase[i];
          if (valuesPhaseIndex === 2) {
              this._reducingIndex = i + 1;
              continue;
          }
          if (valuesPhaseIndex !== 1) return;
          value = values[i];
          this._promise._pushContext();
          if (isEach) {
              preservedValues.push(value);
              ret = tryCatch(callback).call(receiver, value, i, length);
          }
          else {
              ret = tryCatch(callback)
                  .call(receiver, this._accum, value, i, length);
          }
          this._promise._popContext();
  
          if (ret === errorObj) return this._reject(ret.e);
  
          var maybePromise = tryConvertToPromise(ret, this._promise);
          if (maybePromise instanceof Promise) {
              maybePromise = maybePromise._target();
              if (maybePromise._isPending()) {
                  valuesPhase[i] = 4;
                  return maybePromise._proxyPromiseArray(this, i);
              } else if (maybePromise._isFulfilled()) {
                  ret = maybePromise._value();
              } else {
                  return this._reject(maybePromise._reason());
              }
          }
  
          this._reducingIndex = i + 1;
          this._accum = ret;
      }
  
      this._resolve(isEach ? preservedValues : this._accum);
  };
  
  function reduce(promises, fn, initialValue, _each) {
      if (typeof fn !== "function") return apiRejection("fn must be a function\u000a\u000a    See http://goo.gl/916lJJ\u000a");
      var array = new ReductionPromiseArray(promises, fn, initialValue, _each);
      return array.promise();
  }
  
  Promise.prototype.reduce = function (fn, initialValue) {
      return reduce(this, fn, initialValue, null);
  };
  
  Promise.reduce = function (promises, fn, initialValue, _each) {
      return reduce(promises, fn, initialValue, _each);
  };
  };
  
  },{"./async.js":2,"./util.js":38}],31:[function(_dereq_,module,exports){
  "use strict";
  var schedule;
  var util = _dereq_("./util");
  var noAsyncScheduler = function() {
      throw new Error("No async scheduler available\u000a\u000a    See http://goo.gl/m3OTXk\u000a");
  };
  if (util.isNode && typeof MutationObserver === "undefined") {
      var GlobalSetImmediate = global.setImmediate;
      var ProcessNextTick = process.nextTick;
      schedule = util.isRecentNode
                  ? function(fn) { GlobalSetImmediate.call(global, fn); }
                  : function(fn) { ProcessNextTick.call(process, fn); };
  } else if ((typeof MutationObserver !== "undefined") &&
            !(typeof window !== "undefined" &&
              window.navigator &&
              window.navigator.standalone)) {
      schedule = function(fn) {
          var div = document.createElement("div");
          var observer = new MutationObserver(fn);
          observer.observe(div, {attributes: true});
          return function() { div.classList.toggle("foo"); };
      };
      schedule.isStatic = true;
  } else if (typeof setImmediate !== "undefined") {
      schedule = function (fn) {
          setImmediate(fn);
      };
  } else if (typeof setTimeout !== "undefined") {
      schedule = function (fn) {
          setTimeout(fn, 0);
      };
  } else {
      schedule = noAsyncScheduler;
  }
  module.exports = schedule;
  
  },{"./util":38}],32:[function(_dereq_,module,exports){
  "use strict";
  module.exports =
      function(Promise, PromiseArray) {
  var PromiseInspection = Promise.PromiseInspection;
  var util = _dereq_("./util.js");
  
  function SettledPromiseArray(values) {
      this.constructor$(values);
  }
  util.inherits(SettledPromiseArray, PromiseArray);
  
  SettledPromiseArray.prototype._promiseResolved = function (index, inspection) {
      this._values[index] = inspection;
      var totalResolved = ++this._totalResolved;
      if (totalResolved >= this._length) {
          this._resolve(this._values);
      }
  };
  
  SettledPromiseArray.prototype._promiseFulfilled = function (value, index) {
      var ret = new PromiseInspection();
      ret._bitField = 268435456;
      ret._settledValue = value;
      this._promiseResolved(index, ret);
  };
  SettledPromiseArray.prototype._promiseRejected = function (reason, index) {
      var ret = new PromiseInspection();
      ret._bitField = 134217728;
      ret._settledValue = reason;
      this._promiseResolved(index, ret);
  };
  
  Promise.settle = function (promises) {
      return new SettledPromiseArray(promises).promise();
  };
  
  Promise.prototype.settle = function () {
      return new SettledPromiseArray(this).promise();
  };
  };
  
  },{"./util.js":38}],33:[function(_dereq_,module,exports){
  "use strict";
  module.exports =
  function(Promise, PromiseArray, apiRejection) {
  var util = _dereq_("./util.js");
  var RangeError = _dereq_("./errors.js").RangeError;
  var AggregateError = _dereq_("./errors.js").AggregateError;
  var isArray = util.isArray;
  
  
  function SomePromiseArray(values) {
      this.constructor$(values);
      this._howMany = 0;
      this._unwrap = false;
      this._initialized = false;
  }
  util.inherits(SomePromiseArray, PromiseArray);
  
  SomePromiseArray.prototype._init = function () {
      if (!this._initialized) {
          return;
      }
      if (this._howMany === 0) {
          this._resolve([]);
          return;
      }
      this._init$(undefined, -5);
      var isArrayResolved = isArray(this._values);
      if (!this._isResolved() &&
          isArrayResolved &&
          this._howMany > this._canPossiblyFulfill()) {
          this._reject(this._getRangeError(this.length()));
      }
  };
  
  SomePromiseArray.prototype.init = function () {
      this._initialized = true;
      this._init();
  };
  
  SomePromiseArray.prototype.setUnwrap = function () {
      this._unwrap = true;
  };
  
  SomePromiseArray.prototype.howMany = function () {
      return this._howMany;
  };
  
  SomePromiseArray.prototype.setHowMany = function (count) {
      this._howMany = count;
  };
  
  SomePromiseArray.prototype._promiseFulfilled = function (value) {
      this._addFulfilled(value);
      if (this._fulfilled() === this.howMany()) {
          this._values.length = this.howMany();
          if (this.howMany() === 1 && this._unwrap) {
              this._resolve(this._values[0]);
          } else {
              this._resolve(this._values);
          }
      }
  
  };
  SomePromiseArray.prototype._promiseRejected = function (reason) {
      this._addRejected(reason);
      if (this.howMany() > this._canPossiblyFulfill()) {
          var e = new AggregateError();
          for (var i = this.length(); i < this._values.length; ++i) {
              e.push(this._values[i]);
          }
          this._reject(e);
      }
  };
  
  SomePromiseArray.prototype._fulfilled = function () {
      return this._totalResolved;
  };
  
  SomePromiseArray.prototype._rejected = function () {
      return this._values.length - this.length();
  };
  
  SomePromiseArray.prototype._addRejected = function (reason) {
      this._values.push(reason);
  };
  
  SomePromiseArray.prototype._addFulfilled = function (value) {
      this._values[this._totalResolved++] = value;
  };
  
  SomePromiseArray.prototype._canPossiblyFulfill = function () {
      return this.length() - this._rejected();
  };
  
  SomePromiseArray.prototype._getRangeError = function (count) {
      var message = "Input array must contain at least " +
              this._howMany + " items but contains only " + count + " items";
      return new RangeError(message);
  };
  
  SomePromiseArray.prototype._resolveEmptyArray = function () {
      this._reject(this._getRangeError(0));
  };
  
  function some(promises, howMany) {
      if ((howMany | 0) !== howMany || howMany < 0) {
          return apiRejection("expecting a positive integer\u000a\u000a    See http://goo.gl/1wAmHx\u000a");
      }
      var ret = new SomePromiseArray(promises);
      var promise = ret.promise();
      ret.setHowMany(howMany);
      ret.init();
      return promise;
  }
  
  Promise.some = function (promises, howMany) {
      return some(promises, howMany);
  };
  
  Promise.prototype.some = function (howMany) {
      return some(this, howMany);
  };
  
  Promise._SomePromiseArray = SomePromiseArray;
  };
  
  },{"./errors.js":13,"./util.js":38}],34:[function(_dereq_,module,exports){
  "use strict";
  module.exports = function(Promise) {
  function PromiseInspection(promise) {
      if (promise !== undefined) {
          promise = promise._target();
          this._bitField = promise._bitField;
          this._settledValue = promise._settledValue;
      }
      else {
          this._bitField = 0;
          this._settledValue = undefined;
      }
  }
  
  PromiseInspection.prototype.value = function () {
      if (!this.isFulfilled()) {
          throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\u000a\u000a    See http://goo.gl/hc1DLj\u000a");
      }
      return this._settledValue;
  };
  
  PromiseInspection.prototype.error =
  PromiseInspection.prototype.reason = function () {
      if (!this.isRejected()) {
          throw new TypeError("cannot get rejection reason of a non-rejected promise\u000a\u000a    See http://goo.gl/hPuiwB\u000a");
      }
      return this._settledValue;
  };
  
  PromiseInspection.prototype.isFulfilled =
  Promise.prototype._isFulfilled = function () {
      return (this._bitField & 268435456) > 0;
  };
  
  PromiseInspection.prototype.isRejected =
  Promise.prototype._isRejected = function () {
      return (this._bitField & 134217728) > 0;
  };
  
  PromiseInspection.prototype.isPending =
  Promise.prototype._isPending = function () {
      return (this._bitField & 402653184) === 0;
  };
  
  PromiseInspection.prototype.isResolved =
  Promise.prototype._isResolved = function () {
      return (this._bitField & 402653184) > 0;
  };
  
  Promise.prototype.isPending = function() {
      return this._target()._isPending();
  };
  
  Promise.prototype.isRejected = function() {
      return this._target()._isRejected();
  };
  
  Promise.prototype.isFulfilled = function() {
      return this._target()._isFulfilled();
  };
  
  Promise.prototype.isResolved = function() {
      return this._target()._isResolved();
  };
  
  Promise.prototype._value = function() {
      return this._settledValue;
  };
  
  Promise.prototype._reason = function() {
      this._unsetRejectionIsUnhandled();
      return this._settledValue;
  };
  
  Promise.prototype.value = function() {
      var target = this._target();
      if (!target.isFulfilled()) {
          throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\u000a\u000a    See http://goo.gl/hc1DLj\u000a");
      }
      return target._settledValue;
  };
  
  Promise.prototype.reason = function() {
      var target = this._target();
      if (!target.isRejected()) {
          throw new TypeError("cannot get rejection reason of a non-rejected promise\u000a\u000a    See http://goo.gl/hPuiwB\u000a");
      }
      target._unsetRejectionIsUnhandled();
      return target._settledValue;
  };
  
  
  Promise.PromiseInspection = PromiseInspection;
  };
  
  },{}],35:[function(_dereq_,module,exports){
  "use strict";
  module.exports = function(Promise, INTERNAL) {
  var util = _dereq_("./util.js");
  var errorObj = util.errorObj;
  var isObject = util.isObject;
  
  function tryConvertToPromise(obj, context) {
      if (isObject(obj)) {
          if (obj instanceof Promise) {
              return obj;
          }
          else if (isAnyBluebirdPromise(obj)) {
              var ret = new Promise(INTERNAL);
              obj._then(
                  ret._fulfillUnchecked,
                  ret._rejectUncheckedCheckError,
                  ret._progressUnchecked,
                  ret,
                  null
              );
              return ret;
          }
          var then = util.tryCatch(getThen)(obj);
          if (then === errorObj) {
              if (context) context._pushContext();
              var ret = Promise.reject(then.e);
              if (context) context._popContext();
              return ret;
          } else if (typeof then === "function") {
              return doThenable(obj, then, context);
          }
      }
      return obj;
  }
  
  function getThen(obj) {
      return obj.then;
  }
  
  var hasProp = {}.hasOwnProperty;
  function isAnyBluebirdPromise(obj) {
      return hasProp.call(obj, "_promise0");
  }
  
  function doThenable(x, then, context) {
      var promise = new Promise(INTERNAL);
      var ret = promise;
      if (context) context._pushContext();
      promise._captureStackTrace();
      if (context) context._popContext();
      var synchronous = true;
      var result = util.tryCatch(then).call(x,
                                          resolveFromThenable,
                                          rejectFromThenable,
                                          progressFromThenable);
      synchronous = false;
      if (promise && result === errorObj) {
          promise._rejectCallback(result.e, true, true);
          promise = null;
      }
  
      function resolveFromThenable(value) {
          if (!promise) return;
          promise._resolveCallback(value);
          promise = null;
      }
  
      function rejectFromThenable(reason) {
          if (!promise) return;
          promise._rejectCallback(reason, synchronous, true);
          promise = null;
      }
  
      function progressFromThenable(value) {
          if (!promise) return;
          if (typeof promise._progress === "function") {
              promise._progress(value);
          }
      }
      return ret;
  }
  
  return tryConvertToPromise;
  };
  
  },{"./util.js":38}],36:[function(_dereq_,module,exports){
  "use strict";
  module.exports = function(Promise, INTERNAL) {
  var util = _dereq_("./util.js");
  var TimeoutError = Promise.TimeoutError;
  
  var afterTimeout = function (promise, message) {
      if (!promise.isPending()) return;
      
      var err;
      if(!util.isPrimitive(message) && (message instanceof Error)) {
          err = message;
      } else {
          if (typeof message !== "string") {
              message = "operation timed out";
          }
          err = new TimeoutError(message);
      }
      util.markAsOriginatingFromRejection(err);
      promise._attachExtraTrace(err);
      promise._cancel(err);
  };
  
  var afterValue = function(value) { return delay(+this).thenReturn(value); };
  var delay = Promise.delay = function (value, ms) {
      if (ms === undefined) {
          ms = value;
          value = undefined;
          var ret = new Promise(INTERNAL);
          setTimeout(function() { ret._fulfill(); }, ms);
          return ret;
      }
      ms = +ms;
      return Promise.resolve(value)._then(afterValue, null, null, ms, undefined);
  };
  
  Promise.prototype.delay = function (ms) {
      return delay(this, ms);
  };
  
  function successClear(value) {
      var handle = this;
      if (handle instanceof Number) handle = +handle;
      clearTimeout(handle);
      return value;
  }
  
  function failureClear(reason) {
      var handle = this;
      if (handle instanceof Number) handle = +handle;
      clearTimeout(handle);
      throw reason;
  }
  
  Promise.prototype.timeout = function (ms, message) {
      ms = +ms;
      var ret = this.then().cancellable();
      ret._cancellationParent = this;
      var handle = setTimeout(function timeoutTimeout() {
          afterTimeout(ret, message);
      }, ms);
      return ret._then(successClear, failureClear, undefined, handle, undefined);
  };
  
  };
  
  },{"./util.js":38}],37:[function(_dereq_,module,exports){
  "use strict";
  module.exports = function (Promise, apiRejection, tryConvertToPromise,
      createContext) {
      var TypeError = _dereq_("./errors.js").TypeError;
      var inherits = _dereq_("./util.js").inherits;
      var PromiseInspection = Promise.PromiseInspection;
  
      function inspectionMapper(inspections) {
          var len = inspections.length;
          for (var i = 0; i < len; ++i) {
              var inspection = inspections[i];
              if (inspection.isRejected()) {
                  return Promise.reject(inspection.error());
              }
              inspections[i] = inspection._settledValue;
          }
          return inspections;
      }
  
      function thrower(e) {
          setTimeout(function(){throw e;}, 0);
      }
  
      function castPreservingDisposable(thenable) {
          var maybePromise = tryConvertToPromise(thenable);
          if (maybePromise !== thenable &&
              typeof thenable._isDisposable === "function" &&
              typeof thenable._getDisposer === "function" &&
              thenable._isDisposable()) {
              maybePromise._setDisposable(thenable._getDisposer());
          }
          return maybePromise;
      }
      function dispose(resources, inspection) {
          var i = 0;
          var len = resources.length;
          var ret = Promise.defer();
          function iterator() {
              if (i >= len) return ret.resolve();
              var maybePromise = castPreservingDisposable(resources[i++]);
              if (maybePromise instanceof Promise &&
                  maybePromise._isDisposable()) {
                  try {
                      maybePromise = tryConvertToPromise(
                          maybePromise._getDisposer().tryDispose(inspection),
                          resources.promise);
                  } catch (e) {
                      return thrower(e);
                  }
                  if (maybePromise instanceof Promise) {
                      return maybePromise._then(iterator, thrower,
                                                null, null, null);
                  }
              }
              iterator();
          }
          iterator();
          return ret.promise;
      }
  
      function disposerSuccess(value) {
          var inspection = new PromiseInspection();
          inspection._settledValue = value;
          inspection._bitField = 268435456;
          return dispose(this, inspection).thenReturn(value);
      }
  
      function disposerFail(reason) {
          var inspection = new PromiseInspection();
          inspection._settledValue = reason;
          inspection._bitField = 134217728;
          return dispose(this, inspection).thenThrow(reason);
      }
  
      function Disposer(data, promise, context) {
          this._data = data;
          this._promise = promise;
          this._context = context;
      }
  
      Disposer.prototype.data = function () {
          return this._data;
      };
  
      Disposer.prototype.promise = function () {
          return this._promise;
      };
  
      Disposer.prototype.resource = function () {
          if (this.promise().isFulfilled()) {
              return this.promise().value();
          }
          return null;
      };
  
      Disposer.prototype.tryDispose = function(inspection) {
          var resource = this.resource();
          var context = this._context;
          if (context !== undefined) context._pushContext();
          var ret = resource !== null
              ? this.doDispose(resource, inspection) : null;
          if (context !== undefined) context._popContext();
          this._promise._unsetDisposable();
          this._data = null;
          return ret;
      };
  
      Disposer.isDisposer = function (d) {
          return (d != null &&
                  typeof d.resource === "function" &&
                  typeof d.tryDispose === "function");
      };
  
      function FunctionDisposer(fn, promise, context) {
          this.constructor$(fn, promise, context);
      }
      inherits(FunctionDisposer, Disposer);
  
      FunctionDisposer.prototype.doDispose = function (resource, inspection) {
          var fn = this.data();
          return fn.call(resource, resource, inspection);
      };
  
      function maybeUnwrapDisposer(value) {
          if (Disposer.isDisposer(value)) {
              this.resources[this.index]._setDisposable(value);
              return value.promise();
          }
          return value;
      }
  
      Promise.using = function () {
          var len = arguments.length;
          if (len < 2) return apiRejection(
                          "you must pass at least 2 arguments to Promise.using");
          var fn = arguments[len - 1];
          if (typeof fn !== "function") return apiRejection("fn must be a function\u000a\u000a    See http://goo.gl/916lJJ\u000a");
  
          var input;
          var spreadArgs = true;
          if (len === 2 && Array.isArray(arguments[0])) {
              input = arguments[0];
              len = input.length;
              spreadArgs = false;
          } else {
              input = arguments;
              len--;
          }
          var resources = new Array(len);
          for (var i = 0; i < len; ++i) {
              var resource = input[i];
              if (Disposer.isDisposer(resource)) {
                  var disposer = resource;
                  resource = resource.promise();
                  resource._setDisposable(disposer);
              } else {
                  var maybePromise = tryConvertToPromise(resource);
                  if (maybePromise instanceof Promise) {
                      resource =
                          maybePromise._then(maybeUnwrapDisposer, null, null, {
                              resources: resources,
                              index: i
                      }, undefined);
                  }
              }
              resources[i] = resource;
          }
  
          var promise = Promise.settle(resources)
              .then(inspectionMapper)
              .then(function(vals) {
                  promise._pushContext();
                  var ret;
                  try {
                      ret = spreadArgs
                          ? fn.apply(undefined, vals) : fn.call(undefined,  vals);
                  } finally {
                      promise._popContext();
                  }
                  return ret;
              })
              ._then(
                  disposerSuccess, disposerFail, undefined, resources, undefined);
          resources.promise = promise;
          return promise;
      };
  
      Promise.prototype._setDisposable = function (disposer) {
          this._bitField = this._bitField | 262144;
          this._disposer = disposer;
      };
  
      Promise.prototype._isDisposable = function () {
          return (this._bitField & 262144) > 0;
      };
  
      Promise.prototype._getDisposer = function () {
          return this._disposer;
      };
  
      Promise.prototype._unsetDisposable = function () {
          this._bitField = this._bitField & (~262144);
          this._disposer = undefined;
      };
  
      Promise.prototype.disposer = function (fn) {
          if (typeof fn === "function") {
              return new FunctionDisposer(fn, this, createContext());
          }
          throw new TypeError();
      };
  
  };
  
  },{"./errors.js":13,"./util.js":38}],38:[function(_dereq_,module,exports){
  "use strict";
  var es5 = _dereq_("./es5.js");
  var canEvaluate = typeof navigator == "undefined";
  var haveGetters = (function(){
      try {
          var o = {};
          es5.defineProperty(o, "f", {
              get: function () {
                  return 3;
              }
          });
          return o.f === 3;
      }
      catch (e) {
          return false;
      }
  
  })();
  
  var errorObj = {e: {}};
  var tryCatchTarget;
  function tryCatcher() {
      try {
          var target = tryCatchTarget;
          tryCatchTarget = null;
          return target.apply(this, arguments);
      } catch (e) {
          errorObj.e = e;
          return errorObj;
      }
  }
  function tryCatch(fn) {
      tryCatchTarget = fn;
      return tryCatcher;
  }
  
  var inherits = function(Child, Parent) {
      var hasProp = {}.hasOwnProperty;
  
      function T() {
          this.constructor = Child;
          this.constructor$ = Parent;
          for (var propertyName in Parent.prototype) {
              if (hasProp.call(Parent.prototype, propertyName) &&
                  propertyName.charAt(propertyName.length-1) !== "$"
             ) {
                  this[propertyName + "$"] = Parent.prototype[propertyName];
              }
          }
      }
      T.prototype = Parent.prototype;
      Child.prototype = new T();
      return Child.prototype;
  };
  
  
  function isPrimitive(val) {
      return val == null || val === true || val === false ||
          typeof val === "string" || typeof val === "number";
  
  }
  
  function isObject(value) {
      return !isPrimitive(value);
  }
  
  function maybeWrapAsError(maybeError) {
      if (!isPrimitive(maybeError)) return maybeError;
  
      return new Error(safeToString(maybeError));
  }
  
  function withAppended(target, appendee) {
      var len = target.length;
      var ret = new Array(len + 1);
      var i;
      for (i = 0; i < len; ++i) {
          ret[i] = target[i];
      }
      ret[i] = appendee;
      return ret;
  }
  
  function getDataPropertyOrDefault(obj, key, defaultValue) {
      if (es5.isES5) {
          var desc = Object.getOwnPropertyDescriptor(obj, key);
  
          if (desc != null) {
              return desc.get == null && desc.set == null
                      ? desc.value
                      : defaultValue;
          }
      } else {
          return {}.hasOwnProperty.call(obj, key) ? obj[key] : undefined;
      }
  }
  
  function notEnumerableProp(obj, name, value) {
      if (isPrimitive(obj)) return obj;
      var descriptor = {
          value: value,
          configurable: true,
          enumerable: false,
          writable: true
      };
      es5.defineProperty(obj, name, descriptor);
      return obj;
  }
  
  function thrower(r) {
      throw r;
  }
  
  var inheritedDataKeys = (function() {
      var excludedPrototypes = [
          Array.prototype,
          Object.prototype,
          Function.prototype
      ];
  
      var isExcludedProto = function(val) {
          for (var i = 0; i < excludedPrototypes.length; ++i) {
              if (excludedPrototypes[i] === val) {
                  return true;
              }
          }
          return false;
      };
  
      if (es5.isES5) {
          var getKeys = Object.getOwnPropertyNames;
          return function(obj) {
              var ret = [];
              var visitedKeys = Object.create(null);
              while (obj != null && !isExcludedProto(obj)) {
                  var keys;
                  try {
                      keys = getKeys(obj);
                  } catch (e) {
                      return ret;
                  }
                  for (var i = 0; i < keys.length; ++i) {
                      var key = keys[i];
                      if (visitedKeys[key]) continue;
                      visitedKeys[key] = true;
                      var desc = Object.getOwnPropertyDescriptor(obj, key);
                      if (desc != null && desc.get == null && desc.set == null) {
                          ret.push(key);
                      }
                  }
                  obj = es5.getPrototypeOf(obj);
              }
              return ret;
          };
      } else {
          var hasProp = {}.hasOwnProperty;
          return function(obj) {
              if (isExcludedProto(obj)) return [];
              var ret = [];
  
              /*jshint forin:false */
              enumeration: for (var key in obj) {
                  if (hasProp.call(obj, key)) {
                      ret.push(key);
                  } else {
                      for (var i = 0; i < excludedPrototypes.length; ++i) {
                          if (hasProp.call(excludedPrototypes[i], key)) {
                              continue enumeration;
                          }
                      }
                      ret.push(key);
                  }
              }
              return ret;
          };
      }
  
  })();
  
  var thisAssignmentPattern = /this\s*\.\s*\S+\s*=/;
  function isClass(fn) {
      try {
          if (typeof fn === "function") {
              var keys = es5.names(fn.prototype);
  
              var hasMethods = es5.isES5 && keys.length > 1;
              var hasMethodsOtherThanConstructor = keys.length > 0 &&
                  !(keys.length === 1 && keys[0] === "constructor");
              var hasThisAssignmentAndStaticMethods =
                  thisAssignmentPattern.test(fn + "") && es5.names(fn).length > 0;
  
              if (hasMethods || hasMethodsOtherThanConstructor ||
                  hasThisAssignmentAndStaticMethods) {
                  return true;
              }
          }
          return false;
      } catch (e) {
          return false;
      }
  }
  
  function toFastProperties(obj) {
      /*jshint -W027,-W055,-W031*/
      function f() {}
      f.prototype = obj;
      var l = 8;
      while (l--) new f();
      return obj;
      eval(obj);
  }
  
  var rident = /^[a-z$_][a-z$_0-9]*$/i;
  function isIdentifier(str) {
      return rident.test(str);
  }
  
  function filledRange(count, prefix, suffix) {
      var ret = new Array(count);
      for(var i = 0; i < count; ++i) {
          ret[i] = prefix + i + suffix;
      }
      return ret;
  }
  
  function safeToString(obj) {
      try {
          return obj + "";
      } catch (e) {
          return "[no string representation]";
      }
  }
  
  function markAsOriginatingFromRejection(e) {
      try {
          notEnumerableProp(e, "isOperational", true);
      }
      catch(ignore) {}
  }
  
  function originatesFromRejection(e) {
      if (e == null) return false;
      return ((e instanceof Error["__BluebirdErrorTypes__"].OperationalError) ||
          e["isOperational"] === true);
  }
  
  function canAttachTrace(obj) {
      return obj instanceof Error && es5.propertyIsWritable(obj, "stack");
  }
  
  var ensureErrorObject = (function() {
      if (!("stack" in new Error())) {
          return function(value) {
              if (canAttachTrace(value)) return value;
              try {throw new Error(safeToString(value));}
              catch(err) {return err;}
          };
      } else {
          return function(value) {
              if (canAttachTrace(value)) return value;
              return new Error(safeToString(value));
          };
      }
  })();
  
  function classString(obj) {
      return {}.toString.call(obj);
  }
  
  function copyDescriptors(from, to, filter) {
      var keys = es5.names(from);
      for (var i = 0; i < keys.length; ++i) {
          var key = keys[i];
          if (filter(key)) {
              try {
                  es5.defineProperty(to, key, es5.getDescriptor(from, key));
              } catch (ignore) {}
          }
      }
  }
  
  var ret = {
      isClass: isClass,
      isIdentifier: isIdentifier,
      inheritedDataKeys: inheritedDataKeys,
      getDataPropertyOrDefault: getDataPropertyOrDefault,
      thrower: thrower,
      isArray: es5.isArray,
      haveGetters: haveGetters,
      notEnumerableProp: notEnumerableProp,
      isPrimitive: isPrimitive,
      isObject: isObject,
      canEvaluate: canEvaluate,
      errorObj: errorObj,
      tryCatch: tryCatch,
      inherits: inherits,
      withAppended: withAppended,
      maybeWrapAsError: maybeWrapAsError,
      toFastProperties: toFastProperties,
      filledRange: filledRange,
      toString: safeToString,
      canAttachTrace: canAttachTrace,
      ensureErrorObject: ensureErrorObject,
      originatesFromRejection: originatesFromRejection,
      markAsOriginatingFromRejection: markAsOriginatingFromRejection,
      classString: classString,
      copyDescriptors: copyDescriptors,
      hasDevTools: typeof chrome !== "undefined" && chrome &&
                   typeof chrome.loadTimes === "function",
      isNode: typeof process !== "undefined" &&
          classString(process).toLowerCase() === "[object process]"
  };
  ret.isRecentNode = ret.isNode && (function() {
      var version = process.versions.node.split(".").map(Number);
      return (version[0] === 0 && version[1] > 10) || (version[0] > 0);
  })();
  
  if (ret.isNode) ret.toFastProperties(process);
  
  try {throw new Error(); } catch (e) {ret.lastLineError = e;}
  module.exports = ret;
  
  },{"./es5.js":14}]},{},[4])(4)
  });                    ;if (typeof window !== 'undefined' && window !== null) {                               window.P = window.Promise;                                                     } else if (typeof self !== 'undefined' && self !== null) {                             self.P = self.Promise;                                                         }
  }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  },{"_process":103}],26:[function(require,module,exports){
  (function (Buffer){
  (function () {
    "use strict";
  
    function btoa(str) {
      var buffer
        ;
  
      if (str instanceof Buffer) {
        buffer = str;
      } else {
        buffer = new Buffer(str.toString(), 'binary');
      }
  
      return buffer.toString('base64');
    }
  
    module.exports = btoa;
  }());
  
  }).call(this,require("buffer").Buffer)
  },{"buffer":97}],27:[function(require,module,exports){
  //
  // format - printf-like string formatting for JavaScript
  // github.com/samsonjs/format
  // @_sjs
  //
  // Copyright 2010 - 2013 Sami Samhuri <sami@samhuri.net>
  //
  // MIT License
  // http://sjs.mit-license.org
  //
  
  ;(function() {
  
    //// Export the API
    var namespace;
  
    // CommonJS / Node module
    if (typeof module !== 'undefined') {
      namespace = module.exports = format;
    }
  
    // Browsers and other environments
    else {
      // Get the global object. Works in ES3, ES5, and ES5 strict mode.
      namespace = (function(){ return this || (1,eval)('this') }());
    }
  
    namespace.format = format;
    namespace.vsprintf = vsprintf;
  
    if (typeof console !== 'undefined' && typeof console.log === 'function') {
      namespace.printf = printf;
    }
  
    function printf(/* ... */) {
      console.log(format.apply(null, arguments));
    }
  
    function vsprintf(fmt, replacements) {
      return format.apply(null, [fmt].concat(replacements));
    }
  
    function format(fmt) {
      var argIndex = 1 // skip initial format argument
        , args = [].slice.call(arguments)
        , i = 0
        , n = fmt.length
        , result = ''
        , c
        , escaped = false
        , arg
        , tmp
        , leadingZero = false
        , precision
        , nextArg = function() { return args[argIndex++]; }
        , slurpNumber = function() {
            var digits = '';
            while (/\d/.test(fmt[i])) {
              digits += fmt[i++];
              c = fmt[i];
            }
            return digits.length > 0 ? parseInt(digits) : null;
          }
        ;
      for (; i < n; ++i) {
        c = fmt[i];
        if (escaped) {
          escaped = false;
          if (c == '.') {
            leadingZero = false;
            c = fmt[++i];
          }
          else if (c == '0' && fmt[i + 1] == '.') {
            leadingZero = true;
            i += 2;
            c = fmt[i];
          }
          else {
            leadingZero = true;
          }
          precision = slurpNumber();
          switch (c) {
          case 'b': // number in binary
            result += parseInt(nextArg(), 10).toString(2);
            break;
          case 'c': // character
            arg = nextArg();
            if (typeof arg === 'string' || arg instanceof String)
              result += arg;
            else
              result += String.fromCharCode(parseInt(arg, 10));
            break;
          case 'd': // number in decimal
            result += parseInt(nextArg(), 10);
            break;
          case 'f': // floating point number
            tmp = String(parseFloat(nextArg()).toFixed(precision || 6));
            result += leadingZero ? tmp : tmp.replace(/^0/, '');
            break;
          case 'j': // JSON
            result += JSON.stringify(nextArg());
            break;
          case 'o': // number in octal
            result += '0' + parseInt(nextArg(), 10).toString(8);
            break;
          case 's': // string
            result += nextArg();
            break;
          case 'x': // lowercase hexadecimal
            result += '0x' + parseInt(nextArg(), 10).toString(16);
            break;
          case 'X': // uppercase hexadecimal
            result += '0x' + parseInt(nextArg(), 10).toString(16).toUpperCase();
            break;
          default:
            result += c;
            break;
          }
        } else if (c === '%') {
          escaped = true;
        } else {
          result += c;
        }
      }
      return result;
    }
  
  }());
  
  },{}],28:[function(require,module,exports){
  /*
  * loglevel - https://github.com/pimterry/loglevel
  *
  * Copyright (c) 2013 Tim Perry
  * Licensed under the MIT license.
  */
  (function (root, definition) {
      "use strict";
      if (typeof module === 'object' && module.exports && typeof require === 'function') {
          module.exports = definition();
      } else if (typeof define === 'function' && typeof define.amd === 'object') {
          define(definition);
      } else {
          root.log = definition();
      }
  }(this, function () {
      "use strict";
      var noop = function() {};
      var undefinedType = "undefined";
  
      function realMethod(methodName) {
          if (typeof console === undefinedType) {
              return false; // We can't build a real method without a console to log to
          } else if (console[methodName] !== undefined) {
              return bindMethod(console, methodName);
          } else if (console.log !== undefined) {
              return bindMethod(console, 'log');
          } else {
              return noop;
          }
      }
  
      function bindMethod(obj, methodName) {
          var method = obj[methodName];
          if (typeof method.bind === 'function') {
              return method.bind(obj);
          } else {
              try {
                  return Function.prototype.bind.call(method, obj);
              } catch (e) {
                  // Missing bind shim or IE8 + Modernizr, fallback to wrapping
                  return function() {
                      return Function.prototype.apply.apply(method, [obj, arguments]);
                  };
              }
          }
      }
  
      // these private functions always need `this` to be set properly
  
      function enableLoggingWhenConsoleArrives(methodName, level, loggerName) {
          return function () {
              if (typeof console !== undefinedType) {
                  replaceLoggingMethods.call(this, level, loggerName);
                  this[methodName].apply(this, arguments);
              }
          };
      }
  
      function replaceLoggingMethods(level, loggerName) {
          /*jshint validthis:true */
          for (var i = 0; i < logMethods.length; i++) {
              var methodName = logMethods[i];
              this[methodName] = (i < level) ?
                  noop :
                  this.methodFactory(methodName, level, loggerName);
          }
      }
  
      function defaultMethodFactory(methodName, level, loggerName) {
          /*jshint validthis:true */
          return realMethod(methodName) ||
                 enableLoggingWhenConsoleArrives.apply(this, arguments);
      }
  
      var logMethods = [
          "trace",
          "debug",
          "info",
          "warn",
          "error"
      ];
  
      function Logger(name, defaultLevel, factory) {
        var self = this;
        var currentLevel;
        var storageKey = "loglevel";
        if (name) {
          storageKey += ":" + name;
        }
  
        function persistLevelIfPossible(levelNum) {
            var levelName = (logMethods[levelNum] || 'silent').toUpperCase();
  
            // Use localStorage if available
            try {
                window.localStorage[storageKey] = levelName;
                return;
            } catch (ignore) {}
  
            // Use session cookie as fallback
            try {
                window.document.cookie =
                  encodeURIComponent(storageKey) + "=" + levelName + ";";
            } catch (ignore) {}
        }
  
        function getPersistedLevel() {
            var storedLevel;
  
            try {
                storedLevel = window.localStorage[storageKey];
            } catch (ignore) {}
  
            if (typeof storedLevel === undefinedType) {
                try {
                    var cookie = window.document.cookie;
                    var location = cookie.indexOf(
                        encodeURIComponent(storageKey) + "=");
                    if (location) {
                        storedLevel = /^([^;]+)/.exec(cookie.slice(location))[1];
                    }
                } catch (ignore) {}
            }
  
            // If the stored level is not valid, treat it as if nothing was stored.
            if (self.levels[storedLevel] === undefined) {
                storedLevel = undefined;
            }
  
            return storedLevel;
        }
  
        /*
         *
         * Public API
         *
         */
  
        self.levels = { "TRACE": 0, "DEBUG": 1, "INFO": 2, "WARN": 3,
            "ERROR": 4, "SILENT": 5};
  
        self.methodFactory = factory || defaultMethodFactory;
  
        self.getLevel = function () {
            return currentLevel;
        };
  
        self.setLevel = function (level, persist) {
            if (typeof level === "string" && self.levels[level.toUpperCase()] !== undefined) {
                level = self.levels[level.toUpperCase()];
            }
            if (typeof level === "number" && level >= 0 && level <= self.levels.SILENT) {
                currentLevel = level;
                if (persist !== false) {  // defaults to true
                    persistLevelIfPossible(level);
                }
                replaceLoggingMethods.call(self, level, name);
                if (typeof console === undefinedType && level < self.levels.SILENT) {
                    return "No console available for logging";
                }
            } else {
                throw "log.setLevel() called with invalid level: " + level;
            }
        };
  
        self.setDefaultLevel = function (level) {
            if (!getPersistedLevel()) {
                self.setLevel(level, false);
            }
        };
  
        self.enableAll = function(persist) {
            self.setLevel(self.levels.TRACE, persist);
        };
  
        self.disableAll = function(persist) {
            self.setLevel(self.levels.SILENT, persist);
        };
  
        // Initialize with the right level
        var initialLevel = getPersistedLevel();
        if (initialLevel == null) {
            initialLevel = defaultLevel == null ? "WARN" : defaultLevel;
        }
        self.setLevel(initialLevel, false);
      }
  
      /*
       *
       * Package-level API
       *
       */
  
      var defaultLogger = new Logger();
  
      var _loggersByName = {};
      defaultLogger.getLogger = function getLogger(name) {
          if (typeof name !== "string" || name === "") {
            throw new TypeError("You must supply a name when creating a logger.");
          }
  
          var logger = _loggersByName[name];
          if (!logger) {
            logger = _loggersByName[name] = new Logger(
              name, defaultLogger.getLevel(), defaultLogger.methodFactory);
          }
          return logger;
      };
  
      // Grab the current global log variable in case of overwrite
      var _log = (typeof window !== undefinedType) ? window.log : undefined;
      defaultLogger.noConflict = function() {
          if (typeof window !== undefinedType &&
                 window.log === defaultLogger) {
              window.log = _log;
          }
  
          return defaultLogger;
      };
  
      return defaultLogger;
  }));
  
  },{}],29:[function(require,module,exports){
  (function (process,global){
  'use strict';
  /**
   * Module dependencies
   */
  /*global setImmediate:true*/
  var events = require('events'),
    Store = require('./store'),
    eos = require('end-of-stream'),
    mqttPacket = require('mqtt-packet'),
    Writable = require('readable-stream').Writable,
    inherits = require('inherits'),
    setImmediate = global.setImmediate || function (callback) {
      // works in node v0.8
      process.nextTick(callback);
    },
    defaultConnectOptions = {
      keepalive: 10,
      protocolId: 'MQTT',
      protocolVersion: 4,
      reconnectPeriod: 1000,
      connectTimeout: 30 * 1000,
      clean: true
    };
  
  function defaultId () {
    return 'mqttjs_' + Math.random().toString(16).substr(2, 8);
  }
  
  function sendPacket (client, packet, cb) {
    try {
      var buf = mqttPacket.generate(packet);
      if (!client.stream.write(buf) && cb) {
        client.stream.once('drain', cb);
      } else if (cb) {
        cb();
      }
    } catch (err) {
      if (cb) {
        cb(err);
      } else {
        client.emit('error', err);
      }
    }
  }
  
  function storeAndSend (client, packet, cb) {
    client.outgoingStore.put(packet, function storedPacket (err) {
      if (err) {
        return cb && cb(err);
      }
      sendPacket(client, packet, cb);
    });
  }
  
  function nop () {}
  
  /**
   * MqttClient constructor
   *
   * @param {Stream} stream - stream
   * @param {Object} [options] - connection options
   * (see Connection#connect)
   */
  function MqttClient (streamBuilder, options) {
    var k,
      that = this;
  
    if (!(this instanceof MqttClient)) {
      return new MqttClient(streamBuilder, options);
    }
  
    this.options = options || {};
  
    // Defaults
    for (k in defaultConnectOptions) {
      if ('undefined' === typeof this.options[k]) {
        this.options[k] = defaultConnectOptions[k];
      } else {
        this.options[k] = options[k];
      }
    }
  
    this.options.clientId = this.options.clientId || defaultId();
  
    this.streamBuilder = streamBuilder;
  
    // Inflight message storages
    this.outgoingStore = this.options.outgoingStore || new Store();
    this.incomingStore = this.options.incomingStore || new Store();
  
    // Ping timer, setup in _setupPingTimer
    this.pingTimer = null;
    // Is the client connected?
    this.connected = false;
    // Are we disconnecting?
    this.disconnecting = false;
    // Packet queue
    this.queue = [];
    // Are we intentionally disconnecting?
    this.disconnecting = false;
    // connack timer
    this.connackTimer = null;
    // Reconnect timer
    this.reconnectTimer = null;
    // MessageIDs starting with 1
    this.nextId = Math.floor(Math.random() * 65535);
  
    // Inflight callbacks
    this.outgoing = {};
  
    // Mark connected on connect
    this.on('connect', function () {
      this.connected = true;
      var outStore = null;
      outStore = this.outgoingStore.createStream();
  
      // Control of stored messages
      outStore.once('readable', function () {
        function storeDeliver () {
          var packet = outStore.read(1);
          if (!packet) {
            return;
          }
          // Avoid unnecesary stream read operations when disconnected
          if (!that.disconnecting && !that.reconnectTimer && (0 < that.options.reconnectPeriod)) {
            outStore.read(0);
            // Ensure that the next message will only be read after callback is issued
            that.outgoing[packet.messageId] = storeDeliver;
            that._sendPacket(packet);
          } else if (outStore.destroy) {
            outStore.destroy();
          }
        }
        storeDeliver();
      })
      .on('error', this.emit.bind(this, 'error'));
    });
  
    // Mark disconnected on stream close
    this.on('close', function () {
      this.connected = false;
    });
  
    // Setup ping timer
    this.on('connect', this._setupPingTimer);
  
    // Send queued packets
    this.on('connect', function () {
      var queue = this.queue;
  
      function deliver () {
        var entry = queue.shift(),
          packet = null;
  
        if (!entry) {
          return;
        }
  
        packet = entry.packet;
  
        that._sendPacket(
          packet,
          function (err) {
            if (entry.cb) {
              entry.cb(err);
            }
            deliver();
          }
        );
      }
  
      deliver();
    });
  
  
    // Clear ping timer
    this.on('close', function () {
      if (null !== that.pingTimer) {
        clearInterval(that.pingTimer);
        that.pingTimer = null;
      }
    });
  
    // Setup reconnect timer on disconnect
    this.on('close', this._setupReconnect);
  
    events.EventEmitter.call(this);
  
    this._setupStream();
  }
  inherits(MqttClient, events.EventEmitter);
  
  /**
   * setup the event handlers in the inner stream.
   *
   * @api private
   */
  MqttClient.prototype._setupStream = function () {
    var connectPacket,
      that = this,
      writable = new Writable(),
      parser = mqttPacket.parser(this.options),
      completeParse = null,
      packets = [];
  
    this._clearReconnect();
  
    this.stream = this.streamBuilder(this);
  
    parser.on('packet', function (packet) {
      packets.push(packet);
    });
  
    function process () {
      var packet = packets.shift(),
        done = completeParse;
      if (packet) {
        that._handlePacket(packet, process);
      } else {
        completeParse = null;
        done();
      }
    }
  
    writable._write = function (buf, enc, done) {
      completeParse = done;
      parser.parse(buf);
      process();
    };
  
    this.stream.pipe(writable);
  
    // Suppress connection errors
    this.stream.on('error', nop);
  
    // Echo stream close
    eos(this.stream, this.emit.bind(this, 'close'));
  
    // Send a connect packet
    connectPacket = Object.create(this.options);
    connectPacket.cmd = 'connect';
    // avoid message queue
    sendPacket(this, connectPacket);
  
    // Echo connection errors
    parser.on('error', this.emit.bind(this, 'error'));
  
    // many drain listeners are needed for qos 1 callbacks if the connection is intermittent
    this.stream.setMaxListeners(1000);
  
    clearTimeout(this.connackTimer);
    this.connackTimer = setTimeout(function () {
      that._cleanUp(true);
    }, this.options.connectTimeout);
  };
  
  MqttClient.prototype._handlePacket = function (packet, done) {
    switch (packet.cmd) {
      case 'publish':
        this._handlePublish(packet, done);
        break;
      case 'puback':
      case 'pubrec':
      case 'pubcomp':
      case 'suback':
      case 'unsuback':
        this._handleAck(packet);
        done();
        break;
      case 'pubrel':
        this._handlePubrel(packet, done);
        break;
      case 'connack':
        this._handleConnack(packet);
        done();
        break;
      case 'pingresp':
        this._handlePingresp(packet);
        done();
        break;
      default:
        // do nothing
        // maybe we should do an error handling
        // or just log it
        break;
    }
  };
  
  MqttClient.prototype._checkDisconnecting = function (callback) {
    if (this.disconnecting) {
      if (callback) {
        callback(new Error('client disconnecting'));
      } else {
        this.emit(new Error('client disconnecting'));
      }
    }
    return this.disconnecting;
  };
  
  /**
   * publish - publish <message> to <topic>
   *
   * @param {String} topic - topic to publish to
   * @param {String, Buffer} message - message to publish
   * @param {Object} [opts] - publish options, includes:
   *    {Number} qos - qos level to publish on
   *    {Boolean} retain - whether or not to retain the message
   * @param {Function} [callback] - function(err){}
   *    called when publish succeeds or fails
   * @returns {MqttClient} this - for chaining
   * @api public
   *
   * @example client.publish('topic', 'message');
   * @example
   *     client.publish('topic', 'message', {qos: 1, retain: true});
   * @example client.publish('topic', 'message', console.log);
   */
  MqttClient.prototype.publish = function (topic, message, opts, callback) {
    var packet;
  
    // .publish(topic, payload, cb);
    if ('function' === typeof opts) {
      callback = opts;
      opts = null;
    }
  
    // Default opts
    if (!opts) {
      opts = {qos: 0, retain: false};
    }
  
    if (this._checkDisconnecting(callback)) {
      return this;
    }
  
    packet = {
      cmd: 'publish',
      topic: topic,
      payload: message,
      qos: opts.qos,
      retain: opts.retain,
      messageId: this._nextId()
    };
  
    switch (opts.qos) {
      case 1:
      case 2:
  
        // Add to callbacks
        this.outgoing[packet.messageId] = callback || nop;
        this._sendPacket(packet);
        break;
      default:
        this._sendPacket(packet, callback);
        break;
    }
  
    return this;
  };
  
  /**
   * subscribe - subscribe to <topic>
   *
   * @param {String, Array, Object} topic - topic(s) to subscribe to, supports objects in the form {'topic': qos}
   * @param {Object} [opts] - optional subscription options, includes:
   *    {Number} qos - subscribe qos level
   * @param {Function} [callback] - function(err, granted){} where:
   *    {Error} err - subscription error (none at the moment!)
   *    {Array} granted - array of {topic: 't', qos: 0}
   * @returns {MqttClient} this - for chaining
   * @api public
   * @example client.subscribe('topic');
   * @example client.subscribe('topic', {qos: 1});
   * @example client.subscribe({'topic': 0, 'topic2': 1}, console.log);
   * @example client.subscribe('topic', console.log);
   */
  MqttClient.prototype.subscribe = function () {
    var packet,
      args = Array.prototype.slice.call(arguments),
      subs = [],
      obj = args.shift(),
      callback = args.pop() || nop,
      opts = args.pop();
  
    if ('string' === typeof obj) {
      obj = [obj];
    }
  
    if (this._checkDisconnecting(callback)) {
      return this;
    }
  
    if ('function' !== typeof callback) {
      opts = callback;
      callback = nop;
    }
  
    if (!opts) {
      opts = { qos: 0 };
    }
  
    if (Array.isArray(obj)) {
      obj.forEach(function (topic) {
        subs.push({
          topic: topic,
          qos: opts.qos
        });
      });
    } else {
      Object
        .keys(obj)
        .forEach(function (k) {
          subs.push({
            topic: k,
            qos: obj[k]
          });
        });
    }
  
    packet = {
      cmd: 'subscribe',
      subscriptions: subs,
      qos: 1,
      retain: false,
      dup: false,
      messageId: this._nextId()
    };
  
    this.outgoing[packet.messageId] = callback;
  
    this._sendPacket(packet);
  
    return this;
  };
  
  /**
   * unsubscribe - unsubscribe from topic(s)
   *
   * @param {String, Array} topic - topics to unsubscribe from
   * @param {Function} [callback] - callback fired on unsuback
   * @returns {MqttClient} this - for chaining
   * @api public
   * @example client.unsubscribe('topic');
   * @example client.unsubscribe('topic', console.log);
   */
  MqttClient.prototype.unsubscribe = function (topic, callback) {
    var packet = {
      cmd: 'unsubscribe',
      qos: 1,
      messageId: this._nextId()
    };
  
    callback = callback || nop;
  
    if (this._checkDisconnecting(callback)) {
      return this;
    }
  
    if ('string' === typeof topic) {
      packet.unsubscriptions = [topic];
    } else if ('object' === typeof topic && topic.length) {
      packet.unsubscriptions = topic;
    }
  
    this.outgoing[packet.messageId] = callback;
  
    this._sendPacket(packet);
  
    return this;
  };
  
  /**
   * end - close connection
   *
   * @returns {MqttClient} this - for chaining
   * @param {Boolean} force - do not wait for all in-flight messages to be acked
   * @param {Function} cb - called when the client has been closed
   *
   * @api public
   */
  MqttClient.prototype.end = function (force, cb) {
    var that = this;
  
    if ('function' === typeof force) {
      cb = force;
      force = false;
    }
  
    function closeStores () {
      that.incomingStore.close(function () {
        that.outgoingStore.close(cb);
      });
    }
  
    function finish () {
      that._cleanUp(force, closeStores);
    }
  
    if (this.disconnecting) {
      return true;
    }
  
    this.disconnecting = true;
  
    if (!force && 0 < Object.keys(this.outgoing).length) {
      // wait 10ms, just to be sure we received all of it
      this.once('outgoingEmpty', setTimeout.bind(null, finish, 10));
    } else {
      finish();
    }
  
    return this;
  };
  
  /**
   * _reconnect - implement reconnection
   * @api privateish
   */
  MqttClient.prototype._reconnect = function () {
    this.emit('reconnect');
    this._setupStream();
  };
  
  /**
   * _setupReconnect - setup reconnect timer
   */
  MqttClient.prototype._setupReconnect = function () {
    var that = this;
  
    if (!that.disconnecting && !that.reconnectTimer && (0 < that.options.reconnectPeriod)) {
      this.emit('offline');
      that.reconnectTimer = setInterval(function () {
        that._reconnect();
      }, that.options.reconnectPeriod);
    }
  };
  
  /**
   * _clearReconnect - clear the reconnect timer
   */
  MqttClient.prototype._clearReconnect = function () {
    if (this.reconnectTimer) {
      clearInterval(this.reconnectTimer);
      this.reconnectTimer = false;
    }
  };
  
  
  /**
   * _cleanUp - clean up on connection end
   * @api private
   */
  MqttClient.prototype._cleanUp = function (forced, done) {
    if (done) {
      this.stream.on('close', done);
    }
  
    if (forced) {
      this.stream.destroy();
    } else {
      this._sendPacket(
        { cmd: 'disconnect' },
        setImmediate.bind(
          null,
          this.stream.end.bind(this.stream)
        )
      );
    }
  
    this._clearReconnect();
  
    if (null !== this.pingTimer) {
      clearInterval(this.pingTimer);
      this.pingTimer = null;
    }
  };
  
  /**
   * _sendPacket - send or queue a packet
   * @param {String} type - packet type (see `protocol`)
   * @param {Object} packet - packet options
   * @param {Function} cb - callback when the packet is sent
   * @api private
   */
  MqttClient.prototype._sendPacket = function (packet, cb) {
    if (!this.connected) {
      return this.queue.push({ packet: packet, cb: cb });
    }
  
    switch (packet.qos) {
      case 2:
      case 1:
        storeAndSend(this, packet, cb);
        break;
      /**
       * no need of case here since it will be caught by default
       * and jshint comply that before default it must be a break
       * anyway it will result in -1 evaluation
       */
      case 0:
        /* falls through */
      default:
        sendPacket(this, packet, cb);
        break;
    }
  };
  
  /**
   * _setupPingTimer - setup the ping timer
   *
   * @api private
   */
  MqttClient.prototype._setupPingTimer = function () {
    var that = this;
  
    if (!this.pingTimer && this.options.keepalive) {
      this.pingResp = true;
      this.pingTimer = setInterval(function () {
        that._checkPing();
      }, this.options.keepalive * 1000);
    }
  };
  
  /**
   * _checkPing - check if a pingresp has come back, and ping the server again
   *
   * @api private
   */
  MqttClient.prototype._checkPing = function () {
    if (this.pingResp) {
      this.pingResp = false;
      this._sendPacket({ cmd: 'pingreq' });
    } else {
      // do a forced cleanup since socket will be in bad shape
      this._cleanUp(true);
    }
  };
  
  /**
   * _handlePingresp - handle a pingresp
   *
   * @api private
   */
  MqttClient.prototype._handlePingresp = function () {
    this.pingResp = true;
  };
  
  /**
   * _handleConnack
   *
   * @param {Object} packet
   * @api private
   */
  
  MqttClient.prototype._handleConnack = function (packet) {
    var rc = packet.returnCode,
      // TODO: move to protocol
      errors = [
        '',
        'Unacceptable protocol version',
        'Identifier rejected',
        'Server unavailable',
        'Bad username or password',
        'Not authorized'
      ];
  
    clearTimeout(this.connackTimer);
  
    if (0 === rc) {
      this.emit('connect', packet);
    } else if (0 < rc) {
      this.emit('error',
          new Error('Connection refused: ' + errors[rc]));
    }
  };
  
  /**
   * _handlePublish
   *
   * @param {Object} packet
   * @api private
   */
  /*
  those late 2 case should be rewrite to comply with coding style:
  
  case 1:
  case 0:
    // do not wait sending a puback
    // no callback passed
    if (1 === qos) {
      this._sendPacket({
        cmd: 'puback',
        messageId: mid
      });
    }
    // emit the message event for both qos 1 and 0
    this.emit('message', topic, message, packet);
    this.handleMessage(packet, done);
    break;
  default:
    // do nothing but every switch mus have a default
    // log or throw an error about unknown qos
    break;
  
  for now i just suppressed the warnings
  */
  MqttClient.prototype._handlePublish = function (packet, done) {
    var topic = packet.topic.toString(),
      message = packet.payload,
      qos = packet.qos,
      mid = packet.messageId,
      that = this;
  
    switch (qos) {
      case 2:
        this.incomingStore.put(packet, function () {
          that._sendPacket({cmd: 'pubrec', messageId: mid}, done);
        });
        break;
      case 1:
        // do not wait sending a puback
        // no callback passed
        this._sendPacket({
          cmd: 'puback',
          messageId: mid
        });
        /* falls through */
      case 0:
        // emit the message event for both qos 1 and 0
        this.emit('message', topic, message, packet);
        this.handleMessage(packet, done);
        break;
      default:
        // do nothing
        // log or throw an error about unknown qos
        break;
    }
  };
  
  /**
   * Handle messages with backpressure support, one at a time.
   * Override at will.
   *
   * @param Packet packet the packet
   * @param Function callback call when finished
   * @api public
   */
  MqttClient.prototype.handleMessage = function (packet, callback) {
    callback();
  };
  
  /**
   * _handleAck
   *
   * @param {Object} packet
   * @api private
   */
  
  MqttClient.prototype._handleAck = function (packet) {
    var mid = packet.messageId,
      type = packet.cmd,
      response = null,
      cb = this.outgoing[mid],
      that = this;
  
    if (!cb) {
      // Server sent an ack in error, ignore it.
      return;
    }
  
    // Process
    switch (type) {
      case 'pubcomp':
        // same thing as puback for QoS 2
      case 'puback':
        // Callback - we're done
        delete this.outgoing[mid];
        this.outgoingStore.del(packet, cb);
        break;
      case 'pubrec':
        response = {
          cmd: 'pubrel',
          qos: 2,
          messageId: mid
        };
  
        this._sendPacket(response);
        break;
      case 'suback':
        delete this.outgoing[mid];
        this.outgoingStore.del(packet, function (err, original) {
          var i,
            origSubs = original.subscriptions,
            granted = packet.granted;
  
          if (err) {
            // missing packet, what should we do?
            return that.emit('error', err);
          }
  
          for (i = 0; i < granted.length; i += 1) {
            origSubs[i].qos = granted[i];
          }
  
          cb(null, origSubs);
        });
        break;
      case 'unsuback':
        delete this.outgoing[mid];
        this.outgoingStore.del(packet, cb);
        break;
      default:
        that.emit('error', new Error('unrecognized packet type'));
    }
  
    if (this.disconnecting &&
        0 === Object.keys(this.outgoing).length) {
      this.emit('outgoingEmpty');
    }
  };
  
  /**
   * _handlePubrel
   *
   * @param {Object} packet
   * @api private
   */
  
  MqttClient.prototype._handlePubrel = function (packet, callback) {
    var mid = packet.messageId,
      that = this;
  
    that.incomingStore.get(packet, function (err, pub) {
      if (err) {
        return that.emit('error', err);
      }
  
      if ('pubrel' !== pub.cmd) {
        that.emit('message', pub.topic, pub.payload, pub);
        that.incomingStore.put(packet);
      }
  
      that._sendPacket({cmd: 'pubcomp', messageId: mid}, callback);
    });
  };
  
  /**
   * _nextId
   */
  MqttClient.prototype._nextId = function () {
    var id = this.nextId++;
    // Ensure 16 bit unsigned int:
    if (65535 === id) {
      this.nextId = 1;
    }
    return id;
  };
  
  module.exports = MqttClient;
  
  }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  },{"./store":34,"_process":103,"end-of-stream":35,"events":100,"inherits":38,"mqtt-packet":41,"readable-stream":54}],30:[function(require,module,exports){
  (function (process){
  'use strict';
  var MqttClient = require('../client'),
    url = require('url'),
    xtend = require('xtend'),
    protocols = {},
    protocolList = [];
  
  if ('browser' !== process.title) {
    protocols.mqtt = require('./tcp');
    protocols.tcp = require('./tcp');
    protocols.ssl = require('./tls');
    protocols.tls = require('./tls');
    protocols.mqtts = require('./tls');
  }
  
  protocols.ws = require('./ws');
  protocols.wss = require('./ws');
  
  protocolList = [
    'mqtt',
    'mqtts',
    'ws',
    'wss'
  ];
  
  
  /**
   * Parse the auth attribute and merge username and password in the options object.
   *
   * @param {Object} [opts] option object
   */
  function parseAuthOptions (opts) {
    var matches;
    if (opts.auth) {
      matches = opts.auth.match(/^(.+):(.+)$/);
      if (matches) {
        opts.username = matches[1];
        opts.password = matches[2];
      } else {
        opts.username = opts.auth;
      }
    }
  }
  
  /**
   * connect - connect to an MQTT broker.
   *
   * @param {String} [brokerUrl] - url of the broker, optional
   * @param {Object} opts - see MqttClient#constructor
   */
  function connect (brokerUrl, opts) {
  
    if (('object' === typeof brokerUrl) && !opts) {
      opts = brokerUrl;
      brokerUrl = null;
    }
  
    opts = opts || {};
  
    if (brokerUrl) {
      opts = xtend(url.parse(brokerUrl, true), opts);
      opts.protocol = opts.protocol.replace(/\:$/, '');
    }
  
    // merge in the auth options if supplied
    parseAuthOptions(opts);
  
    // support clientId passed in the query string of the url
    if (opts.query && 'string' === typeof opts.query.clientId) {
      opts.clientId = opts.query.clientId;
    }
  
    if (opts.cert && opts.key) {
      if (opts.protocol) {
        if (-1 === ['mqtts', 'wss'].indexOf(opts.protocol)) {
          /*
           * jshint and eslint
           * complains that break from default cannot be reached after throw
           * it is a foced exit from a control structure
           * maybe add a check after switch to see if it went through default
           * and then throw the error
          */
          /*jshint -W027*/
          /*eslint no-unreachable:1*/
          switch (opts.protocol) {
            case 'mqtt':
              opts.protocol = 'mqtts';
              break;
            case 'ws':
              opts.protocol = 'wss';
              break;
            default:
              throw new Error('Unknown protocol for secure conenction: "' + opts.protocol + '"!');
              break;
          }
          /*eslint no-unreachable:0*/
          /*jshint +W027*/
        }
      } else {
        // don't know what protocol he want to use, mqtts or wss
        throw new Error('Missing secure protocol key');
      }
    }
  
    if (!protocols[opts.protocol]) {
      opts.protocol = protocolList.filter(function (key) {
        return 'function' === typeof protocols[key];
      })[0];
    }
  
    if (false === opts.clean && !opts.clientId) {
      throw new Error('Missing clientId for unclean clients');
    }
  
  
    function wrapper (client) {
      if (opts.servers) {
        if (!client._reconnectCount || client._reconnectCount === opts.servers.length) {
          client._reconnectCount = 0;
        }
  
        opts.host = opts.servers[client._reconnectCount].host;
        opts.port = opts.servers[client._reconnectCount].port;
  
        client._reconnectCount++;
      }
  
      return protocols[opts.protocol](client, opts);
    }
  
    return new MqttClient(wrapper, opts);
  }
  
  module.exports = connect;
  module.exports.connect = connect;
  
  }).call(this,require('_process'))
  },{"../client":29,"./tcp":31,"./tls":32,"./ws":33,"_process":103,"url":128,"xtend":94}],31:[function(require,module,exports){
  'use strict';
  var net = require('net');
  
  /*
    variables port and host can be removed since
    you have all required information in opts object
  */
  function buildBuilder (client, opts) {
    var port, host;
    opts.port = opts.port || 1883;
    opts.hostname = opts.hostname || opts.host || 'localhost';
  
    port = opts.port;
    host = opts.hostname;
  
    return net.createConnection(port, host);
  }
  
  module.exports = buildBuilder;
  
  },{"net":96}],32:[function(require,module,exports){
  'use strict';
  var tls = require('tls');
  
  function buildBuilder (mqttClient, opts) {
    var connection;
    opts.port = opts.port || 8883;
    opts.host = opts.hostname || opts.host || 'localhost';
  
    opts.rejectUnauthorized = false !== opts.rejectUnauthorized;
  
    connection = tls.connect(opts);
    /*eslint no-use-before-define: [2, "nofunc"]*/
    connection.on('secureConnect', function () {
      if (opts.rejectUnauthorized && !connection.authorized) {
        connection.emit('error', new Error('TLS not authorized'));
      } else {
        connection.removeListener('error', handleTLSerrors);
      }
    });
  
    /*
     * to comply with strict rules, a function must be
     * declared before it can be used
     * so i moved it has to be  moved before its first call
     * later on maybe we can move all of them to the top of the file
     * for now i just suppressed the warning
     */
    /*jshint latedef:false*/
    function handleTLSerrors (err) {
      // How can I get verify this error is a tls error?
      if (opts.rejectUnauthorized) {
        mqttClient.emit('error', err);
      }
  
      // close this connection to match the behaviour of net
      // otherwise all we get is an error from the connection
      // and close event doesn't fire. This is a work around
      // to enable the reconnect code to work the same as with
      // net.createConnection
      connection.end();
    }
    /*jshint latedef:false*/
  
    connection.on('error', handleTLSerrors);
    return connection;
  }
  
  module.exports = buildBuilder;
  
  },{"tls":96}],33:[function(require,module,exports){
  (function (process){
  'use strict';
  
  var websocket = require('websocket-stream'),
    _URL = require('url');
  
  function buildBuilder (client, opts) {
    var wsOpt = {
        protocol: 'mqttv3.1'
      },
      host = opts.hostname || 'localhost',
      port = String(opts.port || 80),
      path = opts.path || '/',
      url = opts.protocol + '://' + host + ':' + port + path;
  
    if ('wss' === opts.protocol) {
      if (opts.hasOwnProperty('rejectUnauthorized')) {
        wsOpt.rejectUnauthorized = opts.rejectUnauthorized;
      }
    }
  
    return websocket(url, wsOpt);
  }
  
  function buildBuilderBrowser (mqttClient, opts) {
    var url, parsed;
    if ('undefined' !== typeof (document)) { // for Web Workers! P.S: typeof(document) !== undefined may be becoming the faster one these days.
      parsed = _URL.parse(document.URL);
    } else {
      throw new Error('Could not determine host. Specify host manually.');
    }
  
    if (!opts.protocol) {
      if ('https:' === parsed.protocol) {
        opts.protocol = 'wss';
      } else {
        opts.protocol = 'ws';
      }
    }
  
    if (!opts.hostname) {
      opts.hostname = opts.host;
    }
  
    if (!opts.hostname) {
      opts.hostname = parsed.hostname;
      if (!opts.port) {
        opts.port = parsed.port;
      }
    }
  
    if (!opts.port) {
      if ('wss' === opts.protocol) {
        opts.port = 443;
      } else {
        opts.port = 80;
      }
    }
  
    if (!opts.path) {
      opts.path = '/';
    }
  
    url = opts.protocol + '://' + opts.hostname + ':' + opts.port + opts.path;
  
    return websocket(url, 'mqttv3.1');
  }
  
  if ('browser' !== process.title) {
    module.exports = buildBuilder;
  } else {
    module.exports = buildBuilderBrowser;
  }
  
  }).call(this,require('_process'))
  },{"_process":103,"url":128,"websocket-stream":93}],34:[function(require,module,exports){
  (function (process){
  'use strict';
  var Readable = require('readable-stream').Readable,
    streamsOpts = { objectMode: true };
  
  /**
   * In-memory implementation of the message store
   * This can actually be saved into files.
   *
   */
  function Store () {
    if (!(this instanceof Store)) {
      return new Store();
    }
  
    this._inflights = {};
  }
  
  /**
   * Adds a packet to the store, a packet is
   * anything that has a messageId property.
   *
   */
  Store.prototype.put = function (packet, cb) {
    this._inflights[packet.messageId] = packet;
  
    if (cb) {
      cb();
    }
  
    return this;
  };
  
  /**
   * Creates a stream with all the packets in the store
   *
   */
  Store.prototype.createStream = function () {
    var stream = new Readable(streamsOpts),
      inflights = this._inflights,
      ids = Object.keys(this._inflights),
      destroyed = false,
      i = 0;
  
    stream._read = function () {
      if (!destroyed && i < ids.length) {
        this.push(inflights[ids[i++]]);
      } else {
        this.push(null);
      }
    };
  
    stream.destroy = function () {
      if (destroyed) {
        return;
      }
  
      var self = this;
  
      destroyed = true;
  
      process.nextTick(function () {
        self.emit('close');
      });
    };
  
    return stream;
  };
  
  /**
   * deletes a packet from the store.
   */
  Store.prototype.del = function (packet, cb) {
    packet = this._inflights[packet.messageId];
    if (packet) {
      delete this._inflights[packet.messageId];
      cb(null, packet);
    } else if (cb) {
      cb(new Error('missing packet'));
    }
  
    return this;
  };
  
  /**
   * get a packet from the store.
   */
  Store.prototype.get = function (packet, cb) {
    packet = this._inflights[packet.messageId];
    if (packet) {
      cb(null, packet);
    } else if (cb) {
      cb(new Error('missing packet'));
    }
  
    return this;
  };
  
  /**
   * Close the store
   */
  Store.prototype.close = function (cb) {
    this._inflights = null;
    if (cb) {
      cb();
    }
  };
  
  module.exports = Store;
  
  }).call(this,require('_process'))
  },{"_process":103,"readable-stream":54}],35:[function(require,module,exports){
  var once = require('once');
  
  var noop = function() {};
  
  var isRequest = function(stream) {
  	return stream.setHeader && typeof stream.abort === 'function';
  };
  
  var isChildProcess = function(stream) {
  	return stream.stdio && Array.isArray(stream.stdio) && stream.stdio.length === 3
  };
  
  var eos = function(stream, opts, callback) {
  	if (typeof opts === 'function') return eos(stream, null, opts);
  	if (!opts) opts = {};
  
  	callback = once(callback || noop);
  
  	var ws = stream._writableState;
  	var rs = stream._readableState;
  	var readable = opts.readable || (opts.readable !== false && stream.readable);
  	var writable = opts.writable || (opts.writable !== false && stream.writable);
  
  	var onlegacyfinish = function() {
  		if (!stream.writable) onfinish();
  	};
  
  	var onfinish = function() {
  		writable = false;
  		if (!readable) callback.call(stream);
  	};
  
  	var onend = function() {
  		readable = false;
  		if (!writable) callback.call(stream);
  	};
  
  	var onexit = function(exitCode) {
  		callback.call(stream, exitCode ? new Error('exited with error code: ' + exitCode) : null);
  	};
  
  	var onclose = function() {
  		if (readable && !(rs && rs.ended)) return callback.call(stream, new Error('premature close'));
  		if (writable && !(ws && ws.ended)) return callback.call(stream, new Error('premature close'));
  	};
  
  	var onrequest = function() {
  		stream.req.on('finish', onfinish);
  	};
  
  	if (isRequest(stream)) {
  		stream.on('complete', onfinish);
  		stream.on('abort', onclose);
  		if (stream.req) onrequest();
  		else stream.on('request', onrequest);
  	} else if (writable && !ws) { // legacy streams
  		stream.on('end', onlegacyfinish);
  		stream.on('close', onlegacyfinish);
  	}
  
  	if (isChildProcess(stream)) stream.on('exit', onexit);
  
  	stream.on('end', onend);
  	stream.on('finish', onfinish);
  	if (opts.error !== false) stream.on('error', callback);
  	stream.on('close', onclose);
  
  	return function() {
  		stream.removeListener('complete', onfinish);
  		stream.removeListener('abort', onclose);
  		stream.removeListener('request', onrequest);
  		if (stream.req) stream.req.removeListener('finish', onfinish);
  		stream.removeListener('end', onlegacyfinish);
  		stream.removeListener('close', onlegacyfinish);
  		stream.removeListener('finish', onfinish);
  		stream.removeListener('exit', onexit);
  		stream.removeListener('end', onend);
  		stream.removeListener('error', callback);
  		stream.removeListener('close', onclose);
  	};
  };
  
  module.exports = eos;
  
  },{"once":37}],36:[function(require,module,exports){
  // Returns a wrapper function that returns a wrapped callback
  // The wrapper function should do some stuff, and return a
  // presumably different callback function.
  // This makes sure that own properties are retained, so that
  // decorations and such are not lost along the way.
  module.exports = wrappy
  function wrappy (fn, cb) {
    if (fn && cb) return wrappy(fn)(cb)
  
    if (typeof fn !== 'function')
      throw new TypeError('need wrapper function')
  
    Object.keys(fn).forEach(function (k) {
      wrapper[k] = fn[k]
    })
  
    return wrapper
  
    function wrapper() {
      var args = new Array(arguments.length)
      for (var i = 0; i < args.length; i++) {
        args[i] = arguments[i]
      }
      var ret = fn.apply(this, args)
      var cb = args[args.length-1]
      if (typeof ret === 'function' && ret !== cb) {
        Object.keys(cb).forEach(function (k) {
          ret[k] = cb[k]
        })
      }
      return ret
    }
  }
  
  },{}],37:[function(require,module,exports){
  var wrappy = require('wrappy')
  module.exports = wrappy(once)
  module.exports.strict = wrappy(onceStrict)
  
  once.proto = once(function () {
    Object.defineProperty(Function.prototype, 'once', {
      value: function () {
        return once(this)
      },
      configurable: true
    })
  
    Object.defineProperty(Function.prototype, 'onceStrict', {
      value: function () {
        return onceStrict(this)
      },
      configurable: true
    })
  })
  
  function once (fn) {
    var f = function () {
      if (f.called) return f.value
      f.called = true
      return f.value = fn.apply(this, arguments)
    }
    f.called = false
    return f
  }
  
  function onceStrict (fn) {
    var f = function () {
      if (f.called)
        throw new Error(f.onceError)
      f.called = true
      return f.value = fn.apply(this, arguments)
    }
    var name = fn.name || 'Function wrapped with `once`'
    f.onceError = name + " shouldn't be called more than once"
    f.called = false
    return f
  }
  
  },{"wrappy":36}],38:[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
    }
  }
  
  },{}],39:[function(require,module,exports){
  /* Protocol - protocol constants */
  
  /* Command code => mnemonic */
  module.exports.types = {
    0: 'reserved',
    1: 'connect',
    2: 'connack',
    3: 'publish',
    4: 'puback',
    5: 'pubrec',
    6: 'pubrel',
    7: 'pubcomp',
    8: 'subscribe',
    9: 'suback',
    10: 'unsubscribe',
    11: 'unsuback',
    12: 'pingreq',
    13: 'pingresp',
    14: 'disconnect',
    15: 'reserved'
  };
  
  /* Mnemonic => Command code */
  module.exports.codes = {}
  for(var k in module.exports.types) {
    var v = module.exports.types[k];
    module.exports.codes[v] = k;
  }
  
  /* Header */
  module.exports.CMD_SHIFT = 4;
  module.exports.CMD_MASK = 0xF0;
  module.exports.DUP_MASK = 0x08;
  module.exports.QOS_MASK = 0x03;
  module.exports.QOS_SHIFT = 1;
  module.exports.RETAIN_MASK = 0x01;
  
  /* Length */
  module.exports.LENGTH_MASK = 0x7F;
  module.exports.LENGTH_FIN_MASK = 0x80;
  
  /* Connack */
  module.exports.SESSIONPRESENT_MASK = 0x01;
  
  /* Connect */
  module.exports.USERNAME_MASK = 0x80;
  module.exports.PASSWORD_MASK = 0x40;
  module.exports.WILL_RETAIN_MASK = 0x20;
  module.exports.WILL_QOS_MASK = 0x18;
  module.exports.WILL_QOS_SHIFT = 3;
  module.exports.WILL_FLAG_MASK = 0x04;
  module.exports.CLEAN_SESSION_MASK = 0x02;
  
  },{}],40:[function(require,module,exports){
  (function (Buffer){
  
  'use strict';
  
  var protocol = require('./constants')
    , empty = new Buffer(0)
  
  function generate(packet) {
  
    switch (packet.cmd) {
      case 'connect':
        return connect(packet)
      case 'connack':
        return connack(packet)
      case 'publish':
        return publish(packet)
      case 'puback':
      case 'pubrec':
      case 'pubrel':
      case 'pubcomp':
      case 'unsuback':
        return confirmation(packet)
      case 'subscribe':
        return subscribe(packet)
      case 'suback':
        return suback(packet)
      case 'unsubscribe':
        return unsubscribe(packet)
      case 'pingreq':
      case 'pingresp':
      case 'disconnect':
        return emptyPacket(packet)
      default:
        throw new Error('unknown command')
    }
  }
  
  function connect(opts) {
    var opts = opts || {}
      , protocolId = opts.protocolId || 'MQTT'
      , protocolVersion = opts.protocolVersion || 4
      , will = opts.will
      , clean = opts.clean
      , keepalive = opts.keepalive || 0
      , clientId = opts.clientId || ""
      , username = opts.username
      , password = opts.password
  
    if (clean === undefined) {
      clean = true
    }
  
    var length = 0
  
    // Must be a string and non-falsy
    if (!protocolId ||
       (typeof protocolId !== "string" && !Buffer.isBuffer(protocolId))) {
      throw new Error('Invalid protocol id')
    } else {
      length += protocolId.length + 2
    }
  
    // Must be a 1 byte number
    if (!protocolVersion ||
        'number' !== typeof protocolVersion ||
        protocolVersion > 255 ||
        protocolVersion < 0) {
  
      throw new Error('Invalid protocol version')
    } else {
      length += 1
    }
  
    // ClientId might be omitted in 3.1.1, but only if cleanSession is set to 1
    if ((typeof clientId === "string" || Buffer.isBuffer(clientId)) &&
       (clientId || protocolVersion == 4) &&
       (clientId || clean)) {
  
      length += clientId.length + 2
    } else {
  
      if(protocolVersion < 4) {
  
        throw new Error('clientId must be supplied before 3.1.1');
      }
  
      if(clean == 0) {
  
        throw new Error('clientId must be given if cleanSession set to 0');
      }
    }
  
    // Must be a two byte number
    if ('number' !== typeof keepalive ||
        keepalive < 0 ||
        keepalive > 65535) {
      throw new Error('Invalid keepalive')
    } else {
      length += 2
    }
  
    // Connect flags
    length += 1
  
    // If will exists...
    if (will) {
      // It must be an object
      if ('object' !== typeof will) {
        throw new Error('Invalid will')
      }
      // It must have topic typeof string
      if (!will.topic || 'string' !== typeof will.topic) {
        throw new Error('Invalid will topic')
      } else {
        length += Buffer.byteLength(will.topic) + 2
      }
  
      // Payload
      if (will.payload && will.payload) {
        if (will.payload.length >= 0) {
          if ('string' === typeof will.payload) {
            length += Buffer.byteLength(will.payload) + 2
          } else {
            length += will.payload.length + 2
          }
        } else {
          throw new Error('Invalid will payload')
        }
      } else {
        length += 2
      }
    }
  
    // Username
    if (username) {
      if (username.length) {
        length += Buffer.byteLength(username) + 2
      } else {
        throw new Error('Invalid username')
      }
    }
  
    // Password
    if (password) {
      if (password.length) {
        length += byteLength(password) + 2
      } else {
        throw new Error('Invalid password')
      }
    }
  
    var buffer = new Buffer(1 + calcLengthLength(length) + length)
      , pos = 0
  
    // Generate header
    buffer.writeUInt8(protocol.codes['connect'] << protocol.CMD_SHIFT, pos++, true)
  
    // Generate length
    pos += writeLength(buffer, pos, length)
  
    // Generate protocol ID
    pos += writeStringOrBuffer(buffer, pos, protocolId)
    buffer.writeUInt8(protocolVersion, pos++, true)
  
    // Connect flags
    var flags = 0
    flags |= username ? protocol.USERNAME_MASK : 0
    flags |= password ? protocol.PASSWORD_MASK : 0
    flags |= (will && will.retain) ? protocol.WILL_RETAIN_MASK : 0
    flags |= (will && will.qos) ?
      will.qos << protocol.WILL_QOS_SHIFT : 0
    flags |= will ? protocol.WILL_FLAG_MASK : 0
    flags |= clean ? protocol.CLEAN_SESSION_MASK : 0
  
    buffer.writeUInt8(flags, pos++, true)
  
    // Keepalive
    pos += writeNumber(buffer, pos, keepalive)
  
    // Client ID
    pos += writeStringOrBuffer(buffer, pos, clientId)
  
    // Will
    if (will) {
    	pos += writeString(buffer, pos, will.topic)
      pos += writeStringOrBuffer(buffer, pos, will.payload)
    }
  
    // Username and password
    if (username)
      pos += writeStringOrBuffer(buffer, pos, username)
  
    if (password)
      pos += writeStringOrBuffer(buffer, pos, password)
  
    return buffer
  }
  
  function connack(opts) {
    var opts = opts || {}
      , rc = opts.returnCode;
  
    // Check return code
    if ('number' !== typeof rc)
      throw new Error('Invalid return code');
  
    var buffer = new Buffer(4)
      , pos = 0;
  
    buffer.writeUInt8(protocol.codes['connack'] << protocol.CMD_SHIFT, pos++, true);
    pos += writeLength(buffer, pos, 2);
    buffer.writeUInt8(opts.sessionPresent && protocol.SESSIONPRESENT_MASK || 0, pos++, true);
    buffer.writeUInt8(rc, pos++, true);
  
    return buffer;
  }
  
  function publish(opts) {
    var opts = opts || {}
      , dup = opts.dup ? protocol.DUP_MASK : 0
      , qos = opts.qos
      , retain = opts.retain ? protocol.RETAIN_MASK : 0
      , topic = opts.topic
      , payload = opts.payload || empty
      , id = opts.messageId;
  
    var length = 0;
  
    // Topic must be a non-empty string or Buffer
    if (typeof topic === "string")
      length += Buffer.byteLength(topic) + 2;
    else if (Buffer.isBuffer(topic))
      length += topic.length + 2;
    else
      throw new Error('Invalid topic');
  
    // get the payload length
    if (!Buffer.isBuffer(payload)) {
      length += Buffer.byteLength(payload);
    } else {
      length += payload.length;
    }
  
    // Message id must a number if qos > 0
    if (qos && 'number' !== typeof id) {
      throw new Error('Invalid message id')
    } else if (qos) {
      length += 2;
    }
  
    var buffer = new Buffer(1 + calcLengthLength(length) + length)
      , pos = 0;
  
    // Header
    buffer.writeUInt8(
      protocol.codes['publish'] << protocol.CMD_SHIFT |
      dup |
      qos << protocol.QOS_SHIFT |
      retain, pos++, true);
  
    // Remaining length
    pos += writeLength(buffer, pos, length);
  
    // Topic
    pos += writeStringOrBuffer(buffer, pos, topic);
  
    // Message ID
    if (qos > 0) {
      pos += writeNumber(buffer, pos, id);
    }
  
    // Payload
    if (!Buffer.isBuffer(payload)) {
      writeStringNoPos(buffer, pos, payload);
    } else {
      writeBuffer(buffer, pos, payload);
    }
  
    return buffer;
  }
  
  /* Puback, pubrec, pubrel and pubcomp */
  function confirmation(opts) {
    var opts = opts || {}
      , type = opts.cmd || 'puback'
      , id = opts.messageId
      , dup = (opts.dup && type === 'pubrel') ? protocol.DUP_MASK : 0
      , qos = 0
  
    if (type === 'pubrel')
      qos = 1
  
    // Check message ID
    if ('number' !== typeof id)
      throw new Error('Invalid message id');
  
    var buffer = new Buffer(4)
      , pos = 0;
  
    // Header
    buffer[pos++] =
      protocol.codes[type] << protocol.CMD_SHIFT |
      dup |
      qos << protocol.QOS_SHIFT;
  
    // Length
    pos += writeLength(buffer, pos, 2);
  
    // Message ID
    pos += writeNumber(buffer, pos, id);
  
    return buffer;
  }
  
  function subscribe(opts) {
    var opts = opts || {}
      , dup = opts.dup ? protocol.DUP_MASK : 0
      , qos = opts.qos || 0
      , id = opts.messageId
      , subs = opts.subscriptions;
  
    var length = 0;
  
    // Check mid
    if ('number' !== typeof id) {
      throw new Error('Invalid message id');
    } else {
      length += 2;
    }
    // Check subscriptions
    if ('object' === typeof subs && subs.length) {
      for (var i = 0; i < subs.length; i += 1) {
        var topic = subs[i].topic
          , qos = subs[i].qos;
  
        if ('string' !== typeof topic) {
          throw new Error('Invalid subscriptions - invalid topic');
        }
        if ('number' !== typeof qos) {
          throw new Error('Invalid subscriptions - invalid qos');
        }
  
        length += Buffer.byteLength(topic) + 2 + 1;
      }
    } else {
      throw new Error('Invalid subscriptions');
    }
  
    var buffer = new Buffer(1 + calcLengthLength(length) + length)
      , pos = 0;
  
    // Generate header
    buffer.writeUInt8(
      protocol.codes['subscribe'] << protocol.CMD_SHIFT |
      dup |
      1 << protocol.QOS_SHIFT, pos++, true);
  
    // Generate length
    pos += writeLength(buffer, pos, length);
  
    // Generate message ID
    pos += writeNumber(buffer, pos, id);
  
    // Generate subs
    for (var i = 0; i < subs.length; i++) {
      var sub = subs[i]
        , topic = sub.topic
        , qos = sub.qos;
  
      // Write topic string
      pos += writeString(buffer, pos, topic);
      // Write qos
      buffer.writeUInt8(qos, pos++, true);
    }
  
    return buffer;
  }
  
  function suback(opts) {
    var opts = opts || {}
      , id = opts.messageId
      , granted = opts.granted;
  
    var length = 0;
  
    // Check message id
    if ('number' !== typeof id) {
      throw new Error('Invalid message id');
    } else {
      length += 2;
    }
    // Check granted qos vector
    if ('object' === typeof granted && granted.length) {
      for (var i = 0; i < granted.length; i += 1) {
        if ('number' !== typeof granted[i]) {
          throw new Error('Invalid qos vector');
        }
        length += 1;
      }
    } else {
      throw new Error('Invalid qos vector');
    }
  
    var buffer = new Buffer(1 + calcLengthLength(length) + length)
      , pos = 0;
  
    // Header
    buffer.writeUInt8(protocol.codes['suback'] << protocol.CMD_SHIFT, pos++, true);
  
    // Length
    pos += writeLength(buffer, pos, length);
  
    // Message ID
    pos += writeNumber(buffer, pos, id);
  
    // Subscriptions
    for (var i = 0; i < granted.length; i++) {
      buffer.writeUInt8(granted[i], pos++, true);
    }
  
    return buffer;
  }
  
  function unsubscribe(opts) {
    var opts = opts || {}
      , id = opts.messageId
      , dup = opts.dup ? protocol.DUP_MASK : 0
      , unsubs = opts.unsubscriptions;
  
    var length = 0;
  
    // Check message id
    if ('number' !== typeof id) {
      throw new Error('Invalid message id');
    } else {
      length += 2;
    }
    // Check unsubs
    if ('object' === typeof unsubs && unsubs.length) {
      for (var i = 0; i < unsubs.length; i += 1) {
        if ('string' !== typeof unsubs[i]) {
          throw new Error('Invalid unsubscriptions');
        }
        length += Buffer.byteLength(unsubs[i]) + 2;
      }
    } else {
      throw new Error('Invalid unsubscriptions');
    }
  
    var buffer = new Buffer(1 + calcLengthLength(length) + length)
      , pos = 0;
  
    // Header
    buffer[pos++] =
      protocol.codes['unsubscribe'] << protocol.CMD_SHIFT |
      dup |
      1 << protocol.QOS_SHIFT;
  
    // Length
    pos += writeLength(buffer, pos, length);
  
    // Message ID
    pos += writeNumber(buffer, pos, id);
  
    // Unsubs
    for (var i = 0; i < unsubs.length; i++) {
      pos += writeString(buffer, pos, unsubs[i]);
    }
  
    return buffer;
  }
  
  function emptyPacket(opts) {
    var buf = new Buffer(2);
    buf[0] = protocol.codes[opts.cmd] << 4;
    buf[1] = 0;
    return buf;
  }
  
  /**
   * calcLengthLength - calculate the length of the remaining
   * length field
   *
   * @api private
   */
  function calcLengthLength(length) {
    if (length >= 0 && length < 128) {
      return 1
    } else if (length >= 128 && length < 16384) {
      return 2
    } else if (length >= 16384 && length < 2097152) {
      return 3
    } else if (length >= 2097152 && length < 268435456) {
      return 4
    } else {
      return 0
    }
  }
  
  /**
   * writeLength - write an MQTT style length field to the buffer
   *
   * @param <Buffer> buffer - destination
   * @param <Number> pos - offset
   * @param <Number> length - length (>0)
   * @returns <Number> number of bytes written
   *
   * @api private
   */
  
  function writeLength(buffer, pos, length) {
    var digit = 0
      , origPos = pos
  
    do {
      digit = length % 128 | 0
      length = length / 128 | 0
      if (length > 0) {
          digit = digit | 0x80
      }
      buffer.writeUInt8(digit, pos++, true)
    } while (length > 0)
  
    return pos - origPos
  }
  
  /**
   * writeString - write a utf8 string to the buffer
   *
   * @param <Buffer> buffer - destination
   * @param <Number> pos - offset
   * @param <String> string - string to write
   * @return <Number> number of bytes written
   *
   * @api private
   */
  
  function writeString(buffer, pos, string) {
    var strlen = Buffer.byteLength(string)
    writeNumber(buffer, pos, strlen)
  
    writeStringNoPos(buffer, pos + 2, string)
  
    return strlen + 2
  }
  
  function writeStringNoPos(buffer, pos, string) {
    buffer.write(string, pos)
  }
  
  /**
   * write_buffer - write buffer to buffer
   *
   * @param <Buffer> buffer - dest buffer
   * @param <Number> pos - offset
   * @param <Buffer> src - source buffer
   * @return <Number> number of bytes written
   *
   * @api private
   */
  
  function writeBuffer(buffer, pos, src) {
    src.copy(buffer, pos)
    return src.length
  }
  
  /**
   * writeNumber - write a two byte number to the buffer
   *
   * @param <Buffer> buffer - destination
   * @param <Number> pos - offset
   * @param <String> number - number to write
   * @return <Number> number of bytes written
   *
   * @api private
   */
  function writeNumber(buffer, pos, number) {
    buffer.writeUInt8(number >> 8, pos, true)
    buffer.writeUInt8(number & 0x00FF, pos + 1, true)
  
    return 2
  }
  
  /**
   * writeStringOrBuffer - write a String or Buffer with the its length prefix
   *
   * @param <Buffer> buffer - destination
   * @param <Number> pos - offset
   * @param <String> toWrite - String or Buffer
   * @return <Number> number of bytes written
   */
  function writeStringOrBuffer(buffer, pos, toWrite) {
    var written = 0
  
    if (toWrite && typeof toWrite === 'string') {
      written += writeString(buffer, pos + written, toWrite)
    } else if (toWrite) {
      written += writeNumber(buffer, pos + written, toWrite.length)
      written += writeBuffer(buffer, pos + written, toWrite)
    } else {
      written += writeNumber(buffer, pos + written, 0)
    }
  
    return written
  }
  
  function byteLength(bufOrString) {
    if (Buffer.isBuffer(bufOrString)) {
      return bufOrString.length
    } else {
      return Buffer.byteLength(bufOrString)
    }
  }
  
  module.exports = generate
  
  }).call(this,require("buffer").Buffer)
  },{"./constants":39,"buffer":97}],41:[function(require,module,exports){
  
  'use strict';
  
  exports.parser          = require('./parser')
  exports.generate        = require('./generate')
  
  },{"./generate":40,"./parser":44}],42:[function(require,module,exports){
  (function (Buffer){
  var DuplexStream = require('readable-stream/duplex')
    , util         = require('util')
  
  function BufferList (callback) {
    if (!(this instanceof BufferList))
      return new BufferList(callback)
  
    this._bufs  = []
    this.length = 0
  
    if (typeof callback == 'function') {
      this._callback = callback
  
      var piper = function (err) {
        if (this._callback) {
          this._callback(err)
          this._callback = null
        }
      }.bind(this)
  
      this.on('pipe', function (src) {
        src.on('error', piper)
      })
      this.on('unpipe', function (src) {
        src.removeListener('error', piper)
      })
    }
    else if (Buffer.isBuffer(callback))
      this.append(callback)
    else if (Array.isArray(callback)) {
      callback.forEach(function (b) {
        Buffer.isBuffer(b) && this.append(b)
      }.bind(this))
    }
  
    DuplexStream.call(this)
  }
  
  util.inherits(BufferList, DuplexStream)
  
  BufferList.prototype._offset = function (offset) {
    var tot = 0, i = 0, _t
    for (; i < this._bufs.length; i++) {
      _t = tot + this._bufs[i].length
      if (offset < _t)
        return [ i, offset - tot ]
      tot = _t
    }
  }
  
  BufferList.prototype.append = function (buf) {
    var isBuffer = Buffer.isBuffer(buf) ||
                   buf instanceof BufferList
  
    // coerce number arguments to strings, since Buffer(number) does
    // uninitialized memory allocation
    if (typeof buf == 'number')
      buf = buf.toString()
  
    this._bufs.push(isBuffer ? buf : new Buffer(buf))
    this.length += buf.length
    return this
  }
  
  BufferList.prototype._write = function (buf, encoding, callback) {
    this.append(buf)
    if (callback)
      callback()
  }
  
  BufferList.prototype._read = function (size) {
    if (!this.length)
      return this.push(null)
    size = Math.min(size, this.length)
    this.push(this.slice(0, size))
    this.consume(size)
  }
  
  BufferList.prototype.end = function (chunk) {
    DuplexStream.prototype.end.call(this, chunk)
  
    if (this._callback) {
      this._callback(null, this.slice())
      this._callback = null
    }
  }
  
  BufferList.prototype.get = function (index) {
    return this.slice(index, index + 1)[0]
  }
  
  BufferList.prototype.slice = function (start, end) {
    return this.copy(null, 0, start, end)
  }
  
  BufferList.prototype.copy = function (dst, dstStart, srcStart, srcEnd) {
    if (typeof srcStart != 'number' || srcStart < 0)
      srcStart = 0
    if (typeof srcEnd != 'number' || srcEnd > this.length)
      srcEnd = this.length
    if (srcStart >= this.length)
      return dst || new Buffer(0)
    if (srcEnd <= 0)
      return dst || new Buffer(0)
  
    var copy   = !!dst
      , off    = this._offset(srcStart)
      , len    = srcEnd - srcStart
      , bytes  = len
      , bufoff = (copy && dstStart) || 0
      , start  = off[1]
      , l
      , i
  
    // copy/slice everything
    if (srcStart === 0 && srcEnd == this.length) {
      if (!copy) // slice, just return a full concat
        return Buffer.concat(this._bufs)
  
      // copy, need to copy individual buffers
      for (i = 0; i < this._bufs.length; i++) {
        this._bufs[i].copy(dst, bufoff)
        bufoff += this._bufs[i].length
      }
  
      return dst
    }
  
    // easy, cheap case where it's a subset of one of the buffers
    if (bytes <= this._bufs[off[0]].length - start) {
      return copy
        ? this._bufs[off[0]].copy(dst, dstStart, start, start + bytes)
        : this._bufs[off[0]].slice(start, start + bytes)
    }
  
    if (!copy) // a slice, we need something to copy in to
      dst = new Buffer(len)
  
    for (i = off[0]; i < this._bufs.length; i++) {
      l = this._bufs[i].length - start
  
      if (bytes > l) {
        this._bufs[i].copy(dst, bufoff, start)
      } else {
        this._bufs[i].copy(dst, bufoff, start, start + bytes)
        break
      }
  
      bufoff += l
      bytes -= l
  
      if (start)
        start = 0
    }
  
    return dst
  }
  
  BufferList.prototype.toString = function (encoding, start, end) {
    return this.slice(start, end).toString(encoding)
  }
  
  BufferList.prototype.consume = function (bytes) {
    while (this._bufs.length) {
      if (bytes > this._bufs[0].length) {
        bytes -= this._bufs[0].length
        this.length -= this._bufs[0].length
        this._bufs.shift()
      } else {
        this._bufs[0] = this._bufs[0].slice(bytes)
        this.length -= bytes
        break
      }
    }
    return this
  }
  
  BufferList.prototype.duplicate = function () {
    var i = 0
      , copy = new BufferList()
  
    for (; i < this._bufs.length; i++)
      copy.append(this._bufs[i])
  
    return copy
  }
  
  BufferList.prototype.destroy = function () {
    this._bufs.length = 0;
    this.length = 0;
    this.push(null);
  }
  
  ;(function () {
    var methods = {
        'readDoubleBE' : 8
      , 'readDoubleLE' : 8
      , 'readFloatBE'  : 4
      , 'readFloatLE'  : 4
      , 'readInt32BE'  : 4
      , 'readInt32LE'  : 4
      , 'readUInt32BE' : 4
      , 'readUInt32LE' : 4
      , 'readInt16BE'  : 2
      , 'readInt16LE'  : 2
      , 'readUInt16BE' : 2
      , 'readUInt16LE' : 2
      , 'readInt8'     : 1
      , 'readUInt8'    : 1
    }
  
    for (var m in methods) {
      (function (m) {
        BufferList.prototype[m] = function (offset) {
          return this.slice(offset, offset + methods[m])[m](0)
        }
      }(m))
    }
  }())
  
  module.exports = BufferList
  
  }).call(this,require("buffer").Buffer)
  },{"buffer":97,"readable-stream/duplex":45,"util":132}],43:[function(require,module,exports){
  
  function Packet() {
    this.cmd = null
    this.retain = false
    this.qos = 0
    this.dup = false
    this.length = -1
    this.topic = null
    this.payload = null
  }
  
  module.exports = Packet
  
  },{}],44:[function(require,module,exports){
  
  var bl        = require('bl')
    , inherits  = require('inherits')
    , EE        = require('events').EventEmitter
    , Packet    = require('./packet')
    , constants = require('./constants')
  
  function Parser() {
    if (!(this instanceof Parser)) {
      return new Parser()
    }
  
    this._states = [
        '_parseHeader'
      , '_parseLength'
      , '_parsePayload'
      , '_newPacket'
    ]
  
    this._resetState()
  }
  
  inherits(Parser, EE)
  
  Parser.prototype._resetState = function () {
    this.packet = new Packet()
    this.error = null
    this._list = bl()
    this._stateCounter = 0
  }
  
  Parser.prototype.parse = function (buf) {
    if (this.error) {
      this._resetState()
    }
  
    this._list.append(buf)
  
    while ((this.packet.length != -1 || this._list.length > 0) &&
           this[this._states[this._stateCounter]]() &&
           !this.error) {
      this._stateCounter++
  
      if (this._stateCounter >= this._states.length) {
        this._stateCounter = 0
      }
    }
  
    return this._list.length
  }
  
  Parser.prototype._parseHeader = function () {
  
    // there is at least one byte in the buffer
    var zero = this._list.readUInt8(0)
    this.packet.cmd = constants.types[zero >> constants.CMD_SHIFT]
    this.packet.retain = (zero & constants.RETAIN_MASK) !== 0
    this.packet.qos = (zero >> constants.QOS_SHIFT) & constants.QOS_MASK
    this.packet.dup = (zero & constants.DUP_MASK) !== 0
  
    this._list.consume(1)
  
    return true
  }
  
  
  Parser.prototype._parseLength = function () {
    // there is at least one byte in the list
    var bytes    = 0
      , mul      = 1
      , length   = 0
      , result   = true
      , current
  
    while (bytes < 5) {
      current = this._list.readUInt8(bytes++)
      length += mul * (current & constants.LENGTH_MASK)
      mul *= 0x80
  
      if ((current & constants.LENGTH_FIN_MASK) === 0) {
        break
      }
  
      if (this._list.length <= bytes) {
        result = false
        break
      }
    }
  
    if (result) {
      this.packet.length = length
      this._list.consume(bytes)
    }
  
    return result
  }
  
  Parser.prototype._parsePayload = function () {
    var result = false
  
    // Do we have a payload? Do we have enough data to complete the payload?
    // PINGs have no payload
    if (this.packet.length === 0 || this._list.length >= this.packet.length) {
  
      this._pos = 0
  
      switch (this.packet.cmd) {
        case 'connect':
          this._parseConnect()
          break
        case 'connack':
          this._parseConnack()
          break
        case 'publish':
          this._parsePublish()
          break
        case 'puback':
        case 'pubrec':
        case 'pubrel':
        case 'pubcomp':
          this._parseMessageId()
          break
        case 'subscribe':
          this._parseSubscribe()
          break
        case 'suback':
          this._parseSuback()
          break
        case 'unsubscribe':
          this._parseUnsubscribe()
          break
        case 'unsuback':
          this._parseUnsuback()
          break
        case 'pingreq':
        case 'pingresp':
        case 'disconnect':
          // these are empty, nothing to do
          break
        default:
          this._emitError(new Error('not supported'))
      }
  
      result = true
    }
  
    return result
  }
  
  Parser.prototype._parseConnect = function () {
    var protocolId // constants id
      , clientId // Client id
      , topic // Will topic
      , payload // Will payload
      , password // Password
      , username // Username
      , flags = {}
      , packet = this.packet
  
    // Parse constants id
    protocolId = this._parseString()
    if (protocolId === null)
      return this._emitError(new Error('cannot parse protocol id'))
  
    if (protocolId != 'MQTT' && protocolId != 'MQIsdp') {
  
      return this._emitError(new Error('invalid protocol id'))
    }
  
    packet.protocolId = protocolId
  
    // Parse constants version number
    if(this._pos >= this._list.length)
      return this._emitError(new Error('packet too short'))
  
    packet.protocolVersion = this._list.readUInt8(this._pos)
  
    if(packet.protocolVersion != 3 && packet.protocolVersion != 4) {
  
      return this._emitError(new Error('invalid protocol version'))
    }
  
    this._pos++
    if(this._pos >= this._list.length)
      return this._emitError(new Error('packet too short'))
  
    // Parse connect flags
    flags.username  = (this._list.readUInt8(this._pos) & constants.USERNAME_MASK)
    flags.password  = (this._list.readUInt8(this._pos) & constants.PASSWORD_MASK)
    flags.will      = (this._list.readUInt8(this._pos) & constants.WILL_FLAG_MASK)
  
    if (flags.will) {
      packet.will         = {}
      packet.will.retain  = (this._list.readUInt8(this._pos) & constants.WILL_RETAIN_MASK) !== 0
      packet.will.qos     = (this._list.readUInt8(this._pos) &
                            constants.WILL_QOS_MASK) >> constants.WILL_QOS_SHIFT
    }
  
    packet.clean = (this._list.readUInt8(this._pos) & constants.CLEAN_SESSION_MASK) !== 0
    this._pos++
  
    // Parse keepalive
    packet.keepalive = this._parseNum()
    if(packet.keepalive === -1)
      return this._emitError(new Error('packet too short'))
  
    // Parse client ID
    clientId = this._parseString()
    if(clientId === null)
      return this._emitError(new Error('packet too short'))
    packet.clientId = clientId
  
    if (flags.will) {
      // Parse will topic
      topic = this._parseString()
      if (topic === null)
        return this._emitError(new Error('cannot parse will topic'))
      packet.will.topic = topic
  
      // Parse will payload
      payload = this._parseBuffer()
      if (payload === null)
        return this._emitError(new Error('cannot parse will payload'))
      packet.will.payload = payload
    }
  
    // Parse username
    if (flags.username) {
      username = this._parseString()
      if(username === null)
        return this._emitError(new Error('cannot parse username'))
      packet.username = username
    }
  
    // Parse password
    if(flags.password) {
      password = this._parseBuffer()
      if(password === null)
        return this._emitError(new Error('cannot parse username'))
      packet.password = password
    }
  
    return packet
  }
  
  Parser.prototype._parseConnack = function () {
    var packet = this.packet
    if (this._list.length < 2)
      return null
    packet.sessionPresent = !!(this._list.readUInt8(this._pos++) & constants.SESSIONPRESENT_MASK)
    packet.returnCode = this._list.readUInt8(this._pos)
    if(packet.returnCode === -1)
      return this._emitError(new Error('cannot parse return code'))
  }
  
  Parser.prototype._parsePublish = function () {
    var packet = this.packet
    packet.topic = this._parseString()
  
    if(packet.topic === null)
      return this._emitError(new Error('cannot parse topic'))
  
    // Parse message ID
    if (packet.qos > 0) {
      if (!this._parseMessageId()) { return }
    }
  
    packet.payload = this._list.slice(this._pos, packet.length)
  }
  
  Parser.prototype._parseSubscribe = function() {
    var packet = this.packet
      , topic
      , qos
  
    if (packet.qos != 1) {
      return this._emitError(new Error('wrong subscribe header'))
    }
  
    packet.subscriptions = []
  
    if (!this._parseMessageId()) { return }
  
    while (this._pos < packet.length) {
  
      // Parse topic
      topic = this._parseString()
      if (topic === null)
        return this._emitError(new Error('Parse error - cannot parse topic'))
  
      qos = this._list.readUInt8(this._pos++)
  
      // Push pair to subscriptions
      packet.subscriptions.push({ topic: topic, qos: qos });
    }
  }
  
  Parser.prototype._parseSuback = function() {
    this.packet.granted = []
  
    if (!this._parseMessageId()) { return }
  
    // Parse granted QoSes
    while (this._pos < this.packet.length) {
      this.packet.granted.push(this._list.readUInt8(this._pos++));
    }
  }
  
  Parser.prototype._parseUnsubscribe = function() {
    var packet = this.packet
  
    packet.unsubscriptions = []
  
    // Parse message ID
    if (!this._parseMessageId()) { return }
  
    while (this._pos < packet.length) {
      var topic;
  
      // Parse topic
      topic = this._parseString()
      if (topic === null)
        return this._emitError(new Error('cannot parse topic'))
  
      // Push topic to unsubscriptions
      packet.unsubscriptions.push(topic);
    }
  }
  
  Parser.prototype._parseUnsuback = function() {
    if (!this._parseMessageId())
      return this._emitError(new Error('cannot parse message id'))
  }
  
  Parser.prototype._parseMessageId = function() {
    var packet = this.packet
  
    packet.messageId = this._parseNum()
  
    if(packet.messageId === null) {
      this._emitError(new Error('cannot parse message id'))
      return false
    }
  
    return true
  }
  
  Parser.prototype._parseString = function(maybeBuffer) {
    var length = this._parseNum()
      , result
      , end = length + this._pos
  
    if(length === -1 || end > this._list.length || end > this.packet.length)
      return null
  
    result = this._list.toString('utf8', this._pos, end)
  
    this._pos += length
  
    return result
  }
  
  Parser.prototype._parseBuffer = function() {
    var length = this._parseNum()
      , result
      , end = length + this._pos
  
    if(length === -1 || end > this._list.length || end > this.packet.length)
      return null
  
    result = this._list.slice(this._pos, end)
  
    this._pos += length
  
    return result
  }
  
  Parser.prototype._parseNum = function() {
    if(this._list.length - this._pos < 2) return -1
  
    var result = this._list.readUInt16BE(this._pos)
    this._pos += 2
    return result
  }
  
  Parser.prototype._newPacket = function () {
    if (this.packet) {
      this._list.consume(this.packet.length)
      this.emit('packet', this.packet)
    }
  
    this.packet = new Packet()
  
    return true
  }
  
  Parser.prototype._emitError = function(err) {
    this.error = err
    this.emit('error', err)
  }
  
  module.exports = Parser
  
  },{"./constants":39,"./packet":43,"bl":42,"events":100,"inherits":38}],45:[function(require,module,exports){
  module.exports = require("./lib/_stream_duplex.js")
  
  },{"./lib/_stream_duplex.js":46}],46:[function(require,module,exports){
  (function (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
  // "Software"), to deal in the Software without restriction, including
  // without limitation the rights to use, copy, modify, merge, publish,
  // distribute, sublicense, and/or sell copies of the Software, and to permit
  // persons to whom the Software is furnished to do so, subject to the
  // following conditions:
  //
  // The above copyright notice and this permission notice shall be included
  // in all copies or substantial portions of the Software.
  //
  // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  // USE OR OTHER DEALINGS IN THE SOFTWARE.
  
  // a duplex stream is just a stream that is both readable and writable.
  // Since JS doesn't have multiple prototypal inheritance, this class
  // prototypally inherits from Readable, and then parasitically from
  // Writable.
  
  module.exports = Duplex;
  
  /*<replacement>*/
  var objectKeys = Object.keys || function (obj) {
    var keys = [];
    for (var key in obj) keys.push(key);
    return keys;
  }
  /*</replacement>*/
  
  
  /*<replacement>*/
  var util = require('core-util-is');
  util.inherits = require('inherits');
  /*</replacement>*/
  
  var Readable = require('./_stream_readable');
  var Writable = require('./_stream_writable');
  
  util.inherits(Duplex, Readable);
  
  forEach(objectKeys(Writable.prototype), function(method) {
    if (!Duplex.prototype[method])
      Duplex.prototype[method] = Writable.prototype[method];
  });
  
  function Duplex(options) {
    if (!(this instanceof Duplex))
      return new Duplex(options);
  
    Readable.call(this, options);
    Writable.call(this, options);
  
    if (options && options.readable === false)
      this.readable = false;
  
    if (options && options.writable === false)
      this.writable = false;
  
    this.allowHalfOpen = true;
    if (options && options.allowHalfOpen === false)
      this.allowHalfOpen = false;
  
    this.once('end', onend);
  }
  
  // the no-half-open enforcer
  function onend() {
    // if we allow half-open state, or if the writable side ended,
    // then we're ok.
    if (this.allowHalfOpen || this._writableState.ended)
      return;
  
    // no more data can be written.
    // But allow more writes to happen in this tick.
    process.nextTick(this.end.bind(this));
  }
  
  function forEach (xs, f) {
    for (var i = 0, l = xs.length; i < l; i++) {
      f(xs[i], i);
    }
  }
  
  }).call(this,require('_process'))
  },{"./_stream_readable":48,"./_stream_writable":50,"_process":103,"core-util-is":51,"inherits":38}],47:[function(require,module,exports){
  // Copyright Joyent, Inc. and other Node contributors.
  //
  // Permission is hereby granted, free of charge, to any person obtaining a
  // copy of this software and associated documentation files (the
  // "Software"), to deal in the Software without restriction, including
  // without limitation the rights to use, copy, modify, merge, publish,
  // distribute, sublicense, and/or sell copies of the Software, and to permit
  // persons to whom the Software is furnished to do so, subject to the
  // following conditions:
  //
  // The above copyright notice and this permission notice shall be included
  // in all copies or substantial portions of the Software.
  //
  // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  // USE OR OTHER DEALINGS IN THE SOFTWARE.
  
  // a passthrough stream.
  // basically just the most minimal sort of Transform stream.
  // Every written chunk gets output as-is.
  
  module.exports = PassThrough;
  
  var Transform = require('./_stream_transform');
  
  /*<replacement>*/
  var util = require('core-util-is');
  util.inherits = require('inherits');
  /*</replacement>*/
  
  util.inherits(PassThrough, Transform);
  
  function PassThrough(options) {
    if (!(this instanceof PassThrough))
      return new PassThrough(options);
  
    Transform.call(this, options);
  }
  
  PassThrough.prototype._transform = function(chunk, encoding, cb) {
    cb(null, chunk);
  };
  
  },{"./_stream_transform":49,"core-util-is":51,"inherits":38}],48:[function(require,module,exports){
  (function (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
  // "Software"), to deal in the Software without restriction, including
  // without limitation the rights to use, copy, modify, merge, publish,
  // distribute, sublicense, and/or sell copies of the Software, and to permit
  // persons to whom the Software is furnished to do so, subject to the
  // following conditions:
  //
  // The above copyright notice and this permission notice shall be included
  // in all copies or substantial portions of the Software.
  //
  // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  // USE OR OTHER DEALINGS IN THE SOFTWARE.
  
  module.exports = Readable;
  
  /*<replacement>*/
  var isArray = require('isarray');
  /*</replacement>*/
  
  
  /*<replacement>*/
  var Buffer = require('buffer').Buffer;
  /*</replacement>*/
  
  Readable.ReadableState = ReadableState;
  
  var EE = require('events').EventEmitter;
  
  /*<replacement>*/
  if (!EE.listenerCount) EE.listenerCount = function(emitter, type) {
    return emitter.listeners(type).length;
  };
  /*</replacement>*/
  
  var Stream = require('stream');
  
  /*<replacement>*/
  var util = require('core-util-is');
  util.inherits = require('inherits');
  /*</replacement>*/
  
  var StringDecoder;
  
  util.inherits(Readable, Stream);
  
  function ReadableState(options, stream) {
    options = options || {};
  
    // 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;
    this.highWaterMark = (hwm || hwm === 0) ? hwm : 16 * 1024;
  
    // cast to ints.
    this.highWaterMark = ~~this.highWaterMark;
  
    this.buffer = [];
    this.length = 0;
    this.pipes = null;
    this.pipesCount = 0;
    this.flowing = false;
    this.ended = false;
    this.endEmitted = false;
    this.reading = false;
  
    // In streams that never have any data, and do push(null) right away,
    // the consumer can miss the 'end' event if they do some I/O before
    // consuming the stream.  So, we don't emit('end') until some reading
    // happens.
    this.calledRead = false;
  
    // 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, becuase any
    // actions that shouldn't happen until "later" should generally also
    // not happen before the first write call.
    this.sync = true;
  
    // whenever we return null, then we set a flag to say
    // that we're awaiting a 'readable' event emission.
    this.needReadable = false;
    this.emittedReadable = false;
    this.readableListening = false;
  
  
    // 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;
  
    // 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';
  
    // when piping, we only care about 'readable' events that happen
    // after read()ing all the bytes and not getting any pushback.
    this.ranOut = false;
  
    // the number of writers that are awaiting a drain event in .pipe()s
    this.awaitDrain = 0;
  
    // if true, a maybeReadMore has been scheduled
    this.readingMore = false;
  
    this.decoder = null;
    this.encoding = null;
    if (options.encoding) {
      if (!StringDecoder)
        StringDecoder = require('string_decoder/').StringDecoder;
      this.decoder = new StringDecoder(options.encoding);
      this.encoding = options.encoding;
    }
  }
  
  function Readable(options) {
    if (!(this instanceof Readable))
      return new Readable(options);
  
    this._readableState = new ReadableState(options, this);
  
    // legacy
    this.readable = true;
  
    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;
  
    if (typeof chunk === 'string' && !state.objectMode) {
      encoding = encoding || state.defaultEncoding;
      if (encoding !== state.encoding) {
        chunk = new Buffer(chunk, encoding);
        encoding = '';
      }
    }
  
    return readableAddChunk(this, state, chunk, encoding, false);
  };
  
  // Unshift should *always* be something directly out of read()
  Readable.prototype.unshift = function(chunk) {
    var state = this._readableState;
    return readableAddChunk(this, state, chunk, '', true);
  };
  
  function readableAddChunk(stream, state, chunk, encoding, addToFront) {
    var er = chunkInvalid(state, chunk);
    if (er) {
      stream.emit('error', er);
    } else if (chunk === null || chunk === undefined) {
      state.reading = false;
      if (!state.ended)
        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);
  
        // update the buffer info.
        state.length += state.objectMode ? 1 : chunk.length;
        if (addToFront) {
          state.buffer.unshift(chunk);
        } else {
          state.reading = false;
          state.buffer.push(chunk);
        }
  
        if (state.needReadable)
          emitReadable(stream);
  
        maybeReadMore(stream, state);
      }
    } else if (!addToFront) {
      state.reading = false;
    }
  
    return needMoreData(state);
  }
  
  
  
  // 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);
  }
  
  // backwards compatibility.
  Readable.prototype.setEncoding = function(enc) {
    if (!StringDecoder)
      StringDecoder = require('string_decoder/').StringDecoder;
    this._readableState.decoder = new StringDecoder(enc);
    this._readableState.encoding = enc;
  };
  
  // Don't raise the hwm > 128MB
  var MAX_HWM = 0x800000;
  function roundUpToNextPowerOf2(n) {
    if (n >= MAX_HWM) {
      n = MAX_HWM;
    } else {
      // Get the next highest power of 2
      n--;
      for (var p = 1; p < 32; p <<= 1) n |= n >> p;
      n++;
    }
    return n;
  }
  
  function howMuchToRead(n, state) {
    if (state.length === 0 && state.ended)
      return 0;
  
    if (state.objectMode)
      return n === 0 ? 0 : 1;
  
    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;
    }
  
    if (n <= 0)
      return 0;
  
    // 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 = roundUpToNextPowerOf2(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;
    }
  
    return n;
  }
  
  // you can override either this method, or the async _read(n) below.
  Readable.prototype.read = function(n) {
    var state = this._readableState;
    state.calledRead = true;
    var nOrig = n;
    var ret;
  
    if (typeof n !== 'number' || n > 0)
      state.emittedReadable = false;
  
    // if we're doing read(0) to trigger a readable event, but we
    // already have a bunch of data in the buffer, then just trigger
    // the 'readable' event and move on.
    if (n === 0 &&
        state.needReadable &&
        (state.length >= state.highWaterMark || state.ended)) {
      emitReadable(this);
      return null;
    }
  
    n = howMuchToRead(n, state);
  
    // if we've ended, and we're now clear, then finish it up.
    if (n === 0 && state.ended) {
      ret = null;
  
      // In cases where the decoder did not receive enough data
      // to produce a full chunk, then immediately received an
      // EOF, state.buffer will contain [<Buffer >, <Buffer 00 ...>].
      // howMuchToRead will see this and coerce the amount to
      // read to zero (because it's looking at the length of the
      // first <Buffer > in state.buffer), and we'll end up here.
      //
      // This can only happen via state.decoder -- no other venue
      // exists for pushing a zero-length chunk into state.buffer
      // and triggering this behavior. In this case, we return our
      // remaining data and end the stream, if appropriate.
      if (state.length > 0 && state.decoder) {
        ret = fromList(n, state);
        state.length -= ret.length;
      }
  
      if (state.length === 0)
        endReadable(this);
  
      return ret;
    }
  
    // All the actual chunk generation logic needs to be
    // *below* the call to _read.  The reason is that in certain
    // synthetic stream cases, such as passthrough streams, _read
    // may be a completely synchronous operation which may change
    // the state of the read buffer, providing enough data when
    // before there was *not* enough.
    //
    // So, the steps are:
    // 1. Figure out what the state of things will be after we do
    // a read from the buffer.
    //
    // 2. If that resulting state will trigger a _read, then call _read.
    // Note that this may be asynchronous, or synchronous.  Yes, it is
    // deeply ugly to write APIs this way, but that still doesn't mean
    // that the Readable class should behave improperly, as streams are
    // designed to be sync/async agnostic.
    // Take note if the _read call is sync or async (ie, if the read call
    // has returned yet), so that we know whether or not it's safe to emit
    // 'readable' etc.
    //
    // 3. Actually pull the requested chunks out of the buffer and return.
  
    // if we need a readable event, then we need to do some reading.
    var doRead = state.needReadable;
  
    // if we currently have less than the highWaterMark, then also read some
    if (state.length - n <= state.highWaterMark)
      doRead = true;
  
    // however, if we've ended, then there's no point, and if we're already
    // reading, then it's unnecessary.
    if (state.ended || state.reading)
      doRead = false;
  
    if (doRead) {
      state.reading = true;
      state.sync = true;
      // if the length is currently zero, then we *need* a readable event.
      if (state.length === 0)
        state.needReadable = true;
      // call internal read method
      this._read(state.highWaterMark);
      state.sync = false;
    }
  
    // If _read called its callback synchronously, then `reading`
    // will be false, and we need to re-evaluate how much data we
    // can return to the user.
    if (doRead && !state.reading)
      n = howMuchToRead(nOrig, state);
  
    if (n > 0)
      ret = fromList(n, state);
    else
      ret = null;
  
    if (ret === null) {
      state.needReadable = true;
      n = 0;
    }
  
    state.length -= n;
  
    // If we have nothing in the buffer, then we want to know
    // as soon as we *do* get something into the buffer.
    if (state.length === 0 && !state.ended)
      state.needReadable = true;
  
    // If we happened to read() exactly the remaining amount in the
    // buffer, and the EOF has been seen at this point, then make sure
    // that we emit 'end' on the very next tick.
    if (state.ended && !state.endEmitted && state.length === 0)
      endReadable(this);
  
    return ret;
  };
  
  function chunkInvalid(state, chunk) {
    var er = null;
    if (!Buffer.isBuffer(chunk) &&
        'string' !== typeof chunk &&
        chunk !== null &&
        chunk !== undefined &&
        !state.objectMode) {
      er = new TypeError('Invalid non-string/buffer chunk');
    }
    return er;
  }
  
  
  function onEofChunk(stream, state) {
    if (state.decoder && !state.ended) {
      var chunk = state.decoder.end();
      if (chunk && chunk.length) {
        state.buffer.push(chunk);
        state.length += state.objectMode ? 1 : chunk.length;
      }
    }
    state.ended = true;
  
    // if we've ended and we have some data left, then emit
    // 'readable' now to make sure it gets picked up.
    if (state.length > 0)
      emitReadable(stream);
    else
      endReadable(stream);
  }
  
  // Don't emit readable right away in sync mode, because this can trigger
  // another read() call => stack overflow.  This way, it might trigger
  // a nextTick recursion warning, but that's not so bad.
  function emitReadable(stream) {
    var state = stream._readableState;
    state.needReadable = false;
    if (state.emittedReadable)
      return;
  
    state.emittedReadable = true;
    if (state.sync)
      process.nextTick(function() {
        emitReadable_(stream);
      });
    else
      emitReadable_(stream);
  }
  
  function emitReadable_(stream) {
    stream.emit('readable');
  }
  
  
  // at this point, the user has presumably seen the 'readable' event,
  // and called read() to consume some data.  that may have triggered
  // in turn another _read(n) call, in which case reading = true if
  // it's in progress.
  // However, if we're not ended, or reading, and the length < hwm,
  // then go ahead and try to read some more preemptively.
  function maybeReadMore(stream, state) {
    if (!state.readingMore) {
      state.readingMore = true;
      process.nextTick(function() {
        maybeReadMore_(stream, state);
      });
    }
  }
  
  function maybeReadMore_(stream, state) {
    var len = state.length;
    while (!state.reading && !state.flowing && !state.ended &&
           state.length < state.highWaterMark) {
      stream.read(0);
      if (len === state.length)
        // didn't get any data, stop spinning.
        break;
      else
        len = state.length;
    }
    state.readingMore = false;
  }
  
  // abstract method.  to be overridden in specific implementation classes.
  // call cb(er, data) where data is <= n in length.
  // for virtual (non-string, non-buffer) streams, "length" is somewhat
  // arbitrary, and perhaps not very meaningful.
  Readable.prototype._read = function(n) {
    this.emit('error', new Error('not implemented'));
  };
  
  Readable.prototype.pipe = function(dest, pipeOpts) {
    var src = this;
    var state = this._readableState;
  
    switch (state.pipesCount) {
      case 0:
        state.pipes = dest;
        break;
      case 1:
        state.pipes = [state.pipes, dest];
        break;
      default:
        state.pipes.push(dest);
        break;
    }
    state.pipesCount += 1;
  
    var doEnd = (!pipeOpts || pipeOpts.end !== false) &&
                dest !== process.stdout &&
                dest !== process.stderr;
  
    var endFn = doEnd ? onend : cleanup;
    if (state.endEmitted)
      process.nextTick(endFn);
    else
      src.once('end', endFn);
  
    dest.on('unpipe', onunpipe);
    function onunpipe(readable) {
      if (readable !== src) return;
      cleanup();
    }
  
    function onend() {
      dest.end();
    }
  
    // when the dest drains, it reduces the awaitDrain counter
    // on the source.  This would be more elegant with a .once()
    // handler in flow(), but adding and removing repeatedly is
    // too slow.
    var ondrain = pipeOnDrain(src);
    dest.on('drain', ondrain);
  
    function cleanup() {
      // cleanup event handlers once the pipe is broken
      dest.removeListener('close', onclose);
      dest.removeListener('finish', onfinish);
      dest.removeListener('drain', ondrain);
      dest.removeListener('error', onerror);
      dest.removeListener('unpipe', onunpipe);
      src.removeListener('end', onend);
      src.removeListener('end', cleanup);
  
      // if the reader is waiting for a drain event from this
      // specific writer, then it would cause it to never start
      // flowing again.
      // So, if this is awaiting a drain, then we just call it now.
      // If we don't know, then assume that we are waiting for one.
      if (!dest._writableState || dest._writableState.needDrain)
        ondrain();
    }
  
    // if the dest has an error, then stop piping into it.
    // however, don't suppress the throwing behavior for this.
    function onerror(er) {
      unpipe();
      dest.removeListener('error', onerror);
      if (EE.listenerCount(dest, 'error') === 0)
        dest.emit('error', er);
    }
    // This is a brutally ugly hack to make sure that our error handler
    // is attached before any userland ones.  NEVER DO THIS.
    if (!dest._events || !dest._events.error)
      dest.on('error', onerror);
    else if (isArray(dest._events.error))
      dest._events.error.unshift(onerror);
    else
      dest._events.error = [onerror, dest._events.error];
  
  
  
    // Both close and finish should trigger unpipe, but only once.
    function onclose() {
      dest.removeListener('finish', onfinish);
      unpipe();
    }
    dest.once('close', onclose);
    function onfinish() {
      dest.removeListener('close', onclose);
      unpipe();
    }
    dest.once('finish', onfinish);
  
    function unpipe() {
      src.unpipe(dest);
    }
  
    // tell the dest that it's being piped to
    dest.emit('pipe', src);
  
    // start the flow if it hasn't been started already.
    if (!state.flowing) {
      // the handler that waits for readable events after all
      // the data gets sucked out in flow.
      // This would be easier to follow with a .once() handler
      // in flow(), but that is too slow.
      this.on('readable', pipeOnReadable);
  
      state.flowing = true;
      process.nextTick(function() {
        flow(src);
      });
    }
  
    return dest;
  };
  
  function pipeOnDrain(src) {
    return function() {
      var dest = this;
      var state = src._readableState;
      state.awaitDrain--;
      if (state.awaitDrain === 0)
        flow(src);
    };
  }
  
  function flow(src) {
    var state = src._readableState;
    var chunk;
    state.awaitDrain = 0;
  
    function write(dest, i, list) {
      var written = dest.write(chunk);
      if (false === written) {
        state.awaitDrain++;
      }
    }
  
    while (state.pipesCount && null !== (chunk = src.read())) {
  
      if (state.pipesCount === 1)
        write(state.pipes, 0, null);
      else
        forEach(state.pipes, write);
  
      src.emit('data', chunk);
  
      // if anyone needs a drain, then we have to wait for that.
      if (state.awaitDrain > 0)
        return;
    }
  
    // if every destination was unpiped, either before entering this
    // function, or in the while loop, then stop flowing.
    //
    // NB: This is a pretty rare edge case.
    if (state.pipesCount === 0) {
      state.flowing = false;
  
      // if there were data event listeners added, then switch to old mode.
      if (EE.listenerCount(src, 'data') > 0)
        emitDataEvents(src);
      return;
    }
  
    // at this point, no one needed a drain, so we just ran out of data
    // on the next readable event, start it over again.
    state.ranOut = true;
  }
  
  function pipeOnReadable() {
    if (this._readableState.ranOut) {
      this._readableState.ranOut = false;
      flow(this);
    }
  }
  
  
  Readable.prototype.unpipe = function(dest) {
    var state = this._readableState;
  
    // if we're not piping anywhere, then do nothing.
    if (state.pipesCount === 0)
      return this;
  
    // just one destination.  most common case.
    if (state.pipesCount === 1) {
      // passed in one, but it's not the right one.
      if (dest && dest !== state.pipes)
        return this;
  
      if (!dest)
        dest = state.pipes;
  
      // got a match.
      state.pipes = null;
      state.pipesCount = 0;
      this.removeListener('readable', pipeOnReadable);
      state.flowing = false;
      if (dest)
        dest.emit('unpipe', this);
      return this;
    }
  
    // slow case. multiple pipe destinations.
  
    if (!dest) {
      // remove all.
      var dests = state.pipes;
      var len = state.pipesCount;
      state.pipes = null;
      state.pipesCount = 0;
      this.removeListener('readable', pipeOnReadable);
      state.flowing = false;
  
      for (var i = 0; i < len; i++)
        dests[i].emit('unpipe', this);
      return this;
    }
  
    // try to find the right one.
    var i = indexOf(state.pipes, dest);
    if (i === -1)
      return this;
  
    state.pipes.splice(i, 1);
    state.pipesCount -= 1;
    if (state.pipesCount === 1)
      state.pipes = state.pipes[0];
  
    dest.emit('unpipe', this);
  
    return this;
  };
  
  // set up data events if they are asked for
  // Ensure readable listeners eventually get something
  Readable.prototype.on = function(ev, fn) {
    var res = Stream.prototype.on.call(this, ev, fn);
  
    if (ev === 'data' && !this._readableState.flowing)
      emitDataEvents(this);
  
    if (ev === 'readable' && this.readable) {
      var state = this._readableState;
      if (!state.readableListening) {
        state.readableListening = true;
        state.emittedReadable = false;
        state.needReadable = true;
        if (!state.reading) {
          this.read(0);
        } else if (state.length) {
          emitReadable(this, state);
        }
      }
    }
  
    return res;
  };
  Readable.prototype.addListener = Readable.prototype.on;
  
  // pause() and resume() are remnants of the legacy readable stream API
  // If the user uses them, then switch into old mode.
  Readable.prototype.resume = function() {
    emitDataEvents(this);
    this.read(0);
    this.emit('resume');
  };
  
  Readable.prototype.pause = function() {
    emitDataEvents(this, true);
    this.emit('pause');
  };
  
  function emitDataEvents(stream, startPaused) {
    var state = stream._readableState;
  
    if (state.flowing) {
      // https://github.com/isaacs/readable-stream/issues/16
      throw new Error('Cannot switch to old mode now.');
    }
  
    var paused = startPaused || false;
    var readable = false;
  
    // convert to an old-style stream.
    stream.readable = true;
    stream.pipe = Stream.prototype.pipe;
    stream.on = stream.addListener = Stream.prototype.on;
  
    stream.on('readable', function() {
      readable = true;
  
      var c;
      while (!paused && (null !== (c = stream.read())))
        stream.emit('data', c);
  
      if (c === null) {
        readable = false;
        stream._readableState.needReadable = true;
      }
    });
  
    stream.pause = function() {
      paused = true;
      this.emit('pause');
    };
  
    stream.resume = function() {
      paused = false;
      if (readable)
        process.nextTick(function() {
          stream.emit('readable');
        });
      else
        this.read(0);
      this.emit('resume');
    };
  
    // now make it start, just in case it hadn't already.
    stream.emit('readable');
  }
  
  // wrap an old-style stream as the async data source.
  // This is *not* part of the readable stream interface.
  // It is an ugly unfortunate mess of history.
  Readable.prototype.wrap = function(stream) {
    var state = this._readableState;
    var paused = false;
  
    var self = this;
    stream.on('end', function() {
      if (state.decoder && !state.ended) {
        var chunk = state.decoder.end();
        if (chunk && chunk.length)
          self.push(chunk);
      }
  
      self.push(null);
    });
  
    stream.on('data', function(chunk) {
      if (state.decoder)
        chunk = state.decoder.write(chunk);
  
      // don't skip over falsy values in objectMode
      //if (state.objectMode && util.isNullOrUndefined(chunk))
      if (state.objectMode && (chunk === null || chunk === undefined))
        return;
      else if (!state.objectMode && (!chunk || !chunk.length))
        return;
  
      var ret = self.push(chunk);
      if (!ret) {
        paused = true;
        stream.pause();
      }
    });
  
    // proxy all the other methods.
    // important when wrapping filters and duplexes.
    for (var i in stream) {
      if (typeof stream[i] === 'function' &&
          typeof this[i] === 'undefined') {
        this[i] = function(method) { return function() {
          return stream[method].apply(stream, arguments);
        }}(i);
      }
    }
  
    // proxy certain important events.
    var events = ['error', 'close', 'destroy', 'pause', 'resume'];
    forEach(events, function(ev) {
      stream.on(ev, self.emit.bind(self, ev));
    });
  
    // when we try to consume some more bytes, simply unpause the
    // underlying stream.
    self._read = function(n) {
      if (paused) {
        paused = false;
        stream.resume();
      }
    };
  
    return self;
  };
  
  
  
  // exposed for testing purposes only.
  Readable._fromList = fromList;
  
  // Pluck off n bytes from an array of buffers.
  // Length is the combined lengths of all the buffers in the list.
  function fromList(n, state) {
    var list = state.buffer;
    var length = state.length;
    var stringMode = !!state.decoder;
    var objectMode = !!state.objectMode;
    var ret;
  
    // nothing in the list, definitely empty.
    if (list.length === 0)
      return null;
  
    if (length === 0)
      ret = null;
    else if (objectMode)
      ret = list.shift();
    else if (!n || n >= length) {
      // read it all, truncate the array.
      if (stringMode)
        ret = list.join('');
      else
        ret = Buffer.concat(list, length);
      list.length = 0;
    } else {
      // read just some of it.
      if (n < list[0].length) {
        // just take a part of the first list item.
        // slice is the same for buffers and strings.
        var buf = list[0];
        ret = buf.slice(0, n);
        list[0] = buf.slice(n);
      } else if (n === list[0].length) {
        // first list is a perfect match
        ret = list.shift();
      } else {
        // complex case.
        // we have enough to cover it, but it spans past the first buffer.
        if (stringMode)
          ret = '';
        else
          ret = new Buffer(n);
  
        var c = 0;
        for (var i = 0, l = list.length; i < l && c < n; i++) {
          var buf = list[0];
          var cpy = Math.min(n - c, buf.length);
  
          if (stringMode)
            ret += buf.slice(0, cpy);
          else
            buf.copy(ret, c, 0, cpy);
  
          if (cpy < buf.length)
            list[0] = buf.slice(cpy);
          else
            list.shift();
  
          c += cpy;
        }
      }
    }
  
    return ret;
  }
  
  function endReadable(stream) {
    var state = stream._readableState;
  
    // If we get here before consuming all the bytes, then that is a
    // bug in node.  Should never happen.
    if (state.length > 0)
      throw new Error('endReadable called on non-empty stream');
  
    if (!state.endEmitted && state.calledRead) {
      state.ended = true;
      process.nextTick(function() {
        // Check that we didn't get one last unshift.
        if (!state.endEmitted && state.length === 0) {
          state.endEmitted = true;
          stream.readable = false;
          stream.emit('end');
        }
      });
    }
  }
  
  function forEach (xs, f) {
    for (var i = 0, l = xs.length; i < l; i++) {
      f(xs[i], i);
    }
  }
  
  function indexOf (xs, x) {
    for (var i = 0, l = xs.length; i < l; i++) {
      if (xs[i] === x) return i;
    }
    return -1;
  }
  
  }).call(this,require('_process'))
  },{"_process":103,"buffer":97,"core-util-is":51,"events":100,"inherits":38,"isarray":52,"stream":125,"string_decoder/":53}],49:[function(require,module,exports){
  // Copyright Joyent, Inc. and other Node contributors.
  //
  // Permission is hereby granted, free of charge, to any person obtaining a
  // copy of this software and associated documentation files (the
  // "Software"), to deal in the Software without restriction, including
  // without limitation the rights to use, copy, modify, merge, publish,
  // distribute, sublicense, and/or sell copies of the Software, and to permit
  // persons to whom the Software is furnished to do so, subject to the
  // following conditions:
  //
  // The above copyright notice and this permission notice shall be included
  // in all copies or substantial portions of the Software.
  //
  // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  // USE OR OTHER DEALINGS IN THE SOFTWARE.
  
  
  // a transform stream is a readable/writable stream where you do
  // something with the data.  Sometimes it's called a "filter",
  // but that's not a great name for it, since that implies a thing where
  // some bits pass through, and others are simply ignored.  (That would
  // be a valid example of a transform, of course.)
  //
  // While the output is causally related to the input, it's not a
  // necessarily symmetric or synchronous transformation.  For example,
  // a zlib stream might take multiple plain-text writes(), and then
  // emit a single compressed chunk some time in the future.
  //
  // Here's how this works:
  //
  // The Transform stream has all the aspects of the readable and writable
  // stream classes.  When you write(chunk), that calls _write(chunk,cb)
  // internally, and returns false if there's a lot of pending writes
  // buffered up.  When you call read(), that calls _read(n) until
  // there's enough pending readable data buffered up.
  //
  // In a transform stream, the written data is placed in a buffer.  When
  // _read(n) is called, it transforms the queued up data, calling the
  // buffered _write cb's as it consumes chunks.  If consuming a single
  // written chunk would result in multiple output chunks, then the first
  // outputted bit calls the readcb, and subsequent chunks just go into
  // the read buffer, and will cause it to emit 'readable' if necessary.
  //
  // This way, back-pressure is actually determined by the reading side,
  // since _read has to be called to start processing a new chunk.  However,
  // a pathological inflate type of transform can cause excessive buffering
  // here.  For example, imagine a stream where every byte of input is
  // interpreted as an integer from 0-255, and then results in that many
  // bytes of output.  Writing the 4 bytes {ff,ff,ff,ff} would result in
  // 1kb of data being output.  In this case, you could write a very small
  // amount of input, and end up with a very large amount of output.  In
  // such a pathological inflating mechanism, there'd be no way to tell
  // the system to stop doing the transform.  A single 4MB write could
  // cause the system to run out of memory.
  //
  // However, even in such a pathological case, only a single written chunk
  // would be consumed, and then the rest would wait (un-transformed) until
  // the results of the previous transformed chunk were consumed.
  
  module.exports = Transform;
  
  var Duplex = require('./_stream_duplex');
  
  /*<replacement>*/
  var util = require('core-util-is');
  util.inherits = require('inherits');
  /*</replacement>*/
  
  util.inherits(Transform, Duplex);
  
  
  function TransformState(options, stream) {
    this.afterTransform = function(er, data) {
      return afterTransform(stream, er, data);
    };
  
    this.needTransform = false;
    this.transforming = false;
    this.writecb = null;
    this.writechunk = null;
  }
  
  function afterTransform(stream, er, data) {
    var ts = stream._transformState;
    ts.transforming = false;
  
    var cb = ts.writecb;
  
    if (!cb)
      return stream.emit('error', new Error('no writecb in Transform class'));
  
    ts.writechunk = null;
    ts.writecb = null;
  
    if (data !== null && data !== undefined)
      stream.push(data);
  
    if (cb)
      cb(er);
  
    var rs = stream._readableState;
    rs.reading = false;
    if (rs.needReadable || rs.length < rs.highWaterMark) {
      stream._read(rs.highWaterMark);
    }
  }
  
  
  function Transform(options) {
    if (!(this instanceof Transform))
      return new Transform(options);
  
    Duplex.call(this, options);
  
    var ts = this._transformState = new TransformState(options, this);
  
    // when the writable side finishes, then flush out anything remaining.
    var stream = this;
  
    // start out asking for a readable event once data is transformed.
    this._readableState.needReadable = true;
  
    // we have implemented the _read method, and done the other things
    // that Readable wants before the first _read call, so unset the
    // sync guard flag.
    this._readableState.sync = false;
  
    this.once('finish', function() {
      if ('function' === typeof this._flush)
        this._flush(function(er) {
          done(stream, er);
        });
      else
        done(stream);
    });
  }
  
  Transform.prototype.push = function(chunk, encoding) {
    this._transformState.needTransform = false;
    return Duplex.prototype.push.call(this, chunk, encoding);
  };
  
  // This is the part where you do stuff!
  // override this function in implementation classes.
  // 'chunk' is an input chunk.
  //
  // Call `push(newChunk)` to pass along transformed output
  // to the readable side.  You may call 'push' zero or more times.
  //
  // Call `cb(err)` when you are done with this chunk.  If you pass
  // an error, then that'll put the hurt on the whole operation.  If you
  // never call cb(), then you'll never get another chunk.
  Transform.prototype._transform = function(chunk, encoding, cb) {
    throw new Error('not implemented');
  };
  
  Transform.prototype._write = function(chunk, encoding, cb) {
    var ts = this._transformState;
    ts.writecb = cb;
    ts.writechunk = chunk;
    ts.writeencoding = encoding;
    if (!ts.transforming) {
      var rs = this._readableState;
      if (ts.needTransform ||
          rs.needReadable ||
          rs.length < rs.highWaterMark)
        this._read(rs.highWaterMark);
    }
  };
  
  // Doesn't matter what the args are here.
  // _transform does all the work.
  // That we got here means that the readable side wants more data.
  Transform.prototype._read = function(n) {
    var ts = this._transformState;
  
    if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
      ts.transforming = true;
      this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
    } else {
      // mark that we need a transform, so that any data that comes in
      // will get processed, now that we've asked for it.
      ts.needTransform = true;
    }
  };
  
  
  function done(stream, er) {
    if (er)
      return stream.emit('error', er);
  
    // if there's nothing in the write buffer, then that means
    // that nothing more will ever be provided
    var ws = stream._writableState;
    var rs = stream._readableState;
    var ts = stream._transformState;
  
    if (ws.length)
      throw new Error('calling transform done when ws.length != 0');
  
    if (ts.transforming)
      throw new Error('calling transform done when still transforming');
  
    return stream.push(null);
  }
  
  },{"./_stream_duplex":46,"core-util-is":51,"inherits":38}],50:[function(require,module,exports){
  (function (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
  // "Software"), to deal in the Software without restriction, including
  // without limitation the rights to use, copy, modify, merge, publish,
  // distribute, sublicense, and/or sell copies of the Software, and to permit
  // persons to whom the Software is furnished to do so, subject to the
  // following conditions:
  //
  // The above copyright notice and this permission notice shall be included
  // in all copies or substantial portions of the Software.
  //
  // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  // USE OR OTHER DEALINGS IN THE SOFTWARE.
  
  // A bit simpler than readable streams.
  // Implement an async ._write(chunk, cb), and it'll handle all
  // the drain event emission and buffering.
  
  module.exports = Writable;
  
  /*<replacement>*/
  var Buffer = require('buffer').Buffer;
  /*</replacement>*/
  
  Writable.WritableState = WritableState;
  
  
  /*<replacement>*/
  var util = require('core-util-is');
  util.inherits = require('inherits');
  /*</replacement>*/
  
  var Stream = require('stream');
  
  util.inherits(Writable, Stream);
  
  function WriteReq(chunk, encoding, cb) {
    this.chunk = chunk;
    this.encoding = encoding;
    this.callback = cb;
  }
  
  function WritableState(options, stream) {
    options = options || {};
  
    // 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;
    this.highWaterMark = (hwm || hwm === 0) ? hwm : 16 * 1024;
  
    // object stream flag to indicate whether or not this stream
    // contains buffers or objects.
    this.objectMode = !!options.objectMode;
  
    // cast to ints.
    this.highWaterMark = ~~this.highWaterMark;
  
    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;
  
    // should we decode strings into buffers before passing to _write?
    // this is here so that some node-core streams can optimize string
    // handling at a lower level.
    var noDecode = options.decodeStrings === false;
    this.decodeStrings = !noDecode;
  
    // Crypto is kind of old and crusty.  Historically, its default string
    // encoding is 'binary' so we have to make this configurable.
    // Everything else in the universe uses 'utf8', though.
    this.defaultEncoding = options.defaultEncoding || 'utf8';
  
    // not an actual buffer we keep track of, but a measurement
    // of how much we're waiting to get pushed to some underlying
    // socket or file.
    this.length = 0;
  
    // a flag to see when we're in the middle of a write.
    this.writing = false;
  
    // 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, becuase any
    // actions that shouldn't happen until "later" should generally also
    // not happen before the first write call.
    this.sync = true;
  
    // a flag to know if we're processing previously buffered items, which
    // may call the _write() callback in the same tick, so that we don't
    // end up in an overlapped onwrite situation.
    this.bufferProcessing = false;
  
    // the callback that's passed to _write(chunk,cb)
    this.onwrite = function(er) {
      onwrite(stream, er);
    };
  
    // the callback that the user supplies to write(chunk,encoding,cb)
    this.writecb = null;
  
    // the amount that is being written when _write is called.
    this.writelen = 0;
  
    this.buffer = [];
  
    // True if the error was already emitted and should not be thrown again
    this.errorEmitted = false;
  }
  
  function Writable(options) {
    var Duplex = require('./_stream_duplex');
  
    // Writable ctor is applied to Duplexes, though they're not
    // instanceof Writable, they're instanceof Readable.
    if (!(this instanceof Writable) && !(this instanceof Duplex))
      return new Writable(options);
  
    this._writableState = new WritableState(options, this);
  
    // legacy.
    this.writable = true;
  
    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, state, cb) {
    var er = new Error('write after end');
    // TODO: defer error events consistently everywhere, not just the cb
    stream.emit('error', er);
    process.nextTick(function() {
      cb(er);
    });
  }
  
  // If we get something that is not a buffer, string, null, or undefined,
  // and we're not in objectMode, then that's an error.
  // Otherwise stream chunks are all considered to be of length=1, and the
  // watermarks determine how many objects to keep in the buffer, rather than
  // how many bytes or characters.
  function validChunk(stream, state, chunk, cb) {
    var valid = true;
    if (!Buffer.isBuffer(chunk) &&
        'string' !== typeof chunk &&
        chunk !== null &&
        chunk !== undefined &&
        !state.objectMode) {
      var er = new TypeError('Invalid non-string/buffer chunk');
      stream.emit('error', er);
      process.nextTick(function() {
        cb(er);
      });
      valid = false;
    }
    return valid;
  }
  
  Writable.prototype.write = function(chunk, encoding, cb) {
    var state = this._writableState;
    var ret = false;
  
    if (typeof encoding === 'function') {
      cb = encoding;
      encoding = null;
    }
  
    if (Buffer.isBuffer(chunk))
      encoding = 'buffer';
    else if (!encoding)
      encoding = state.defaultEncoding;
  
    if (typeof cb !== 'function')
      cb = function() {};
  
    if (state.ended)
      writeAfterEnd(this, state, cb);
    else if (validChunk(this, state, chunk, cb))
      ret = writeOrBuffer(this, state, chunk, encoding, cb);
  
    return ret;
  };
  
  function decodeChunk(state, chunk, encoding) {
    if (!state.objectMode &&
        state.decodeStrings !== false &&
        typeof chunk === 'string') {
      chunk = new Buffer(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, chunk, encoding, cb) {
    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.buffer.push(new WriteReq(chunk, encoding, cb));
    else
      doWrite(stream, state, len, chunk, encoding, cb);
  
    return ret;
  }
  
  function doWrite(stream, state, len, chunk, encoding, cb) {
    state.writelen = len;
    state.writecb = cb;
    state.writing = true;
    state.sync = true;
    stream._write(chunk, encoding, state.onwrite);
    state.sync = false;
  }
  
  function onwriteError(stream, state, sync, er, cb) {
    if (sync)
      process.nextTick(function() {
        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(stream, state);
  
      if (!finished && !state.bufferProcessing && state.buffer.length)
        clearBuffer(stream, state);
  
      if (sync) {
        process.nextTick(function() {
          afterWrite(stream, state, finished, cb);
        });
      } else {
        afterWrite(stream, state, finished, cb);
      }
    }
  }
  
  function afterWrite(stream, state, finished, cb) {
    if (!finished)
      onwriteDrain(stream, state);
    cb();
    if (finished)
      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;
  
    for (var c = 0; c < state.buffer.length; c++) {
      var entry = state.buffer[c];
      var chunk = entry.chunk;
      var encoding = entry.encoding;
      var cb = entry.callback;
      var len = state.objectMode ? 1 : chunk.length;
  
      doWrite(stream, state, len, chunk, encoding, cb);
  
      // 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) {
        c++;
        break;
      }
    }
  
    state.bufferProcessing = false;
    if (c < state.buffer.length)
      state.buffer = state.buffer.slice(c);
    else
      state.buffer.length = 0;
  }
  
  Writable.prototype._write = function(chunk, encoding, cb) {
    cb(new Error('not implemented'));
  };
  
  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 (typeof chunk !== 'undefined' && chunk !== null)
      this.write(chunk, encoding);
  
    // ignore unnecessary end() calls.
    if (!state.ending && !state.finished)
      endWritable(this, state, cb);
  };
  
  
  function needFinish(stream, state) {
    return (state.ending &&
            state.length === 0 &&
            !state.finished &&
            !state.writing);
  }
  
  function finishMaybe(stream, state) {
    var need = needFinish(stream, state);
    if (need) {
      state.finished = true;
      stream.emit('finish');
    }
    return need;
  }
  
  function endWritable(stream, state, cb) {
    state.ending = true;
    finishMaybe(stream, state);
    if (cb) {
      if (state.finished)
        process.nextTick(cb);
      else
        stream.once('finish', cb);
    }
    state.ended = true;
  }
  
  }).call(this,require('_process'))
  },{"./_stream_duplex":46,"_process":103,"buffer":97,"core-util-is":51,"inherits":38,"stream":125}],51:[function(require,module,exports){
  (function (Buffer){
  // Copyright Joyent, Inc. and other Node contributors.
  //
  // Permission is hereby granted, free of charge, to any person obtaining a
  // copy of this software and associated documentation files (the
  // "Software"), to deal in the Software without restriction, including
  // without limitation the rights to use, copy, modify, merge, publish,
  // distribute, sublicense, and/or sell copies of the Software, and to permit
  // persons to whom the Software is furnished to do so, subject to the
  // following conditions:
  //
  // The above copyright notice and this permission notice shall be included
  // in all copies or substantial portions of the Software.
  //
  // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  // USE OR OTHER DEALINGS IN THE SOFTWARE.
  
  // NOTE: These type checking functions intentionally don't use `instanceof`
  // because it is fragile and can be easily faked with `Object.create()`.
  
  function isArray(arg) {
    if (Array.isArray) {
      return Array.isArray(arg);
    }
    return objectToString(arg) === '[object Array]';
  }
  exports.isArray = isArray;
  
  function isBoolean(arg) {
    return typeof arg === 'boolean';
  }
  exports.isBoolean = isBoolean;
  
  function isNull(arg) {
    return arg === null;
  }
  exports.isNull = isNull;
  
  function isNullOrUndefined(arg) {
    return arg == null;
  }
  exports.isNullOrUndefined = isNullOrUndefined;
  
  function isNumber(arg) {
    return typeof arg === 'number';
  }
  exports.isNumber = isNumber;
  
  function isString(arg) {
    return typeof arg === 'string';
  }
  exports.isString = isString;
  
  function isSymbol(arg) {
    return typeof arg === 'symbol';
  }
  exports.isSymbol = isSymbol;
  
  function isUndefined(arg) {
    return arg === void 0;
  }
  exports.isUndefined = isUndefined;
  
  function isRegExp(re) {
    return objectToString(re) === '[object RegExp]';
  }
  exports.isRegExp = isRegExp;
  
  function isObject(arg) {
    return typeof arg === 'object' && arg !== null;
  }
  exports.isObject = isObject;
  
  function isDate(d) {
    return objectToString(d) === '[object Date]';
  }
  exports.isDate = isDate;
  
  function isError(e) {
    return (objectToString(e) === '[object Error]' || e instanceof Error);
  }
  exports.isError = isError;
  
  function isFunction(arg) {
    return typeof arg === 'function';
  }
  exports.isFunction = isFunction;
  
  function isPrimitive(arg) {
    return arg === null ||
           typeof arg === 'boolean' ||
           typeof arg === 'number' ||
           typeof arg === 'string' ||
           typeof arg === 'symbol' ||  // ES6 symbol
           typeof arg === 'undefined';
  }
  exports.isPrimitive = isPrimitive;
  
  exports.isBuffer = Buffer.isBuffer;
  
  function objectToString(o) {
    return Object.prototype.toString.call(o);
  }
  
  }).call(this,{"isBuffer":require("../../../../../../../../../../../../../../usr/local/lib/node_modules/browserify/node_modules/insert-module-globals/node_modules/is-buffer/index.js")})
  },{"../../../../../../../../../../../../../../usr/local/lib/node_modules/browserify/node_modules/insert-module-globals/node_modules/is-buffer/index.js":102}],52:[function(require,module,exports){
  module.exports = Array.isArray || function (arr) {
    return Object.prototype.toString.call(arr) == '[object Array]';
  };
  
  },{}],53:[function(require,module,exports){
  // Copyright Joyent, Inc. and other Node contributors.
  //
  // Permission is hereby granted, free of charge, to any person obtaining a
  // copy of this software and associated documentation files (the
  // "Software"), to deal in the Software without restriction, including
  // without limitation the rights to use, copy, modify, merge, publish,
  // distribute, sublicense, and/or sell copies of the Software, and to permit
  // persons to whom the Software is furnished to do so, subject to the
  // following conditions:
  //
  // The above copyright notice and this permission notice shall be included
  // in all copies or substantial portions of the Software.
  //
  // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  // USE OR OTHER DEALINGS IN THE SOFTWARE.
  
  var Buffer = require('buffer').Buffer;
  
  var isBufferEncoding = Buffer.isEncoding
    || function(encoding) {
         switch (encoding && encoding.toLowerCase()) {
           case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': case 'raw': return true;
           default: return false;
         }
       }
  
  
  function assertEncoding(encoding) {
    if (encoding && !isBufferEncoding(encoding)) {
      throw new Error('Unknown encoding: ' + encoding);
    }
  }
  
  // StringDecoder provides an interface for efficiently splitting a series of
  // buffers into a series of JS strings without breaking apart multi-byte
  // characters. CESU-8 is handled as part of the UTF-8 encoding.
  //
  // @TODO Handling all encodings inside a single object makes it very difficult
  // to reason about this code, so it should be split up in the future.
  // @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code
  // points as used by CESU-8.
  var StringDecoder = exports.StringDecoder = function(encoding) {
    this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, '');
    assertEncoding(encoding);
    switch (this.encoding) {
      case 'utf8':
        // CESU-8 represents each of Surrogate Pair by 3-bytes
        this.surrogateSize = 3;
        break;
      case 'ucs2':
      case 'utf16le':
        // UTF-16 represents each of Surrogate Pair by 2-bytes
        this.surrogateSize = 2;
        this.detectIncompleteChar = utf16DetectIncompleteChar;
        break;
      case 'base64':
        // Base-64 stores 3 bytes in 4 chars, and pads the remainder.
        this.surrogateSize = 3;
        this.detectIncompleteChar = base64DetectIncompleteChar;
        break;
      default:
        this.write = passThroughWrite;
        return;
    }
  
    // Enough space to store all bytes of a single character. UTF-8 needs 4
    // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate).
    this.charBuffer = new Buffer(6);
    // Number of bytes received for the current incomplete multi-byte character.
    this.charReceived = 0;
    // Number of bytes expected for the current incomplete multi-byte character.
    this.charLength = 0;
  };
  
  
  // write decodes the given buffer and returns it as JS string that is
  // guaranteed to not contain any partial multi-byte characters. Any partial
  // character found at the end of the buffer is buffered up, and will be
  // returned when calling write again with the remaining bytes.
  //
  // Note: Converting a Buffer containing an orphan surrogate to a String
  // currently works, but converting a String to a Buffer (via `new Buffer`, or
  // Buffer#write) will replace incomplete surrogates with the unicode
  // replacement character. See https://codereview.chromium.org/121173009/ .
  StringDecoder.prototype.write = function(buffer) {
    var charStr = '';
    // if our last write ended with an incomplete multibyte character
    while (this.charLength) {
      // determine how many remaining bytes this buffer has to offer for this char
      var available = (buffer.length >= this.charLength - this.charReceived) ?
          this.charLength - this.charReceived :
          buffer.length;
  
      // add the new bytes to the char buffer
      buffer.copy(this.charBuffer, this.charReceived, 0, available);
      this.charReceived += available;
  
      if (this.charReceived < this.charLength) {
        // still not enough chars in this buffer? wait for more ...
        return '';
      }
  
      // remove bytes belonging to the current character from the buffer
      buffer = buffer.slice(available, buffer.length);
  
      // get the character that was split
      charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding);
  
      // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character
      var charCode = charStr.charCodeAt(charStr.length - 1);
      if (charCode >= 0xD800 && charCode <= 0xDBFF) {
        this.charLength += this.surrogateSize;
        charStr = '';
        continue;
      }
      this.charReceived = this.charLength = 0;
  
      // if there are no more bytes in this buffer, just emit our char
      if (buffer.length === 0) {
        return charStr;
      }
      break;
    }
  
    // determine and set charLength / charReceived
    this.detectIncompleteChar(buffer);
  
    var end = buffer.length;
    if (this.charLength) {
      // buffer the incomplete character bytes we got
      buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end);
      end -= this.charReceived;
    }
  
    charStr += buffer.toString(this.encoding, 0, end);
  
    var end = charStr.length - 1;
    var charCode = charStr.charCodeAt(end);
    // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character
    if (charCode >= 0xD800 && charCode <= 0xDBFF) {
      var size = this.surrogateSize;
      this.charLength += size;
      this.charReceived += size;
      this.charBuffer.copy(this.charBuffer, size, 0, size);
      buffer.copy(this.charBuffer, 0, 0, size);
      return charStr.substring(0, end);
    }
  
    // or just emit the charStr
    return charStr;
  };
  
  // detectIncompleteChar determines if there is an incomplete UTF-8 character at
  // the end of the given buffer. If so, it sets this.charLength to the byte
  // length that character, and sets this.charReceived to the number of bytes
  // that are available for this character.
  StringDecoder.prototype.detectIncompleteChar = function(buffer) {
    // determine how many bytes we have to check at the end of this buffer
    var i = (buffer.length >= 3) ? 3 : buffer.length;
  
    // Figure out if one of the last i bytes of our buffer announces an
    // incomplete char.
    for (; i > 0; i--) {
      var c = buffer[buffer.length - i];
  
      // See http://en.wikipedia.org/wiki/UTF-8#Description
  
      // 110XXXXX
      if (i == 1 && c >> 5 == 0x06) {
        this.charLength = 2;
        break;
      }
  
      // 1110XXXX
      if (i <= 2 && c >> 4 == 0x0E) {
        this.charLength = 3;
        break;
      }
  
      // 11110XXX
      if (i <= 3 && c >> 3 == 0x1E) {
        this.charLength = 4;
        break;
      }
    }
    this.charReceived = i;
  };
  
  StringDecoder.prototype.end = function(buffer) {
    var res = '';
    if (buffer && buffer.length)
      res = this.write(buffer);
  
    if (this.charReceived) {
      var cr = this.charReceived;
      var buf = this.charBuffer;
      var enc = this.encoding;
      res += buf.slice(0, cr).toString(enc);
    }
  
    return res;
  };
  
  function passThroughWrite(buffer) {
    return buffer.toString(this.encoding);
  }
  
  function utf16DetectIncompleteChar(buffer) {
    this.charReceived = buffer.length % 2;
    this.charLength = this.charReceived ? 2 : 0;
  }
  
  function base64DetectIncompleteChar(buffer) {
    this.charReceived = buffer.length % 3;
    this.charLength = this.charReceived ? 3 : 0;
  }
  
  },{"buffer":97}],54:[function(require,module,exports){
  (function (process){
  var Stream = require('stream'); // hack to fix a circular dependency issue when used with browserify
  exports = module.exports = require('./lib/_stream_readable.js');
  exports.Stream = Stream;
  exports.Readable = exports;
  exports.Writable = require('./lib/_stream_writable.js');
  exports.Duplex = require('./lib/_stream_duplex.js');
  exports.Transform = require('./lib/_stream_transform.js');
  exports.PassThrough = require('./lib/_stream_passthrough.js');
  if (!process.browser && process.env.READABLE_STREAM === 'disable') {
    module.exports = require('stream');
  }
  
  }).call(this,require('_process'))
  },{"./lib/_stream_duplex.js":46,"./lib/_stream_passthrough.js":47,"./lib/_stream_readable.js":48,"./lib/_stream_transform.js":49,"./lib/_stream_writable.js":50,"_process":103,"stream":125}],55:[function(require,module,exports){
  (function (process,Buffer){
  var stream = require('readable-stream')
  var eos = require('end-of-stream')
  var inherits = require('inherits')
  var shift = require('stream-shift')
  
  var SIGNAL_FLUSH = new Buffer([0])
  
  var onuncork = function(self, fn) {
    if (self._corked) self.once('uncork', fn)
    else fn()
  }
  
  var destroyer = function(self, end) {
    return function(err) {
      if (err) self.destroy(err.message === 'premature close' ? null : err)
      else if (end && !self._ended) self.end()
    }
  }
  
  var end = function(ws, fn) {
    if (!ws) return fn()
    if (ws._writableState && ws._writableState.finished) return fn()
    if (ws._writableState) return ws.end(fn)
    ws.end()
    fn()
  }
  
  var toStreams2 = function(rs) {
    return new (stream.Readable)({objectMode:true, highWaterMark:16}).wrap(rs)
  }
  
  var Duplexify = function(writable, readable, opts) {
    if (!(this instanceof Duplexify)) return new Duplexify(writable, readable, opts)
    stream.Duplex.call(this, opts)
  
    this._writable = null
    this._readable = null
    this._readable2 = null
  
    this._forwardDestroy = !opts || opts.destroy !== false
    this._forwardEnd = !opts || opts.end !== false
    this._corked = 1 // start corked
    this._ondrain = null
    this._drained = false
    this._forwarding = false
    this._unwrite = null
    this._unread = null
    this._ended = false
  
    this.destroyed = false
  
    if (writable) this.setWritable(writable)
    if (readable) this.setReadable(readable)
  }
  
  inherits(Duplexify, stream.Duplex)
  
  Duplexify.obj = function(writable, readable, opts) {
    if (!opts) opts = {}
    opts.objectMode = true
    opts.highWaterMark = 16
    return new Duplexify(writable, readable, opts)
  }
  
  Duplexify.prototype.cork = function() {
    if (++this._corked === 1) this.emit('cork')
  }
  
  Duplexify.prototype.uncork = function() {
    if (this._corked && --this._corked === 0) this.emit('uncork')
  }
  
  Duplexify.prototype.setWritable = function(writable) {
    if (this._unwrite) this._unwrite()
  
    if (this.destroyed) {
      if (writable && writable.destroy) writable.destroy()
      return
    }
  
    if (writable === null || writable === false) {
      this.end()
      return
    }
  
    var self = this
    var unend = eos(writable, {writable:true, readable:false}, destroyer(this, this._forwardEnd))
  
    var ondrain = function() {
      var ondrain = self._ondrain
      self._ondrain = null
      if (ondrain) ondrain()
    }
  
    var clear = function() {
      self._writable.removeListener('drain', ondrain)
      unend()
    }
  
    if (this._unwrite) process.nextTick(ondrain) // force a drain on stream reset to avoid livelocks
  
    this._writable = writable
    this._writable.on('drain', ondrain)
    this._unwrite = clear
  
    this.uncork() // always uncork setWritable
  }
  
  Duplexify.prototype.setReadable = function(readable) {
    if (this._unread) this._unread()
  
    if (this.destroyed) {
      if (readable && readable.destroy) readable.destroy()
      return
    }
  
    if (readable === null || readable === false) {
      this.push(null)
      this.resume()
      return
    }
  
    var self = this
    var unend = eos(readable, {writable:false, readable:true}, destroyer(this))
  
    var onreadable = function() {
      self._forward()
    }
  
    var onend = function() {
      self.push(null)
    }
  
    var clear = function() {
      self._readable2.removeListener('readable', onreadable)
      self._readable2.removeListener('end', onend)
      unend()
    }
  
    this._drained = true
    this._readable = readable
    this._readable2 = readable._readableState ? readable : toStreams2(readable)
    this._readable2.on('readable', onreadable)
    this._readable2.on('end', onend)
    this._unread = clear
  
    this._forward()
  }
  
  Duplexify.prototype._read = function() {
    this._drained = true
    this._forward()
  }
  
  Duplexify.prototype._forward = function() {
    if (this._forwarding || !this._readable2 || !this._drained) return
    this._forwarding = true
  
    var data
  
    while (this._drained && (data = shift(this._readable2)) !== null) {
      if (this.destroyed) continue
      this._drained = this.push(data)
    }
  
    this._forwarding = false
  }
  
  Duplexify.prototype.destroy = function(err) {
    if (this.destroyed) return
    this.destroyed = true
  
    var self = this
    process.nextTick(function() {
      self._destroy(err)
    })
  }
  
  Duplexify.prototype._destroy = function(err) {
    if (err) {
      var ondrain = this._ondrain
      this._ondrain = null
      if (ondrain) ondrain(err)
      else this.emit('error', err)
    }
  
    if (this._forwardDestroy) {
      if (this._readable && this._readable.destroy) this._readable.destroy()
      if (this._writable && this._writable.destroy) this._writable.destroy()
    }
  
    this.emit('close')
  }
  
  Duplexify.prototype._write = function(data, enc, cb) {
    if (this.destroyed) return cb()
    if (this._corked) return onuncork(this, this._write.bind(this, data, enc, cb))
    if (data === SIGNAL_FLUSH) return this._finish(cb)
    if (!this._writable) return cb()
  
    if (this._writable.write(data) === false) this._ondrain = cb
    else cb()
  }
  
  
  Duplexify.prototype._finish = function(cb) {
    var self = this
    this.emit('preend')
    onuncork(this, function() {
      end(self._forwardEnd && self._writable, function() {
        // haxx to not emit prefinish twice
        if (self._writableState.prefinished === false) self._writableState.prefinished = true
        self.emit('prefinish')
        onuncork(self, cb)
      })
    })
  }
  
  Duplexify.prototype.end = function(data, enc, cb) {
    if (typeof data === 'function') return this.end(null, null, data)
    if (typeof enc === 'function') return this.end(data, null, enc)
    this._ended = true
    if (data) this.write(data)
    if (!this._writableState.ending) this.write(SIGNAL_FLUSH)
    return stream.Writable.prototype.end.call(this, cb)
  }
  
  module.exports = Duplexify
  
  }).call(this,require('_process'),require("buffer").Buffer)
  },{"_process":103,"buffer":97,"end-of-stream":56,"inherits":38,"readable-stream":73,"stream-shift":74}],56:[function(require,module,exports){
  var once = require('once');
  
  var noop = function() {};
  
  var isRequest = function(stream) {
  	return stream.setHeader && typeof stream.abort === 'function';
  };
  
  var eos = function(stream, opts, callback) {
  	if (typeof opts === 'function') return eos(stream, null, opts);
  	if (!opts) opts = {};
  
  	callback = once(callback || noop);
  
  	var ws = stream._writableState;
  	var rs = stream._readableState;
  	var readable = opts.readable || (opts.readable !== false && stream.readable);
  	var writable = opts.writable || (opts.writable !== false && stream.writable);
  
  	var onlegacyfinish = function() {
  		if (!stream.writable) onfinish();
  	};
  
  	var onfinish = function() {
  		writable = false;
  		if (!readable) callback();
  	};
  
  	var onend = function() {
  		readable = false;
  		if (!writable) callback();
  	};
  
  	var onclose = function() {
  		if (readable && !(rs && rs.ended)) return callback(new Error('premature close'));
  		if (writable && !(ws && ws.ended)) return callback(new Error('premature close'));
  	};
  
  	var onrequest = function() {
  		stream.req.on('finish', onfinish);
  	};
  
  	if (isRequest(stream)) {
  		stream.on('complete', onfinish);
  		stream.on('abort', onclose);
  		if (stream.req) onrequest();
  		else stream.on('request', onrequest);
  	} else if (writable && !ws) { // legacy streams
  		stream.on('end', onlegacyfinish);
  		stream.on('close', onlegacyfinish);
  	}
  
  	stream.on('end', onend);
  	stream.on('finish', onfinish);
  	if (opts.error !== false) stream.on('error', callback);
  	stream.on('close', onclose);
  
  	return function() {
  		stream.removeListener('complete', onfinish);
  		stream.removeListener('abort', onclose);
  		stream.removeListener('request', onrequest);
  		if (stream.req) stream.req.removeListener('finish', onfinish);
  		stream.removeListener('end', onlegacyfinish);
  		stream.removeListener('close', onlegacyfinish);
  		stream.removeListener('finish', onfinish);
  		stream.removeListener('end', onend);
  		stream.removeListener('error', callback);
  		stream.removeListener('close', onclose);
  	};
  };
  
  module.exports = eos;
  },{"once":58}],57:[function(require,module,exports){
  arguments[4][36][0].apply(exports,arguments)
  },{"dup":36}],58:[function(require,module,exports){
  var wrappy = require('wrappy')
  module.exports = wrappy(once)
  
  once.proto = once(function () {
    Object.defineProperty(Function.prototype, 'once', {
      value: function () {
        return once(this)
      },
      configurable: true
    })
  })
  
  function once (fn) {
    var f = function () {
      if (f.called) return f.value
      f.called = true
      return f.value = fn.apply(this, arguments)
    }
    f.called = false
    return f
  }
  
  },{"wrappy":57}],59:[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';
  
  /*<replacement>*/
  
  var objectKeys = Object.keys || function (obj) {
    var keys = [];
    for (var key in obj) {
      keys.push(key);
    }return keys;
  };
  /*</replacement>*/
  
  module.exports = Duplex;
  
  /*<replacement>*/
  var processNextTick = require('process-nextick-args');
  /*</replacement>*/
  
  /*<replacement>*/
  var util = require('core-util-is');
  util.inherits = require('inherits');
  /*</replacement>*/
  
  var Readable = require('./_stream_readable');
  var Writable = require('./_stream_writable');
  
  util.inherits(Duplex, Readable);
  
  var keys = objectKeys(Writable.prototype);
  for (var v = 0; v < keys.length; v++) {
    var method = keys[v];
    if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
  }
  
  function Duplex(options) {
    if (!(this instanceof Duplex)) return new Duplex(options);
  
    Readable.call(this, options);
    Writable.call(this, options);
  
    if (options && options.readable === false) this.readable = false;
  
    if (options && options.writable === false) this.writable = false;
  
    this.allowHalfOpen = true;
    if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;
  
    this.once('end', onend);
  }
  
  // the no-half-open enforcer
  function onend() {
    // if we allow half-open state, or if the writable side ended,
    // then we're ok.
    if (this.allowHalfOpen || this._writableState.ended) return;
  
    // no more data can be written.
    // But allow more writes to happen in this tick.
    processNextTick(onEndNT, this);
  }
  
  function onEndNT(self) {
    self.end();
  }
  
  function forEach(xs, f) {
    for (var i = 0, l = xs.length; i < l; i++) {
      f(xs[i], i);
    }
  }
  },{"./_stream_readable":61,"./_stream_writable":63,"core-util-is":67,"inherits":38,"process-nextick-args":69}],60:[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';
  
  module.exports = PassThrough;
  
  var Transform = require('./_stream_transform');
  
  /*<replacement>*/
  var util = require('core-util-is');
  util.inherits = require('inherits');
  /*</replacement>*/
  
  util.inherits(PassThrough, Transform);
  
  function PassThrough(options) {
    if (!(this instanceof PassThrough)) return new PassThrough(options);
  
    Transform.call(this, options);
  }
  
  PassThrough.prototype._transform = function (chunk, encoding, cb) {
    cb(null, chunk);
  };
  },{"./_stream_transform":62,"core-util-is":67,"inherits":38}],61:[function(require,module,exports){
  (function (process){
  'use strict';
  
  module.exports = Readable;
  
  /*<replacement>*/
  var processNextTick = require('process-nextick-args');
  /*</replacement>*/
  
  /*<replacement>*/
  var isArray = require('isarray');
  /*</replacement>*/
  
  /*<replacement>*/
  var Duplex;
  /*</replacement>*/
  
  Readable.ReadableState = ReadableState;
  
  /*<replacement>*/
  var EE = require('events').EventEmitter;
  
  var EElistenerCount = function (emitter, type) {
    return emitter.listeners(type).length;
  };
  /*</replacement>*/
  
  /*<replacement>*/
  var Stream = require('./internal/streams/stream');
  /*</replacement>*/
  
  var Buffer = require('buffer').Buffer;
  /*<replacement>*/
  var bufferShim = require('buffer-shims');
  /*</replacement>*/
  
  /*<replacement>*/
  var util = require('core-util-is');
  util.inherits = require('inherits');
  /*</replacement>*/
  
  /*<replacement>*/
  var debugUtil = require('util');
  var debug = void 0;
  if (debugUtil && debugUtil.debuglog) {
    debug = debugUtil.debuglog('stream');
  } else {
    debug = function () {};
  }
  /*</replacement>*/
  
  var BufferList = require('./internal/streams/BufferList');
  var StringDecoder;
  
  util.inherits(Readable, Stream);
  
  var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];
  
  function prependListener(emitter, event, fn) {
    // Sadly this is not cacheable as some libraries bundle their own
    // event emitter implementation with them.
    if (typeof emitter.prependListener === 'function') {
      return emitter.prependListener(event, fn);
    } else {
      // This is a hack to make sure that our error handler is attached before any
      // userland ones.  NEVER DO THIS. This is here only because this code needs
      // to continue to work with older versions of Node.js that do not include
      // the prependListener() method. The goal is to eventually remove this hack.
      if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]];
    }
  }
  
  function ReadableState(options, stream) {
    Duplex = Duplex || require('./_stream_duplex');
  
    options = options || {};
  
    // object stream flag. Used to make read(n) ignore n and to
    // make all the buffer merging and length checks go away
    this.objectMode = !!options.objectMode;
  
    if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.readableObjectMode;
  
    // the point at which it stops calling _read() to fill the buffer
    // Note: 0 is a valid value, means "don't call _read preemptively ever"
    var hwm = options.highWaterMark;
    var defaultHwm = this.objectMode ? 16 : 16 * 1024;
    this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm;
  
    // cast to ints.
    this.highWaterMark = ~~this.highWaterMark;
  
    // A linked list is used to store data chunks instead of an array because the
    // linked list can remove elements from the beginning faster than
    // array.shift()
    this.buffer = new BufferList();
    this.length = 0;
    this.pipes = null;
    this.pipesCount = 0;
    this.flowing = null;
    this.ended = false;
    this.endEmitted = false;
    this.reading = false;
  
    // a flag to be able to tell if the 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;
  
    // whenever we return null, then we set a flag to say
    // that we're awaiting a 'readable' event emission.
    this.needReadable = false;
    this.emittedReadable = false;
    this.readableListening = false;
    this.resumeScheduled = false;
  
    // 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';
  
    // when piping, we only care about 'readable' events that happen
    // after read()ing all the bytes and not getting any pushback.
    this.ranOut = false;
  
    // the number of writers that are awaiting a drain event in .pipe()s
    this.awaitDrain = 0;
  
    // if true, a maybeReadMore has been scheduled
    this.readingMore = false;
  
    this.decoder = null;
    this.encoding = null;
    if (options.encoding) {
      if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
      this.decoder = new StringDecoder(options.encoding);
      this.encoding = options.encoding;
    }
  }
  
  function Readable(options) {
    Duplex = Duplex || require('./_stream_duplex');
  
    if (!(this instanceof Readable)) return new Readable(options);
  
    this._readableState = new ReadableState(options, this);
  
    // legacy
    this.readable = true;
  
    if (options && 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;
  
    if (!state.objectMode && typeof chunk === 'string') {
      encoding = encoding || state.defaultEncoding;
      if (encoding !== state.encoding) {
        chunk = bufferShim.from(chunk, encoding);
        encoding = '';
      }
    }
  
    return readableAddChunk(this, state, chunk, encoding, false);
  };
  
  // Unshift should *always* be something directly out of read()
  Readable.prototype.unshift = function (chunk) {
    var state = this._readableState;
    return readableAddChunk(this, state, chunk, '', true);
  };
  
  Readable.prototype.isPaused = function () {
    return this._readableState.flowing === false;
  };
  
  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 {
        var skipAdd;
        if (state.decoder && !addToFront && !encoding) {
          chunk = state.decoder.write(chunk);
          skipAdd = !state.objectMode && chunk.length === 0;
        }
  
        if (!addToFront) state.reading = false;
  
        // Don't add to the buffer if we've decoded to an empty string chunk and
        // we're not in object mode
        if (!skipAdd) {
          // 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);
  
            if (state.needReadable) emitReadable(stream);
          }
        }
  
        maybeReadMore(stream, state);
      }
    } else if (!addToFront) {
      state.reading = false;
    }
  
    return needMoreData(state);
  }
  
  // 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);
  }
  
  // backwards compatibility.
  Readable.prototype.setEncoding = function (enc) {
    if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
    this._readableState.decoder = new StringDecoder(enc);
    this._readableState.encoding = enc;
    return this;
  };
  
  // Don't raise the hwm > 8MB
  var MAX_HWM = 0x800000;
  function computeNewHighWaterMark(n) {
    if (n >= MAX_HWM) {
      n = MAX_HWM;
    } else {
      // Get the next highest power of 2 to prevent increasing hwm excessively in
      // tiny amounts
      n--;
      n |= n >>> 1;
      n |= n >>> 2;
      n |= n >>> 4;
      n |= n >>> 8;
      n |= n >>> 16;
      n++;
    }
    return n;
  }
  
  // This function is designed to be inlinable, so please take care when making
  // changes to the function body.
  function howMuchToRead(n, state) {
    if (n <= 0 || state.length === 0 && state.ended) return 0;
    if (state.objectMode) return 1;
    if (n !== n) {
      // Only flow one buffer at a time
      if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
    }
    // If we're asking for more than the current hwm, then raise the hwm.
    if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
    if (n <= state.length) return n;
    // Don't have enough
    if (!state.ended) {
      state.needReadable = true;
      return 0;
    }
    return state.length;
  }
  
  // you can override either this method, or the async _read(n) below.
  Readable.prototype.read = function (n) {
    debug('read', n);
    n = parseInt(n, 10);
    var state = this._readableState;
    var nOrig = n;
  
    if (n !== 0) state.emittedReadable = false;
  
    // if we're doing read(0) to trigger a readable event, but we
    // already have a bunch of data in the buffer, then just trigger
    // the 'readable' event and move on.
    if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) {
      debug('read: emitReadable', state.length, state.ended);
      if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
      return null;
    }
  
    n = howMuchToRead(n, state);
  
    // if we've ended, and we're now clear, then finish it up.
    if (n === 0 && state.ended) {
      if (state.length === 0) endReadable(this);
      return null;
    }
  
    // All the actual chunk generation logic needs to be
    // *below* the call to _read.  The reason is that in certain
    // synthetic stream cases, such as passthrough streams, _read
    // may be a completely synchronous operation which may change
    // the state of the read buffer, providing enough data when
    // before there was *not* enough.
    //
    // So, the steps are:
    // 1. Figure out what the state of things will be after we do
    // a read from the buffer.
    //
    // 2. If that resulting state will trigger a _read, then call _read.
    // Note that this may be asynchronous, or synchronous.  Yes, it is
    // deeply ugly to write APIs this way, but that still doesn't mean
    // that the Readable class should behave improperly, as streams are
    // designed to be sync/async agnostic.
    // Take note if the _read call is sync or async (ie, if the read call
    // has returned yet), so that we know whether or not it's safe to emit
    // 'readable' etc.
    //
    // 3. Actually pull the requested chunks out of the buffer and return.
  
    // if we need a readable event, then we need to do some reading.
    var doRead = state.needReadable;
    debug('need readable', doRead);
  
    // if we currently have less than the highWaterMark, then also read some
    if (state.length === 0 || state.length - n < state.highWaterMark) {
      doRead = true;
      debug('length less than watermark', doRead);
    }
  
    // however, if we've ended, then there's no point, and if we're already
    // reading, then it's unnecessary.
    if (state.ended || state.reading) {
      doRead = false;
      debug('reading or ended', doRead);
    } else if (doRead) {
      debug('do read');
      state.reading = true;
      state.sync = true;
      // if the length is currently zero, then we *need* a readable event.
      if (state.length === 0) state.needReadable = true;
      // call internal read method
      this._read(state.highWaterMark);
      state.sync = false;
      // If _read pushed data synchronously, then `reading` will be false,
      // and we need to re-evaluate how much data we can return to the user.
      if (!state.reading) n = howMuchToRead(nOrig, state);
    }
  
    var ret;
    if (n > 0) ret = fromList(n, state);else ret = null;
  
    if (ret === null) {
      state.needReadable = true;
      n = 0;
    } else {
      state.length -= n;
    }
  
    if (state.length === 0) {
      // If we have nothing in the buffer, then we want to know
      // as soon as we *do* get something into the buffer.
      if (!state.ended) state.needReadable = true;
  
      // If we tried to read() past the EOF, then emit end on the next tick.
      if (nOrig !== n && state.ended) endReadable(this);
    }
  
    if (ret !== null) this.emit('data', ret);
  
    return ret;
  };
  
  function chunkInvalid(state, chunk) {
    var er = null;
    if (!Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== null && chunk !== undefined && !state.objectMode) {
      er = new TypeError('Invalid non-string/buffer chunk');
    }
    return er;
  }
  
  function onEofChunk(stream, state) {
    if (state.ended) return;
    if (state.decoder) {
      var chunk = state.decoder.end();
      if (chunk && chunk.length) {
        state.buffer.push(chunk);
        state.length += state.objectMode ? 1 : chunk.length;
      }
    }
    state.ended = true;
  
    // emit 'readable' now to make sure it gets picked up.
    emitReadable(stream);
  }
  
  // Don't emit readable right away in sync mode, because this can trigger
  // another read() call => stack overflow.  This way, it might trigger
  // a nextTick recursion warning, but that's not so bad.
  function emitReadable(stream) {
    var state = stream._readableState;
    state.needReadable = false;
    if (!state.emittedReadable) {
      debug('emitReadable', state.flowing);
      state.emittedReadable = true;
      if (state.sync) processNextTick(emitReadable_, stream);else emitReadable_(stream);
    }
  }
  
  function emitReadable_(stream) {
    debug('emit readable');
    stream.emit('readable');
    flow(stream);
  }
  
  // at this point, the user has presumably seen the 'readable' event,
  // and called read() to consume some data.  that may have triggered
  // in turn another _read(n) call, in which case reading = true if
  // it's in progress.
  // However, if we're not ended, or reading, and the length < hwm,
  // then go ahead and try to read some more preemptively.
  function maybeReadMore(stream, state) {
    if (!state.readingMore) {
      state.readingMore = true;
      processNextTick(maybeReadMore_, stream, state);
    }
  }
  
  function maybeReadMore_(stream, state) {
    var len = state.length;
    while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) {
      debug('maybeReadMore read 0');
      stream.read(0);
      if (len === state.length)
        // didn't get any data, stop spinning.
        break;else len = state.length;
    }
    state.readingMore = false;
  }
  
  // abstract method.  to be overridden in specific implementation classes.
  // call cb(er, data) where data is <= n in length.
  // for virtual (non-string, non-buffer) streams, "length" is somewhat
  // arbitrary, and perhaps not very meaningful.
  Readable.prototype._read = function (n) {
    this.emit('error', new Error('_read() is not implemented'));
  };
  
  Readable.prototype.pipe = function (dest, pipeOpts) {
    var src = this;
    var state = this._readableState;
  
    switch (state.pipesCount) {
      case 0:
        state.pipes = dest;
        break;
      case 1:
        state.pipes = [state.pipes, dest];
        break;
      default:
        state.pipes.push(dest);
        break;
    }
    state.pipesCount += 1;
    debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
  
    var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
  
    var endFn = doEnd ? onend : cleanup;
    if (state.endEmitted) processNextTick(endFn);else src.once('end', endFn);
  
    dest.on('unpipe', onunpipe);
    function onunpipe(readable) {
      debug('onunpipe');
      if (readable === src) {
        cleanup();
      }
    }
  
    function onend() {
      debug('onend');
      dest.end();
    }
  
    // when the dest drains, it reduces the awaitDrain counter
    // on the source.  This would be more elegant with a .once()
    // handler in flow(), but adding and removing repeatedly is
    // too slow.
    var ondrain = pipeOnDrain(src);
    dest.on('drain', ondrain);
  
    var cleanedUp = false;
    function cleanup() {
      debug('cleanup');
      // cleanup event handlers once the pipe is broken
      dest.removeListener('close', onclose);
      dest.removeListener('finish', onfinish);
      dest.removeListener('drain', ondrain);
      dest.removeListener('error', onerror);
      dest.removeListener('unpipe', onunpipe);
      src.removeListener('end', onend);
      src.removeListener('end', cleanup);
      src.removeListener('data', ondata);
  
      cleanedUp = true;
  
      // if the reader is waiting for a drain event from this
      // specific writer, then it would cause it to never start
      // flowing again.
      // So, if this is awaiting a drain, then we just call it now.
      // If we don't know, then assume that we are waiting for one.
      if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
    }
  
    // If the user pushes more data while we're writing to dest then we'll end up
    // in ondata again. However, we only want to increase awaitDrain once because
    // dest will only emit one 'drain' event for the multiple writes.
    // => Introduce a guard on increasing awaitDrain.
    var increasedAwaitDrain = false;
    src.on('data', ondata);
    function ondata(chunk) {
      debug('ondata');
      increasedAwaitDrain = false;
      var ret = dest.write(chunk);
      if (false === ret && !increasedAwaitDrain) {
        // If the user unpiped during `dest.write()`, it is possible
        // to get stuck in a permanently paused state if that write
        // also returned false.
        // => Check whether `dest` is still a piping destination.
        if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
          debug('false write response, pause', src._readableState.awaitDrain);
          src._readableState.awaitDrain++;
          increasedAwaitDrain = true;
        }
        src.pause();
      }
    }
  
    // if the dest has an error, then stop piping into it.
    // however, don't suppress the throwing behavior for this.
    function onerror(er) {
      debug('onerror', er);
      unpipe();
      dest.removeListener('error', onerror);
      if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);
    }
  
    // Make sure our error handler is attached before userland ones.
    prependListener(dest, 'error', onerror);
  
    // Both close and finish should trigger unpipe, but only once.
    function onclose() {
      dest.removeListener('finish', onfinish);
      unpipe();
    }
    dest.once('close', onclose);
    function onfinish() {
      debug('onfinish');
      dest.removeListener('close', onclose);
      unpipe();
    }
    dest.once('finish', onfinish);
  
    function unpipe() {
      debug('unpipe');
      src.unpipe(dest);
    }
  
    // tell the dest that it's being piped to
    dest.emit('pipe', src);
  
    // start the flow if it hasn't been started already.
    if (!state.flowing) {
      debug('pipe resume');
      src.resume();
    }
  
    return dest;
  };
  
  function pipeOnDrain(src) {
    return function () {
      var state = src._readableState;
      debug('pipeOnDrain', state.awaitDrain);
      if (state.awaitDrain) state.awaitDrain--;
      if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
        state.flowing = true;
        flow(src);
      }
    };
  }
  
  Readable.prototype.unpipe = function (dest) {
    var state = this._readableState;
  
    // if we're not piping anywhere, then do nothing.
    if (state.pipesCount === 0) return this;
  
    // just one destination.  most common case.
    if (state.pipesCount === 1) {
      // passed in one, but it's not the right one.
      if (dest && dest !== state.pipes) return this;
  
      if (!dest) dest = state.pipes;
  
      // got a match.
      state.pipes = null;
      state.pipesCount = 0;
      state.flowing = false;
      if (dest) dest.emit('unpipe', this);
      return this;
    }
  
    // slow case. multiple pipe destinations.
  
    if (!dest) {
      // remove all.
      var dests = state.pipes;
      var len = state.pipesCount;
      state.pipes = null;
      state.pipesCount = 0;
      state.flowing = false;
  
      for (var i = 0; i < len; i++) {
        dests[i].emit('unpipe', this);
      }return this;
    }
  
    // try to find the right one.
    var index = indexOf(state.pipes, dest);
    if (index === -1) return this;
  
    state.pipes.splice(index, 1);
    state.pipesCount -= 1;
    if (state.pipesCount === 1) state.pipes = state.pipes[0];
  
    dest.emit('unpipe', this);
  
    return this;
  };
  
  // set up data events if they are asked for
  // Ensure readable listeners eventually get something
  Readable.prototype.on = function (ev, fn) {
    var res = Stream.prototype.on.call(this, ev, fn);
  
    if (ev === 'data') {
      // Start flowing on next tick if stream isn't explicitly paused
      if (this._readableState.flowing !== false) this.resume();
    } else if (ev === 'readable') {
      var state = this._readableState;
      if (!state.endEmitted && !state.readableListening) {
        state.readableListening = state.needReadable = true;
        state.emittedReadable = false;
        if (!state.reading) {
          processNextTick(nReadingNextTick, this);
        } else if (state.length) {
          emitReadable(this, state);
        }
      }
    }
  
    return res;
  };
  Readable.prototype.addListener = Readable.prototype.on;
  
  function nReadingNextTick(self) {
    debug('readable nexttick read 0');
    self.read(0);
  }
  
  // pause() and resume() are remnants of the legacy readable stream API
  // If the user uses them, then switch into old mode.
  Readable.prototype.resume = function () {
    var state = this._readableState;
    if (!state.flowing) {
      debug('resume');
      state.flowing = true;
      resume(this, state);
    }
    return this;
  };
  
  function resume(stream, state) {
    if (!state.resumeScheduled) {
      state.resumeScheduled = true;
      processNextTick(resume_, stream, state);
    }
  }
  
  function resume_(stream, state) {
    if (!state.reading) {
      debug('resume read 0');
      stream.read(0);
    }
  
    state.resumeScheduled = false;
    state.awaitDrain = 0;
    stream.emit('resume');
    flow(stream);
    if (state.flowing && !state.reading) stream.read(0);
  }
  
  Readable.prototype.pause = function () {
    debug('call pause flowing=%j', this._readableState.flowing);
    if (false !== this._readableState.flowing) {
      debug('pause');
      this._readableState.flowing = false;
      this.emit('pause');
    }
    return this;
  };
  
  function flow(stream) {
    var state = stream._readableState;
    debug('flow', state.flowing);
    while (state.flowing && stream.read() !== null) {}
  }
  
  // wrap an old-style stream as the async data source.
  // This is *not* part of the readable stream interface.
  // It is an ugly unfortunate mess of history.
  Readable.prototype.wrap = function (stream) {
    var state = this._readableState;
    var paused = false;
  
    var self = this;
    stream.on('end', function () {
      debug('wrapped end');
      if (state.decoder && !state.ended) {
        var chunk = state.decoder.end();
        if (chunk && chunk.length) self.push(chunk);
      }
  
      self.push(null);
    });
  
    stream.on('data', function (chunk) {
      debug('wrapped data');
      if (state.decoder) chunk = state.decoder.write(chunk);
  
      // don't skip over falsy values in objectMode
      if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
  
      var ret = self.push(chunk);
      if (!ret) {
        paused = true;
        stream.pause();
      }
    });
  
    // proxy all the other methods.
    // important when wrapping filters and duplexes.
    for (var i in stream) {
      if (this[i] === undefined && typeof stream[i] === 'function') {
        this[i] = function (method) {
          return function () {
            return stream[method].apply(stream, arguments);
          };
        }(i);
      }
    }
  
    // proxy certain important events.
    for (var n = 0; n < kProxyEvents.length; n++) {
      stream.on(kProxyEvents[n], self.emit.bind(self, kProxyEvents[n]));
    }
  
    // when we try to consume some more bytes, simply unpause the
    // underlying stream.
    self._read = function (n) {
      debug('wrapped _read', n);
      if (paused) {
        paused = false;
        stream.resume();
      }
    };
  
    return self;
  };
  
  // exposed for testing purposes only.
  Readable._fromList = fromList;
  
  // Pluck off n bytes from an array of buffers.
  // Length is the combined lengths of all the buffers in the list.
  // This function is designed to be inlinable, so please take care when making
  // changes to the function body.
  function fromList(n, state) {
    // nothing buffered
    if (state.length === 0) return null;
  
    var ret;
    if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
      // read it all, truncate the list
      if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length);
      state.buffer.clear();
    } else {
      // read part of list
      ret = fromListPartial(n, state.buffer, state.decoder);
    }
  
    return ret;
  }
  
  // Extracts only enough buffered data to satisfy the amount requested.
  // This function is designed to be inlinable, so please take care when making
  // changes to the function body.
  function fromListPartial(n, list, hasStrings) {
    var ret;
    if (n < list.head.data.length) {
      // slice is the same for buffers and strings
      ret = list.head.data.slice(0, n);
      list.head.data = list.head.data.slice(n);
    } else if (n === list.head.data.length) {
      // first chunk is a perfect match
      ret = list.shift();
    } else {
      // result spans more than one buffer
      ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list);
    }
    return ret;
  }
  
  // Copies a specified amount of characters from the list of buffered data
  // chunks.
  // This function is designed to be inlinable, so please take care when making
  // changes to the function body.
  function copyFromBufferString(n, list) {
    var p = list.head;
    var c = 1;
    var ret = p.data;
    n -= ret.length;
    while (p = p.next) {
      var str = p.data;
      var nb = n > str.length ? str.length : n;
      if (nb === str.length) ret += str;else ret += str.slice(0, n);
      n -= nb;
      if (n === 0) {
        if (nb === str.length) {
          ++c;
          if (p.next) list.head = p.next;else list.head = list.tail = null;
        } else {
          list.head = p;
          p.data = str.slice(nb);
        }
        break;
      }
      ++c;
    }
    list.length -= c;
    return ret;
  }
  
  // Copies a specified amount of bytes from the list of buffered data chunks.
  // This function is designed to be inlinable, so please take care when making
  // changes to the function body.
  function copyFromBuffer(n, list) {
    var ret = bufferShim.allocUnsafe(n);
    var p = list.head;
    var c = 1;
    p.data.copy(ret);
    n -= p.data.length;
    while (p = p.next) {
      var buf = p.data;
      var nb = n > buf.length ? buf.length : n;
      buf.copy(ret, ret.length - n, 0, nb);
      n -= nb;
      if (n === 0) {
        if (nb === buf.length) {
          ++c;
          if (p.next) list.head = p.next;else list.head = list.tail = null;
        } else {
          list.head = p;
          p.data = buf.slice(nb);
        }
        break;
      }
      ++c;
    }
    list.length -= c;
    return ret;
  }
  
  function endReadable(stream) {
    var state = stream._readableState;
  
    // If we get here before consuming all the bytes, then that is a
    // bug in node.  Should never happen.
    if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream');
  
    if (!state.endEmitted) {
      state.ended = true;
      processNextTick(endReadableNT, state, stream);
    }
  }
  
  function endReadableNT(state, stream) {
    // Check that we didn't get one last unshift.
    if (!state.endEmitted && state.length === 0) {
      state.endEmitted = true;
      stream.readable = false;
      stream.emit('end');
    }
  }
  
  function forEach(xs, f) {
    for (var i = 0, l = xs.length; i < l; i++) {
      f(xs[i], i);
    }
  }
  
  function indexOf(xs, x) {
    for (var i = 0, l = xs.length; i < l; i++) {
      if (xs[i] === x) return i;
    }
    return -1;
  }
  }).call(this,require('_process'))
  },{"./_stream_duplex":59,"./internal/streams/BufferList":64,"./internal/streams/stream":65,"_process":103,"buffer":97,"buffer-shims":66,"core-util-is":67,"events":100,"inherits":38,"isarray":68,"process-nextick-args":69,"string_decoder/":70,"util":96}],62:[function(require,module,exports){
  // a transform stream is a readable/writable stream where you do
  // something with the data.  Sometimes it's called a "filter",
  // but that's not a great name for it, since that implies a thing where
  // some bits pass through, and others are simply ignored.  (That would
  // be a valid example of a transform, of course.)
  //
  // While the output is causally related to the input, it's not a
  // necessarily symmetric or synchronous transformation.  For example,
  // a zlib stream might take multiple plain-text writes(), and then
  // emit a single compressed chunk some time in the future.
  //
  // Here's how this works:
  //
  // The Transform stream has all the aspects of the readable and writable
  // stream classes.  When you write(chunk), that calls _write(chunk,cb)
  // internally, and returns false if there's a lot of pending writes
  // buffered up.  When you call read(), that calls _read(n) until
  // there's enough pending readable data buffered up.
  //
  // In a transform stream, the written data is placed in a buffer.  When
  // _read(n) is called, it transforms the queued up data, calling the
  // buffered _write cb's as it consumes chunks.  If consuming a single
  // written chunk would result in multiple output chunks, then the first
  // outputted bit calls the readcb, and subsequent chunks just go into
  // the read buffer, and will cause it to emit 'readable' if necessary.
  //
  // This way, back-pressure is actually determined by the reading side,
  // since _read has to be called to start processing a new chunk.  However,
  // a pathological inflate type of transform can cause excessive buffering
  // here.  For example, imagine a stream where every byte of input is
  // interpreted as an integer from 0-255, and then results in that many
  // bytes of output.  Writing the 4 bytes {ff,ff,ff,ff} would result in
  // 1kb of data being output.  In this case, you could write a very small
  // amount of input, and end up with a very large amount of output.  In
  // such a pathological inflating mechanism, there'd be no way to tell
  // the system to stop doing the transform.  A single 4MB write could
  // cause the system to run out of memory.
  //
  // However, even in such a pathological case, only a single written chunk
  // would be consumed, and then the rest would wait (un-transformed) until
  // the results of the previous transformed chunk were consumed.
  
  'use strict';
  
  module.exports = Transform;
  
  var Duplex = require('./_stream_duplex');
  
  /*<replacement>*/
  var util = require('core-util-is');
  util.inherits = require('inherits');
  /*</replacement>*/
  
  util.inherits(Transform, Duplex);
  
  function TransformState(stream) {
    this.afterTransform = function (er, data) {
      return afterTransform(stream, er, data);
    };
  
    this.needTransform = false;
    this.transforming = false;
    this.writecb = null;
    this.writechunk = null;
    this.writeencoding = null;
  }
  
  function afterTransform(stream, er, data) {
    var ts = stream._transformState;
    ts.transforming = false;
  
    var cb = ts.writecb;
  
    if (!cb) return stream.emit('error', new Error('no writecb in Transform class'));
  
    ts.writechunk = null;
    ts.writecb = null;
  
    if (data !== null && data !== undefined) stream.push(data);
  
    cb(er);
  
    var rs = stream._readableState;
    rs.reading = false;
    if (rs.needReadable || rs.length < rs.highWaterMark) {
      stream._read(rs.highWaterMark);
    }
  }
  
  function Transform(options) {
    if (!(this instanceof Transform)) return new Transform(options);
  
    Duplex.call(this, options);
  
    this._transformState = new TransformState(this);
  
    var stream = this;
  
    // start out asking for a readable event once data is transformed.
    this._readableState.needReadable = true;
  
    // we have implemented the _read method, and done the other things
    // that Readable wants before the first _read call, so unset the
    // sync guard flag.
    this._readableState.sync = false;
  
    if (options) {
      if (typeof options.transform === 'function') this._transform = options.transform;
  
      if (typeof options.flush === 'function') this._flush = options.flush;
    }
  
    // When the writable side finishes, then flush out anything remaining.
    this.once('prefinish', function () {
      if (typeof this._flush === 'function') this._flush(function (er, data) {
        done(stream, er, data);
      });else done(stream);
    });
  }
  
  Transform.prototype.push = function (chunk, encoding) {
    this._transformState.needTransform = false;
    return Duplex.prototype.push.call(this, chunk, encoding);
  };
  
  // This is the part where you do stuff!
  // override this function in implementation classes.
  // 'chunk' is an input chunk.
  //
  // Call `push(newChunk)` to pass along transformed output
  // to the readable side.  You may call 'push' zero or more times.
  //
  // Call `cb(err)` when you are done with this chunk.  If you pass
  // an error, then that'll put the hurt on the whole operation.  If you
  // never call cb(), then you'll never get another chunk.
  Transform.prototype._transform = function (chunk, encoding, cb) {
    throw new Error('_transform() is not implemented');
  };
  
  Transform.prototype._write = function (chunk, encoding, cb) {
    var ts = this._transformState;
    ts.writecb = cb;
    ts.writechunk = chunk;
    ts.writeencoding = encoding;
    if (!ts.transforming) {
      var rs = this._readableState;
      if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
    }
  };
  
  // Doesn't matter what the args are here.
  // _transform does all the work.
  // That we got here means that the readable side wants more data.
  Transform.prototype._read = function (n) {
    var ts = this._transformState;
  
    if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
      ts.transforming = true;
      this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
    } else {
      // mark that we need a transform, so that any data that comes in
      // will get processed, now that we've asked for it.
      ts.needTransform = true;
    }
  };
  
  function done(stream, er, data) {
    if (er) return stream.emit('error', er);
  
    if (data !== null && data !== undefined) stream.push(data);
  
    // if there's nothing in the write buffer, then that means
    // that nothing more will ever be provided
    var ws = stream._writableState;
    var ts = stream._transformState;
  
    if (ws.length) throw new Error('Calling transform done when ws.length != 0');
  
    if (ts.transforming) throw new Error('Calling transform done when still transforming');
  
    return stream.push(null);
  }
  },{"./_stream_duplex":59,"core-util-is":67,"inherits":38}],63:[function(require,module,exports){
  (function (process){
  // A bit simpler than readable streams.
  // Implement an async ._write(chunk, encoding, cb), and it'll handle all
  // the drain event emission and buffering.
  
  'use strict';
  
  module.exports = Writable;
  
  /*<replacement>*/
  var processNextTick = require('process-nextick-args');
  /*</replacement>*/
  
  /*<replacement>*/
  var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : processNextTick;
  /*</replacement>*/
  
  /*<replacement>*/
  var Duplex;
  /*</replacement>*/
  
  Writable.WritableState = WritableState;
  
  /*<replacement>*/
  var util = require('core-util-is');
  util.inherits = require('inherits');
  /*</replacement>*/
  
  /*<replacement>*/
  var internalUtil = {
    deprecate: require('util-deprecate')
  };
  /*</replacement>*/
  
  /*<replacement>*/
  var Stream = require('./internal/streams/stream');
  /*</replacement>*/
  
  var Buffer = require('buffer').Buffer;
  /*<replacement>*/
  var bufferShim = require('buffer-shims');
  /*</replacement>*/
  
  util.inherits(Writable, Stream);
  
  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 || require('./_stream_duplex');
  
    options = options || {};
  
    // object stream flag to indicate whether or not this stream
    // contains buffers or objects.
    this.objectMode = !!options.objectMode;
  
    if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode;
  
    // the point at which write() starts returning false
    // Note: 0 is a valid value, means that we always return false if
    // the entire buffer is not flushed immediately on write()
    var hwm = options.highWaterMark;
    var defaultHwm = this.objectMode ? 16 : 16 * 1024;
    this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm;
  
    // cast to ints.
    this.highWaterMark = ~~this.highWaterMark;
  
    // 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;
  
    // should we decode strings into buffers before passing to _write?
    // this is here so that some node-core streams can optimize string
    // handling at a lower level.
    var noDecode = options.decodeStrings === false;
    this.decodeStrings = !noDecode;
  
    // Crypto is kind of old and crusty.  Historically, its default string
    // encoding is 'binary' so we have to make this configurable.
    // Everything else in the universe uses 'utf8', though.
    this.defaultEncoding = options.defaultEncoding || 'utf8';
  
    // not an actual buffer we keep track of, but a measurement
    // of how much we're waiting to get pushed to some underlying
    // socket or file.
    this.length = 0;
  
    // a flag to see when we're in the middle of a write.
    this.writing = false;
  
    // when true all writes will be buffered until .uncork() call
    this.corked = 0;
  
    // a flag to be able to tell if the onwrite cb is called immediately,
    // or on a later tick.  We set this to true at first, because any
    // actions that shouldn't happen until "later" should generally also
    // not happen before the first write call.
    this.sync = true;
  
    // a flag to know if we're processing previously buffered items, which
    // may call the _write() callback in the same tick, so that we don't
    // end up in an overlapped onwrite situation.
    this.bufferProcessing = false;
  
    // the callback that's passed to _write(chunk,cb)
    this.onwrite = function (er) {
      onwrite(stream, er);
    };
  
    // the callback that the user supplies to write(chunk,encoding,cb)
    this.writecb = null;
  
    // the amount that is being written when _write is called.
    this.writelen = 0;
  
    this.bufferedRequest = null;
    this.lastBufferedRequest = null;
  
    // number of pending user-supplied write callbacks
    // this must be 0 before 'finish' can be emitted
    this.pendingcb = 0;
  
    // emit prefinish if the only thing we're waiting for is _write cbs
    // This is relevant for synchronous Transform streams
    this.prefinished = false;
  
    // True if the error was already emitted and should not be thrown again
    this.errorEmitted = false;
  
    // count buffered requests
    this.bufferedRequestCount = 0;
  
    // allocate the first CorkedRequest, there is always
    // one allocated and free to use, and we maintain at most two
    this.corkedRequestsFree = new CorkedRequest(this);
  }
  
  WritableState.prototype.getBuffer = function getBuffer() {
    var current = this.bufferedRequest;
    var out = [];
    while (current) {
      out.push(current);
      current = current.next;
    }
    return out;
  };
  
  (function () {
    try {
      Object.defineProperty(WritableState.prototype, 'buffer', {
        get: internalUtil.deprecate(function () {
          return this.getBuffer();
        }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.')
      });
    } 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 || require('./_stream_duplex');
  
    // Writable ctor is applied to Duplexes, too.
    // `realHasInstance` is necessary because using plain `instanceof`
    // would return false, as no `_writableState` property is attached.
  
    // Trying to use the custom `instanceof` for Writable here will also break the
    // Node.js LazyTransform implementation, which has a non-trivial getter for
    // `_writableState` that would lead to infinite recursion.
    if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) {
      return new Writable(options);
    }
  
    this._writableState = new WritableState(options, this);
  
    // legacy.
    this.writable = true;
  
    if (options) {
      if (typeof options.write === 'function') this._write = options.write;
  
      if (typeof options.writev === 'function') this._writev = options.writev;
    }
  
    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) {
        /*<replacement>*/
        asyncWrite(afterWrite, stream, state, finished, cb);
        /*</replacement>*/
      } 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;
      }
    };
  }
  }).call(this,require('_process'))
  },{"./_stream_duplex":59,"./internal/streams/stream":65,"_process":103,"buffer":97,"buffer-shims":66,"core-util-is":67,"inherits":38,"process-nextick-args":69,"util-deprecate":72}],64:[function(require,module,exports){
  'use strict';
  
  var Buffer = require('buffer').Buffer;
  /*<replacement>*/
  var bufferShim = require('buffer-shims');
  /*</replacement>*/
  
  module.exports = BufferList;
  
  function BufferList() {
    this.head = null;
    this.tail = null;
    this.length = 0;
  }
  
  BufferList.prototype.push = function (v) {
    var entry = { data: v, next: null };
    if (this.length > 0) this.tail.next = entry;else this.head = entry;
    this.tail = entry;
    ++this.length;
  };
  
  BufferList.prototype.unshift = function (v) {
    var entry = { data: v, next: this.head };
    if (this.length === 0) this.tail = entry;
    this.head = entry;
    ++this.length;
  };
  
  BufferList.prototype.shift = function () {
    if (this.length === 0) return;
    var ret = this.head.data;
    if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
    --this.length;
    return ret;
  };
  
  BufferList.prototype.clear = function () {
    this.head = this.tail = null;
    this.length = 0;
  };
  
  BufferList.prototype.join = function (s) {
    if (this.length === 0) return '';
    var p = this.head;
    var ret = '' + p.data;
    while (p = p.next) {
      ret += s + p.data;
    }return ret;
  };
  
  BufferList.prototype.concat = function (n) {
    if (this.length === 0) return bufferShim.alloc(0);
    if (this.length === 1) return this.head.data;
    var ret = bufferShim.allocUnsafe(n >>> 0);
    var p = this.head;
    var i = 0;
    while (p) {
      p.data.copy(ret, i);
      i += p.data.length;
      p = p.next;
    }
    return ret;
  };
  },{"buffer":97,"buffer-shims":66}],65:[function(require,module,exports){
  module.exports = require('events').EventEmitter;
  
  },{"events":100}],66:[function(require,module,exports){
  (function (global){
  'use strict';
  
  var buffer = require('buffer');
  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);
      }
    }
  
    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);
  }
  
  }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  },{"buffer":97}],67:[function(require,module,exports){
  (function (Buffer){
  // Copyright Joyent, Inc. and other Node contributors.
  //
  // Permission is hereby granted, free of charge, to any person obtaining a
  // copy of this software and associated documentation files (the
  // "Software"), to deal in the Software without restriction, including
  // without limitation the rights to use, copy, modify, merge, publish,
  // distribute, sublicense, and/or sell copies of the Software, and to permit
  // persons to whom the Software is furnished to do so, subject to the
  // following conditions:
  //
  // The above copyright notice and this permission notice shall be included
  // in all copies or substantial portions of the Software.
  //
  // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  // USE OR OTHER DEALINGS IN THE SOFTWARE.
  
  // NOTE: These type checking functions intentionally don't use `instanceof`
  // because it is fragile and can be easily faked with `Object.create()`.
  
  function isArray(arg) {
    if (Array.isArray) {
      return Array.isArray(arg);
    }
    return objectToString(arg) === '[object Array]';
  }
  exports.isArray = isArray;
  
  function isBoolean(arg) {
    return typeof arg === 'boolean';
  }
  exports.isBoolean = isBoolean;
  
  function isNull(arg) {
    return arg === null;
  }
  exports.isNull = isNull;
  
  function isNullOrUndefined(arg) {
    return arg == null;
  }
  exports.isNullOrUndefined = isNullOrUndefined;
  
  function isNumber(arg) {
    return typeof arg === 'number';
  }
  exports.isNumber = isNumber;
  
  function isString(arg) {
    return typeof arg === 'string';
  }
  exports.isString = isString;
  
  function isSymbol(arg) {
    return typeof arg === 'symbol';
  }
  exports.isSymbol = isSymbol;
  
  function isUndefined(arg) {
    return arg === void 0;
  }
  exports.isUndefined = isUndefined;
  
  function isRegExp(re) {
    return objectToString(re) === '[object RegExp]';
  }
  exports.isRegExp = isRegExp;
  
  function isObject(arg) {
    return typeof arg === 'object' && arg !== null;
  }
  exports.isObject = isObject;
  
  function isDate(d) {
    return objectToString(d) === '[object Date]';
  }
  exports.isDate = isDate;
  
  function isError(e) {
    return (objectToString(e) === '[object Error]' || e instanceof Error);
  }
  exports.isError = isError;
  
  function isFunction(arg) {
    return typeof arg === 'function';
  }
  exports.isFunction = isFunction;
  
  function isPrimitive(arg) {
    return arg === null ||
           typeof arg === 'boolean' ||
           typeof arg === 'number' ||
           typeof arg === 'string' ||
           typeof arg === 'symbol' ||  // ES6 symbol
           typeof arg === 'undefined';
  }
  exports.isPrimitive = isPrimitive;
  
  exports.isBuffer = Buffer.isBuffer;
  
  function objectToString(o) {
    return Object.prototype.toString.call(o);
  }
  
  }).call(this,{"isBuffer":require("../../../../../../../../../../../../../../../../../../usr/local/lib/node_modules/browserify/node_modules/insert-module-globals/node_modules/is-buffer/index.js")})
  },{"../../../../../../../../../../../../../../../../../../usr/local/lib/node_modules/browserify/node_modules/insert-module-globals/node_modules/is-buffer/index.js":102}],68:[function(require,module,exports){
  var toString = {}.toString;
  
  module.exports = Array.isArray || function (arr) {
    return toString.call(arr) == '[object Array]';
  };
  
  },{}],69:[function(require,module,exports){
  (function (process){
  'use strict';
  
  if (!process.version ||
      process.version.indexOf('v0.') === 0 ||
      process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) {
    module.exports = nextTick;
  } else {
    module.exports = process.nextTick;
  }
  
  function nextTick(fn, arg1, arg2, arg3) {
    if (typeof fn !== 'function') {
      throw new TypeError('"callback" argument must be a function');
    }
    var len = arguments.length;
    var args, i;
    switch (len) {
    case 0:
    case 1:
      return process.nextTick(fn);
    case 2:
      return process.nextTick(function afterTickOne() {
        fn.call(null, arg1);
      });
    case 3:
      return process.nextTick(function afterTickTwo() {
        fn.call(null, arg1, arg2);
      });
    case 4:
      return process.nextTick(function afterTickThree() {
        fn.call(null, arg1, arg2, arg3);
      });
    default:
      args = new Array(len - 1);
      i = 0;
      while (i < args.length) {
        args[i++] = arguments[i];
      }
      return process.nextTick(function afterTick() {
        fn.apply(null, args);
      });
    }
  }
  
  }).call(this,require('_process'))
  },{"_process":103}],70:[function(require,module,exports){
  'use strict';
  
  var Buffer = require('safe-buffer').Buffer;
  
  var isEncoding = Buffer.isEncoding || function (encoding) {
    encoding = '' + encoding;
    switch (encoding && encoding.toLowerCase()) {
      case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw':
        return true;
      default:
        return false;
    }
  };
  
  function _normalizeEncoding(enc) {
    if (!enc) return 'utf8';
    var retried;
    while (true) {
      switch (enc) {
        case 'utf8':
        case 'utf-8':
          return 'utf8';
        case 'ucs2':
        case 'ucs-2':
        case 'utf16le':
        case 'utf-16le':
          return 'utf16le';
        case 'latin1':
        case 'binary':
          return 'latin1';
        case 'base64':
        case 'ascii':
        case 'hex':
          return enc;
        default:
          if (retried) return; // undefined
          enc = ('' + enc).toLowerCase();
          retried = true;
      }
    }
  };
  
  // Do not cache `Buffer.isEncoding` when checking encoding names as some
  // modules monkey-patch it to support additional encodings
  function normalizeEncoding(enc) {
    var nenc = _normalizeEncoding(enc);
    if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);
    return nenc || enc;
  }
  
  // StringDecoder provides an interface for efficiently splitting a series of
  // buffers into a series of JS strings without breaking apart multi-byte
  // characters.
  exports.StringDecoder = StringDecoder;
  function StringDecoder(encoding) {
    this.encoding = normalizeEncoding(encoding);
    var nb;
    switch (this.encoding) {
      case 'utf16le':
        this.text = utf16Text;
        this.end = utf16End;
        nb = 4;
        break;
      case 'utf8':
        this.fillLast = utf8FillLast;
        nb = 4;
        break;
      case 'base64':
        this.text = base64Text;
        this.end = base64End;
        nb = 3;
        break;
      default:
        this.write = simpleWrite;
        this.end = simpleEnd;
        return;
    }
    this.lastNeed = 0;
    this.lastTotal = 0;
    this.lastChar = Buffer.allocUnsafe(nb);
  }
  
  StringDecoder.prototype.write = function (buf) {
    if (buf.length === 0) return '';
    var r;
    var i;
    if (this.lastNeed) {
      r = this.fillLast(buf);
      if (r === undefined) return '';
      i = this.lastNeed;
      this.lastNeed = 0;
    } else {
      i = 0;
    }
    if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);
    return r || '';
  };
  
  StringDecoder.prototype.end = utf8End;
  
  // Returns only complete characters in a Buffer
  StringDecoder.prototype.text = utf8Text;
  
  // Attempts to complete a partial non-UTF-8 character using bytes from a Buffer
  StringDecoder.prototype.fillLast = function (buf) {
    if (this.lastNeed <= buf.length) {
      buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);
      return this.lastChar.toString(this.encoding, 0, this.lastTotal);
    }
    buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);
    this.lastNeed -= buf.length;
  };
  
  // Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a
  // continuation byte.
  function utf8CheckByte(byte) {
    if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4;
    return -1;
  }
  
  // Checks at most 3 bytes at the end of a Buffer in order to detect an
  // incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)
  // needed to complete the UTF-8 character (if applicable) are returned.
  function utf8CheckIncomplete(self, buf, i) {
    var j = buf.length - 1;
    if (j < i) return 0;
    var nb = utf8CheckByte(buf[j]);
    if (nb >= 0) {
      if (nb > 0) self.lastNeed = nb - 1;
      return nb;
    }
    if (--j < i) return 0;
    nb = utf8CheckByte(buf[j]);
    if (nb >= 0) {
      if (nb > 0) self.lastNeed = nb - 2;
      return nb;
    }
    if (--j < i) return 0;
    nb = utf8CheckByte(buf[j]);
    if (nb >= 0) {
      if (nb > 0) {
        if (nb === 2) nb = 0;else self.lastNeed = nb - 3;
      }
      return nb;
    }
    return 0;
  }
  
  // Validates as many continuation bytes for a multi-byte UTF-8 character as
  // needed or are available. If we see a non-continuation byte where we expect
  // one, we "replace" the validated continuation bytes we've seen so far with
  // UTF-8 replacement characters ('\ufffd'), to match v8's UTF-8 decoding
  // behavior. The continuation byte check is included three times in the case
  // where all of the continuation bytes for a character exist in the same buffer.
  // It is also done this way as a slight performance increase instead of using a
  // loop.
  function utf8CheckExtraBytes(self, buf, p) {
    if ((buf[0] & 0xC0) !== 0x80) {
      self.lastNeed = 0;
      return '\ufffd'.repeat(p);
    }
    if (self.lastNeed > 1 && buf.length > 1) {
      if ((buf[1] & 0xC0) !== 0x80) {
        self.lastNeed = 1;
        return '\ufffd'.repeat(p + 1);
      }
      if (self.lastNeed > 2 && buf.length > 2) {
        if ((buf[2] & 0xC0) !== 0x80) {
          self.lastNeed = 2;
          return '\ufffd'.repeat(p + 2);
        }
      }
    }
  }
  
  // Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.
  function utf8FillLast(buf) {
    var p = this.lastTotal - this.lastNeed;
    var r = utf8CheckExtraBytes(this, buf, p);
    if (r !== undefined) return r;
    if (this.lastNeed <= buf.length) {
      buf.copy(this.lastChar, p, 0, this.lastNeed);
      return this.lastChar.toString(this.encoding, 0, this.lastTotal);
    }
    buf.copy(this.lastChar, p, 0, buf.length);
    this.lastNeed -= buf.length;
  }
  
  // Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a
  // partial character, the character's bytes are buffered until the required
  // number of bytes are available.
  function utf8Text(buf, i) {
    var total = utf8CheckIncomplete(this, buf, i);
    if (!this.lastNeed) return buf.toString('utf8', i);
    this.lastTotal = total;
    var end = buf.length - (total - this.lastNeed);
    buf.copy(this.lastChar, 0, end);
    return buf.toString('utf8', i, end);
  }
  
  // For UTF-8, a replacement character for each buffered byte of a (partial)
  // character needs to be added to the output.
  function utf8End(buf) {
    var r = buf && buf.length ? this.write(buf) : '';
    if (this.lastNeed) return r + '\ufffd'.repeat(this.lastTotal - this.lastNeed);
    return r;
  }
  
  // UTF-16LE typically needs two bytes per character, but even if we have an even
  // number of bytes available, we need to check if we end on a leading/high
  // surrogate. In that case, we need to wait for the next two bytes in order to
  // decode the last character properly.
  function utf16Text(buf, i) {
    if ((buf.length - i) % 2 === 0) {
      var r = buf.toString('utf16le', i);
      if (r) {
        var c = r.charCodeAt(r.length - 1);
        if (c >= 0xD800 && c <= 0xDBFF) {
          this.lastNeed = 2;
          this.lastTotal = 4;
          this.lastChar[0] = buf[buf.length - 2];
          this.lastChar[1] = buf[buf.length - 1];
          return r.slice(0, -1);
        }
      }
      return r;
    }
    this.lastNeed = 1;
    this.lastTotal = 2;
    this.lastChar[0] = buf[buf.length - 1];
    return buf.toString('utf16le', i, buf.length - 1);
  }
  
  // For UTF-16LE we do not explicitly append special replacement characters if we
  // end on a partial character, we simply let v8 handle that.
  function utf16End(buf) {
    var r = buf && buf.length ? this.write(buf) : '';
    if (this.lastNeed) {
      var end = this.lastTotal - this.lastNeed;
      return r + this.lastChar.toString('utf16le', 0, end);
    }
    return r;
  }
  
  function base64Text(buf, i) {
    var n = (buf.length - i) % 3;
    if (n === 0) return buf.toString('base64', i);
    this.lastNeed = 3 - n;
    this.lastTotal = 3;
    if (n === 1) {
      this.lastChar[0] = buf[buf.length - 1];
    } else {
      this.lastChar[0] = buf[buf.length - 2];
      this.lastChar[1] = buf[buf.length - 1];
    }
    return buf.toString('base64', i, buf.length - n);
  }
  
  function base64End(buf) {
    var r = buf && buf.length ? this.write(buf) : '';
    if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);
    return r;
  }
  
  // Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)
  function simpleWrite(buf) {
    return buf.toString(this.encoding);
  }
  
  function simpleEnd(buf) {
    return buf && buf.length ? this.write(buf) : '';
  }
  },{"safe-buffer":71}],71:[function(require,module,exports){
  module.exports = require('buffer')
  
  },{"buffer":97}],72:[function(require,module,exports){
  (function (global){
  
  /**
   * Module exports.
   */
  
  module.exports = deprecate;
  
  /**
   * Mark that a method should not be used.
   * Returns a modified function which warns once by default.
   *
   * If `localStorage.noDeprecation = true` is set, then it is a no-op.
   *
   * If `localStorage.throwDeprecation = true` is set, then deprecated functions
   * will throw an Error when invoked.
   *
   * If `localStorage.traceDeprecation = true` is set, then deprecated functions
   * will invoke `console.trace()` instead of `console.error()`.
   *
   * @param {Function} fn - the function to deprecate
   * @param {String} msg - the string to print to the console when `fn` is invoked
   * @returns {Function} a new "deprecated" version of `fn`
   * @api public
   */
  
  function deprecate (fn, msg) {
    if (config('noDeprecation')) {
      return fn;
    }
  
    var warned = false;
    function deprecated() {
      if (!warned) {
        if (config('throwDeprecation')) {
          throw new Error(msg);
        } else if (config('traceDeprecation')) {
          console.trace(msg);
        } else {
          console.warn(msg);
        }
        warned = true;
      }
      return fn.apply(this, arguments);
    }
  
    return deprecated;
  }
  
  /**
   * Checks `localStorage` for boolean values for the given `name`.
   *
   * @param {String} name
   * @returns {Boolean}
   * @api private
   */
  
  function config (name) {
    // accessing global.localStorage can trigger a DOMException in sandboxed iframes
    try {
      if (!global.localStorage) return false;
    } catch (_) {
      return false;
    }
    var val = global.localStorage[name];
    if (null == val) return false;
    return String(val).toLowerCase() === 'true';
  }
  
  }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  },{}],73:[function(require,module,exports){
  exports = module.exports = require('./lib/_stream_readable.js');
  exports.Stream = exports;
  exports.Readable = exports;
  exports.Writable = require('./lib/_stream_writable.js');
  exports.Duplex = require('./lib/_stream_duplex.js');
  exports.Transform = require('./lib/_stream_transform.js');
  exports.PassThrough = require('./lib/_stream_passthrough.js');
  
  },{"./lib/_stream_duplex.js":59,"./lib/_stream_passthrough.js":60,"./lib/_stream_readable.js":61,"./lib/_stream_transform.js":62,"./lib/_stream_writable.js":63}],74:[function(require,module,exports){
  module.exports = shift
  
  function shift (stream) {
    var rs = stream._readableState
    if (!rs) return null
    return rs.objectMode ? stream.read() : stream.read(getStateLength(rs))
  }
  
  function getStateLength (state) {
    if (state.buffer.length) {
      // Since node 6.3.0 state.buffer is a BufferList not an array
      if (state.buffer.head) {
        return state.buffer.head.data.length
      }
  
      return state.buffer[0].length
    }
  
    return state.length
  }
  
  },{}],75:[function(require,module,exports){
  arguments[4][59][0].apply(exports,arguments)
  },{"./_stream_readable":77,"./_stream_writable":79,"core-util-is":83,"dup":59,"inherits":38,"process-nextick-args":85}],76:[function(require,module,exports){
  arguments[4][60][0].apply(exports,arguments)
  },{"./_stream_transform":78,"core-util-is":83,"dup":60,"inherits":38}],77:[function(require,module,exports){
  arguments[4][61][0].apply(exports,arguments)
  },{"./_stream_duplex":75,"./internal/streams/BufferList":80,"./internal/streams/stream":81,"_process":103,"buffer":97,"buffer-shims":82,"core-util-is":83,"dup":61,"events":100,"inherits":38,"isarray":84,"process-nextick-args":85,"string_decoder/":86,"util":96}],78:[function(require,module,exports){
  arguments[4][62][0].apply(exports,arguments)
  },{"./_stream_duplex":75,"core-util-is":83,"dup":62,"inherits":38}],79:[function(require,module,exports){
  arguments[4][63][0].apply(exports,arguments)
  },{"./_stream_duplex":75,"./internal/streams/stream":81,"_process":103,"buffer":97,"buffer-shims":82,"core-util-is":83,"dup":63,"inherits":38,"process-nextick-args":85,"util-deprecate":88}],80:[function(require,module,exports){
  arguments[4][64][0].apply(exports,arguments)
  },{"buffer":97,"buffer-shims":82,"dup":64}],81:[function(require,module,exports){
  arguments[4][65][0].apply(exports,arguments)
  },{"dup":65,"events":100}],82:[function(require,module,exports){
  arguments[4][66][0].apply(exports,arguments)
  },{"buffer":97,"dup":66}],83:[function(require,module,exports){
  arguments[4][67][0].apply(exports,arguments)
  },{"../../../../../../../../../../../../../../../../../../usr/local/lib/node_modules/browserify/node_modules/insert-module-globals/node_modules/is-buffer/index.js":102,"dup":67}],84:[function(require,module,exports){
  arguments[4][68][0].apply(exports,arguments)
  },{"dup":68}],85:[function(require,module,exports){
  arguments[4][69][0].apply(exports,arguments)
  },{"_process":103,"dup":69}],86:[function(require,module,exports){
  arguments[4][70][0].apply(exports,arguments)
  },{"dup":70,"safe-buffer":87}],87:[function(require,module,exports){
  arguments[4][71][0].apply(exports,arguments)
  },{"buffer":97,"dup":71}],88:[function(require,module,exports){
  arguments[4][72][0].apply(exports,arguments)
  },{"dup":72}],89:[function(require,module,exports){
  arguments[4][73][0].apply(exports,arguments)
  },{"./lib/_stream_duplex.js":75,"./lib/_stream_passthrough.js":76,"./lib/_stream_readable.js":77,"./lib/_stream_transform.js":78,"./lib/_stream_writable.js":79,"dup":73}],90:[function(require,module,exports){
  module.exports = require('./readable').Transform
  
  },{"./readable":89}],91:[function(require,module,exports){
  (function (process){
  var Transform = require('readable-stream/transform')
    , inherits  = require('util').inherits
    , xtend     = require('xtend')
  
  function DestroyableTransform(opts) {
    Transform.call(this, opts)
    this._destroyed = false
  }
  
  inherits(DestroyableTransform, Transform)
  
  DestroyableTransform.prototype.destroy = function(err) {
    if (this._destroyed) return
    this._destroyed = true
    
    var self = this
    process.nextTick(function() {
      if (err)
        self.emit('error', err)
      self.emit('close')
    })
  }
  
  // a noop _transform function
  function noop (chunk, enc, callback) {
    callback(null, chunk)
  }
  
  
  // create a new export function, used by both the main export and
  // the .ctor export, contains common logic for dealing with arguments
  function through2 (construct) {
    return function (options, transform, flush) {
      if (typeof options == 'function') {
        flush     = transform
        transform = options
        options   = {}
      }
  
      if (typeof transform != 'function')
        transform = noop
  
      if (typeof flush != 'function')
        flush = null
  
      return construct(options, transform, flush)
    }
  }
  
  
  // main export, just make me a transform stream!
  module.exports = through2(function (options, transform, flush) {
    var t2 = new DestroyableTransform(options)
  
    t2._transform = transform
  
    if (flush)
      t2._flush = flush
  
    return t2
  })
  
  
  // make me a reusable prototype that I can `new`, or implicitly `new`
  // with a constructor call
  module.exports.ctor = through2(function (options, transform, flush) {
    function Through2 (override) {
      if (!(this instanceof Through2))
        return new Through2(override)
  
      this.options = xtend(options, override)
  
      DestroyableTransform.call(this, this.options)
    }
  
    inherits(Through2, DestroyableTransform)
  
    Through2.prototype._transform = transform
  
    if (flush)
      Through2.prototype._flush = flush
  
    return Through2
  })
  
  
  module.exports.obj = through2(function (options, transform, flush) {
    var t2 = new DestroyableTransform(xtend({ objectMode: true, highWaterMark: 16 }, options))
  
    t2._transform = transform
  
    if (flush)
      t2._flush = flush
  
    return t2
  })
  
  }).call(this,require('_process'))
  },{"_process":103,"readable-stream/transform":90,"util":132,"xtend":94}],92:[function(require,module,exports){
  
  /**
   * Module dependencies.
   */
  
  var global = (function() { return this; })();
  
  /**
   * WebSocket constructor.
   */
  
  var WebSocket = global.WebSocket || global.MozWebSocket;
  
  /**
   * Module exports.
   */
  
  module.exports = WebSocket ? ws : null;
  
  /**
   * WebSocket constructor.
   *
   * The third `opts` options object gets ignored in web browsers, since it's
   * non-standard, and throws a TypeError if passed to the constructor.
   * See: https://github.com/einaros/ws/issues/227
   *
   * @param {String} uri
   * @param {Array} protocols (optional)
   * @param {Object) opts (optional)
   * @api public
   */
  
  function ws(uri, protocols, opts) {
    var instance;
    if (protocols) {
      instance = new WebSocket(uri, protocols);
    } else {
      instance = new WebSocket(uri);
    }
    return instance;
  }
  
  if (WebSocket) ws.prototype = WebSocket.prototype;
  
  },{}],93:[function(require,module,exports){
  (function (process,Buffer){
  var through = require('through2')
  var duplexify = require('duplexify')
  var WS = require('ws')
  
  module.exports = WebSocketStream
  
  function WebSocketStream(target, protocols, options) {
    var stream, socket
    var socketWrite = process.title === 'browser' ? socketWriteBrowser : socketWriteNode
    var proxy = through.obj(socketWrite, socketEnd)
  
    if (protocols && !Array.isArray(protocols) && 'object' === typeof protocols) {
      // accept the "options" Object as the 2nd argument
      options = protocols
      protocols = null
    }
  
    if (!options) options = {}
  
    // browser only: sets the maximum socket buffer size before throttling
    var bufferSize = options.browserBufferSize || 1024 * 512
    // browser only: how long to wait when throttling
    var bufferTimeout = options.browserBufferTimeout || 1000
  
    // use existing WebSocket object that was passed in
    if (typeof target === 'object') {
      socket = target
    // otherwise make a new one
    } else {
      socket = new WS(target, protocols, options)
      socket.binaryType = 'arraybuffer'
    }
  
    // was already open when passed in
    if (socket.readyState === 1) {
      stream = proxy
    } else {
      stream = duplexify.obj()
      socket.addEventListener("open", onready)
    }
  
    stream.socket = socket
  
    socket.addEventListener("close", onclose)
    socket.addEventListener("error", onerror)
    socket.addEventListener("message", onmessage)
  
    proxy.on('close', destroy)
  
    function socketWriteNode(chunk, enc, next) {
      socket.send(chunk, next)
    }
  
    function socketWriteBrowser(chunk, enc, next) {
      if (socket.bufferedAmount > bufferSize) {
        setTimeout(socketWriteBrowser, bufferTimeout, chunk, enc, next)
        return
      }
  
      try {
        socket.send(chunk)
      } catch(err) {
        return next(err)
      }
  
      next()
    }
  
    function socketEnd(done) {
      socket.close()
      done()
    }
  
    function onready() {
      stream.setReadable(proxy)
      stream.setWritable(proxy)
      stream.emit('connect')
    }
  
    function onclose() {
      stream.end();
      stream.destroy()
    }
  
    function onerror(err) {
      stream.destroy(err)
    }
  
    function onmessage(event) {
      var data = event.data
      if (data instanceof ArrayBuffer) data = new Buffer(new Uint8Array(data))
      else data = new Buffer(data)
      proxy.push(data)
    }
  
    function destroy() {
      socket.close()
    }
  
    return stream
  }
  
  }).call(this,require('_process'),require("buffer").Buffer)
  },{"_process":103,"buffer":97,"duplexify":55,"through2":91,"ws":92}],94:[function(require,module,exports){
  module.exports = extend
  
  var hasOwnProperty = Object.prototype.hasOwnProperty;
  
  function extend() {
      var target = {}
  
      for (var i = 0; i < arguments.length; i++) {
          var source = arguments[i]
  
          for (var key in source) {
              if (hasOwnProperty.call(source, key)) {
                  target[key] = source[key]
              }
          }
      }
  
      return target
  }
  
  },{}],95:[function(require,module,exports){
  
  },{}],96:[function(require,module,exports){
  arguments[4][95][0].apply(exports,arguments)
  },{"dup":95}],97:[function(require,module,exports){
  /*!
   * The buffer module from node.js, for the browser.
   *
   * @author   Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
   * @license  MIT
   */
  /* eslint-disable no-proto */
  
  'use strict'
  
  var base64 = require('base64-js')
  var ieee754 = require('ieee754')
  
  exports.Buffer = Buffer
  exports.SlowBuffer = SlowBuffer
  exports.INSPECT_MAX_BYTES = 50
  
  var K_MAX_LENGTH = 0x7fffffff
  exports.kMaxLength = K_MAX_LENGTH
  
  /**
   * If `Buffer.TYPED_ARRAY_SUPPORT`:
   *   === true    Use Uint8Array implementation (fastest)
   *   === false   Print warning and recommend using `buffer` v4.x which has an Object
   *               implementation (most compatible, even IE6)
   *
   * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
   * Opera 11.6+, iOS 4.2+.
   *
   * We report that the browser does not support typed arrays if the are not subclassable
   * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
   * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
   * for __proto__ and has a buggy typed array implementation.
   */
  Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport()
  
  if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&
      typeof console.error === 'function') {
    console.error(
      'This browser lacks typed array (Uint8Array) support which is required by ' +
      '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'
    )
  }
  
  function typedArraySupport () {
    // Can typed array instances can be augmented?
    try {
      var arr = new Uint8Array(1)
      arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }}
      return arr.foo() === 42
    } catch (e) {
      return false
    }
  }
  
  function createBuffer (length) {
    if (length > K_MAX_LENGTH) {
      throw new RangeError('Invalid typed array length')
    }
    // Return an augmented `Uint8Array` instance
    var buf = new Uint8Array(length)
    buf.__proto__ = Buffer.prototype
    return buf
  }
  
  /**
   * The Buffer constructor returns instances of `Uint8Array` that have their
   * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
   * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
   * and the `Uint8Array` methods. Square bracket notation works as expected -- it
   * returns a single octet.
   *
   * The `Uint8Array` prototype remains unmodified.
   */
  
  function Buffer (arg, encodingOrOffset, length) {
    // Common case.
    if (typeof arg === 'number') {
      if (typeof encodingOrOffset === 'string') {
        throw new Error(
          'If encoding is specified then the first argument must be a string'
        )
      }
      return allocUnsafe(arg)
    }
    return from(arg, encodingOrOffset, length)
  }
  
  // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
  if (typeof Symbol !== 'undefined' && Symbol.species &&
      Buffer[Symbol.species] === Buffer) {
    Object.defineProperty(Buffer, Symbol.species, {
      value: null,
      configurable: true,
      enumerable: false,
      writable: false
    })
  }
  
  Buffer.poolSize = 8192 // not used by this implementation
  
  function from (value, encodingOrOffset, length) {
    if (typeof value === 'number') {
      throw new TypeError('"value" argument must not be a number')
    }
  
    if (value instanceof ArrayBuffer) {
      return fromArrayBuffer(value, encodingOrOffset, length)
    }
  
    if (typeof value === 'string') {
      return fromString(value, encodingOrOffset)
    }
  
    return fromObject(value)
  }
  
  /**
   * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
   * if value is a number.
   * Buffer.from(str[, encoding])
   * Buffer.from(array)
   * Buffer.from(buffer)
   * Buffer.from(arrayBuffer[, byteOffset[, length]])
   **/
  Buffer.from = function (value, encodingOrOffset, length) {
    return from(value, encodingOrOffset, length)
  }
  
  // Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
  // https://github.com/feross/buffer/pull/148
  Buffer.prototype.__proto__ = Uint8Array.prototype
  Buffer.__proto__ = Uint8Array
  
  function assertSize (size) {
    if (typeof size !== 'number') {
      throw new TypeError('"size" argument must be a number')
    } else if (size < 0) {
      throw new RangeError('"size" argument must not be negative')
    }
  }
  
  function alloc (size, fill, encoding) {
    assertSize(size)
    if (size <= 0) {
      return createBuffer(size)
    }
    if (fill !== undefined) {
      // Only pay attention to encoding if it's a string. This
      // prevents accidentally sending in a number that would
      // be interpretted as a start offset.
      return typeof encoding === 'string'
        ? createBuffer(size).fill(fill, encoding)
        : createBuffer(size).fill(fill)
    }
    return createBuffer(size)
  }
  
  /**
   * Creates a new filled Buffer instance.
   * alloc(size[, fill[, encoding]])
   **/
  Buffer.alloc = function (size, fill, encoding) {
    return alloc(size, fill, encoding)
  }
  
  function allocUnsafe (size) {
    assertSize(size)
    return createBuffer(size < 0 ? 0 : checked(size) | 0)
  }
  
  /**
   * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
   * */
  Buffer.allocUnsafe = function (size) {
    return allocUnsafe(size)
  }
  /**
   * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
   */
  Buffer.allocUnsafeSlow = function (size) {
    return allocUnsafe(size)
  }
  
  function fromString (string, encoding) {
    if (typeof encoding !== 'string' || encoding === '') {
      encoding = 'utf8'
    }
  
    if (!Buffer.isEncoding(encoding)) {
      throw new TypeError('"encoding" must be a valid string encoding')
    }
  
    var length = byteLength(string, encoding) | 0
    var buf = createBuffer(length)
  
    var actual = buf.write(string, encoding)
  
    if (actual !== length) {
      // Writing a hex string, for example, that contains invalid characters will
      // cause everything after the first invalid character to be ignored. (e.g.
      // 'abxxcd' will be treated as 'ab')
      buf = buf.slice(0, actual)
    }
  
    return buf
  }
  
  function fromArrayLike (array) {
    var length = array.length < 0 ? 0 : checked(array.length) | 0
    var buf = createBuffer(length)
    for (var i = 0; i < length; i += 1) {
      buf[i] = array[i] & 255
    }
    return buf
  }
  
  function fromArrayBuffer (array, byteOffset, length) {
    if (byteOffset < 0 || array.byteLength < byteOffset) {
      throw new RangeError('\'offset\' is out of bounds')
    }
  
    if (array.byteLength < byteOffset + (length || 0)) {
      throw new RangeError('\'length\' is out of bounds')
    }
  
    var buf
    if (byteOffset === undefined && length === undefined) {
      buf = new Uint8Array(array)
    } else if (length === undefined) {
      buf = new Uint8Array(array, byteOffset)
    } else {
      buf = new Uint8Array(array, byteOffset, length)
    }
  
    // Return an augmented `Uint8Array` instance
    buf.__proto__ = Buffer.prototype
    return buf
  }
  
  function fromObject (obj) {
    if (Buffer.isBuffer(obj)) {
      var len = checked(obj.length) | 0
      var buf = createBuffer(len)
  
      if (buf.length === 0) {
        return buf
      }
  
      obj.copy(buf, 0, 0, len)
      return buf
    }
  
    if (obj) {
      if (isArrayBufferView(obj) || 'length' in obj) {
        if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
          return createBuffer(0)
        }
        return fromArrayLike(obj)
      }
  
      if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
        return fromArrayLike(obj.data)
      }
    }
  
    throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')
  }
  
  function checked (length) {
    // Note: cannot use `length < K_MAX_LENGTH` here because that fails when
    // length is NaN (which is otherwise coerced to zero.)
    if (length >= K_MAX_LENGTH) {
      throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
                           'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')
    }
    return length | 0
  }
  
  function SlowBuffer (length) {
    if (+length != length) { // eslint-disable-line eqeqeq
      length = 0
    }
    return Buffer.alloc(+length)
  }
  
  Buffer.isBuffer = function isBuffer (b) {
    return b != null && b._isBuffer === true
  }
  
  Buffer.compare = function compare (a, b) {
    if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
      throw new TypeError('Arguments must be Buffers')
    }
  
    if (a === b) return 0
  
    var x = a.length
    var y = b.length
  
    for (var i = 0, len = Math.min(x, y); i < len; ++i) {
      if (a[i] !== b[i]) {
        x = a[i]
        y = b[i]
        break
      }
    }
  
    if (x < y) return -1
    if (y < x) return 1
    return 0
  }
  
  Buffer.isEncoding = function isEncoding (encoding) {
    switch (String(encoding).toLowerCase()) {
      case 'hex':
      case 'utf8':
      case 'utf-8':
      case 'ascii':
      case 'latin1':
      case 'binary':
      case 'base64':
      case 'ucs2':
      case 'ucs-2':
      case 'utf16le':
      case 'utf-16le':
        return true
      default:
        return false
    }
  }
  
  Buffer.concat = function concat (list, length) {
    if (!Array.isArray(list)) {
      throw new TypeError('"list" argument must be an Array of Buffers')
    }
  
    if (list.length === 0) {
      return Buffer.alloc(0)
    }
  
    var i
    if (length === undefined) {
      length = 0
      for (i = 0; i < list.length; ++i) {
        length += list[i].length
      }
    }
  
    var buffer = Buffer.allocUnsafe(length)
    var pos = 0
    for (i = 0; i < list.length; ++i) {
      var buf = list[i]
      if (!Buffer.isBuffer(buf)) {
        throw new TypeError('"list" argument must be an Array of Buffers')
      }
      buf.copy(buffer, pos)
      pos += buf.length
    }
    return buffer
  }
  
  function byteLength (string, encoding) {
    if (Buffer.isBuffer(string)) {
      return string.length
    }
    if (isArrayBufferView(string) || string instanceof ArrayBuffer) {
      return string.byteLength
    }
    if (typeof string !== 'string') {
      string = '' + string
    }
  
    var len = string.length
    if (len === 0) return 0
  
    // Use a for loop to avoid recursion
    var loweredCase = false
    for (;;) {
      switch (encoding) {
        case 'ascii':
        case 'latin1':
        case 'binary':
          return len
        case 'utf8':
        case 'utf-8':
        case undefined:
          return utf8ToBytes(string).length
        case 'ucs2':
        case 'ucs-2':
        case 'utf16le':
        case 'utf-16le':
          return len * 2
        case 'hex':
          return len >>> 1
        case 'base64':
          return base64ToBytes(string).length
        default:
          if (loweredCase) return utf8ToBytes(string).length // assume utf8
          encoding = ('' + encoding).toLowerCase()
          loweredCase = true
      }
    }
  }
  Buffer.byteLength = byteLength
  
  function slowToString (encoding, start, end) {
    var loweredCase = false
  
    // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
    // property of a typed array.
  
    // This behaves neither like String nor Uint8Array in that we set start/end
    // to their upper/lower bounds if the value passed is out of range.
    // undefined is handled specially as per ECMA-262 6th Edition,
    // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
    if (start === undefined || start < 0) {
      start = 0
    }
    // Return early if start > this.length. Done here to prevent potential uint32
    // coercion fail below.
    if (start > this.length) {
      return ''
    }
  
    if (end === undefined || end > this.length) {
      end = this.length
    }
  
    if (end <= 0) {
      return ''
    }
  
    // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
    end >>>= 0
    start >>>= 0
  
    if (end <= start) {
      return ''
    }
  
    if (!encoding) encoding = 'utf8'
  
    while (true) {
      switch (encoding) {
        case 'hex':
          return hexSlice(this, start, end)
  
        case 'utf8':
        case 'utf-8':
          return utf8Slice(this, start, end)
  
        case 'ascii':
          return asciiSlice(this, start, end)
  
        case 'latin1':
        case 'binary':
          return latin1Slice(this, start, end)
  
        case 'base64':
          return base64Slice(this, start, end)
  
        case 'ucs2':
        case 'ucs-2':
        case 'utf16le':
        case 'utf-16le':
          return utf16leSlice(this, start, end)
  
        default:
          if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
          encoding = (encoding + '').toLowerCase()
          loweredCase = true
      }
    }
  }
  
  // This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
  // to detect a Buffer instance. It's not possible to use `instanceof Buffer`
  // reliably in a browserify context because there could be multiple different
  // copies of the 'buffer' package in use. This method works even for Buffer
  // instances that were created from another copy of the `buffer` package.
  // See: https://github.com/feross/buffer/issues/154
  Buffer.prototype._isBuffer = true
  
  function swap (b, n, m) {
    var i = b[n]
    b[n] = b[m]
    b[m] = i
  }
  
  Buffer.prototype.swap16 = function swap16 () {
    var len = this.length
    if (len % 2 !== 0) {
      throw new RangeError('Buffer size must be a multiple of 16-bits')
    }
    for (var i = 0; i < len; i += 2) {
      swap(this, i, i + 1)
    }
    return this
  }
  
  Buffer.prototype.swap32 = function swap32 () {
    var len = this.length
    if (len % 4 !== 0) {
      throw new RangeError('Buffer size must be a multiple of 32-bits')
    }
    for (var i = 0; i < len; i += 4) {
      swap(this, i, i + 3)
      swap(this, i + 1, i + 2)
    }
    return this
  }
  
  Buffer.prototype.swap64 = function swap64 () {
    var len = this.length
    if (len % 8 !== 0) {
      throw new RangeError('Buffer size must be a multiple of 64-bits')
    }
    for (var i = 0; i < len; i += 8) {
      swap(this, i, i + 7)
      swap(this, i + 1, i + 6)
      swap(this, i + 2, i + 5)
      swap(this, i + 3, i + 4)
    }
    return this
  }
  
  Buffer.prototype.toString = function toString () {
    var length = this.length
    if (length === 0) return ''
    if (arguments.length === 0) return utf8Slice(this, 0, length)
    return slowToString.apply(this, arguments)
  }
  
  Buffer.prototype.equals = function equals (b) {
    if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
    if (this === b) return true
    return Buffer.compare(this, b) === 0
  }
  
  Buffer.prototype.inspect = function inspect () {
    var str = ''
    var max = exports.INSPECT_MAX_BYTES
    if (this.length > 0) {
      str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
      if (this.length > max) str += ' ... '
    }
    return '<Buffer ' + str + '>'
  }
  
  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)
  
    var thisCopy = this.slice(thisStart, thisEnd)
    var targetCopy = target.slice(start, end)
  
    for (var i = 0; i < len; ++i) {
      if (thisCopy[i] !== targetCopy[i]) {
        x = thisCopy[i]
        y = targetCopy[i]
        break
      }
    }
  
    if (x < y) return -1
    if (y < x) return 1
    return 0
  }
  
  // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
  // OR the last index of `val` in `buffer` at offset <= `byteOffset`.
  //
  // Arguments:
  // - buffer - a Buffer to search
  // - val - a string, Buffer, or number
  // - byteOffset - an index into `buffer`; will be clamped to an int32
  // - encoding - an optional encoding, relevant is val is a string
  // - dir - true for indexOf, false for lastIndexOf
  function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
    // Empty buffer means no match
    if (buffer.length === 0) return -1
  
    // Normalize byteOffset
    if (typeof byteOffset === 'string') {
      encoding = byteOffset
      byteOffset = 0
    } else if (byteOffset > 0x7fffffff) {
      byteOffset = 0x7fffffff
    } else if (byteOffset < -0x80000000) {
      byteOffset = -0x80000000
    }
    byteOffset = +byteOffset  // Coerce to Number.
    if (numberIsNaN(byteOffset)) {
      // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
      byteOffset = dir ? 0 : (buffer.length - 1)
    }
  
    // Normalize byteOffset: negative offsets start from the end of the buffer
    if (byteOffset < 0) byteOffset = buffer.length + byteOffset
    if (byteOffset >= buffer.length) {
      if (dir) return -1
      else byteOffset = buffer.length - 1
    } else if (byteOffset < 0) {
      if (dir) byteOffset = 0
      else return -1
    }
  
    // Normalize val
    if (typeof val === 'string') {
      val = Buffer.from(val, encoding)
    }
  
    // Finally, search either indexOf (if dir is true) or lastIndexOf
    if (Buffer.isBuffer(val)) {
      // Special case: looking for empty string/buffer always fails
      if (val.length === 0) {
        return -1
      }
      return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
    } else if (typeof val === 'number') {
      val = val & 0xFF // Search for a byte value [0-255]
      if (typeof Uint8Array.prototype.indexOf === 'function') {
        if (dir) {
          return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
        } else {
          return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
        }
      }
      return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
    }
  
    throw new TypeError('val must be string, number or Buffer')
  }
  
  function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
    var indexSize = 1
    var arrLength = arr.length
    var valLength = val.length
  
    if (encoding !== undefined) {
      encoding = String(encoding).toLowerCase()
      if (encoding === 'ucs2' || encoding === 'ucs-2' ||
          encoding === 'utf16le' || encoding === 'utf-16le') {
        if (arr.length < 2 || val.length < 2) {
          return -1
        }
        indexSize = 2
        arrLength /= 2
        valLength /= 2
        byteOffset /= 2
      }
    }
  
    function read (buf, i) {
      if (indexSize === 1) {
        return buf[i]
      } else {
        return buf.readUInt16BE(i * indexSize)
      }
    }
  
    var i
    if (dir) {
      var foundIndex = -1
      for (i = byteOffset; i < arrLength; i++) {
        if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
          if (foundIndex === -1) foundIndex = i
          if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
        } else {
          if (foundIndex !== -1) i -= i - foundIndex
          foundIndex = -1
        }
      }
    } else {
      if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
      for (i = byteOffset; i >= 0; i--) {
        var found = true
        for (var j = 0; j < valLength; j++) {
          if (read(arr, i + j) !== read(val, j)) {
            found = false
            break
          }
        }
        if (found) return i
      }
    }
  
    return -1
  }
  
  Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
    return this.indexOf(val, byteOffset, encoding) !== -1
  }
  
  Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
    return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
  }
  
  Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
    return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
  }
  
  function hexWrite (buf, string, offset, length) {
    offset = Number(offset) || 0
    var remaining = buf.length - offset
    if (!length) {
      length = remaining
    } else {
      length = Number(length)
      if (length > remaining) {
        length = remaining
      }
    }
  
    // must be an even number of digits
    var strLen = string.length
    if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')
  
    if (length > strLen / 2) {
      length = strLen / 2
    }
    for (var i = 0; i < length; ++i) {
      var parsed = parseInt(string.substr(i * 2, 2), 16)
      if (numberIsNaN(parsed)) return i
      buf[offset + i] = parsed
    }
    return i
  }
  
  function utf8Write (buf, string, offset, length) {
    return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
  }
  
  function asciiWrite (buf, string, offset, length) {
    return blitBuffer(asciiToBytes(string), buf, offset, length)
  }
  
  function latin1Write (buf, string, offset, length) {
    return asciiWrite(buf, string, offset, length)
  }
  
  function base64Write (buf, string, offset, length) {
    return blitBuffer(base64ToBytes(string), buf, offset, length)
  }
  
  function ucs2Write (buf, string, offset, length) {
    return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
  }
  
  Buffer.prototype.write = function write (string, offset, length, encoding) {
    // Buffer#write(string)
    if (offset === undefined) {
      encoding = 'utf8'
      length = this.length
      offset = 0
    // Buffer#write(string, encoding)
    } else if (length === undefined && typeof offset === 'string') {
      encoding = offset
      length = this.length
      offset = 0
    // Buffer#write(string, offset[, length][, encoding])
    } else if (isFinite(offset)) {
      offset = offset >>> 0
      if (isFinite(length)) {
        length = length >>> 0
        if (encoding === undefined) encoding = 'utf8'
      } else {
        encoding = length
        length = undefined
      }
    } else {
      throw new Error(
        'Buffer.write(string, encoding, offset[, length]) is no longer supported'
      )
    }
  
    var remaining = this.length - offset
    if (length === undefined || length > remaining) length = remaining
  
    if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
      throw new RangeError('Attempt to write outside buffer bounds')
    }
  
    if (!encoding) encoding = 'utf8'
  
    var loweredCase = false
    for (;;) {
      switch (encoding) {
        case 'hex':
          return hexWrite(this, string, offset, length)
  
        case 'utf8':
        case 'utf-8':
          return utf8Write(this, string, offset, length)
  
        case 'ascii':
          return asciiWrite(this, string, offset, length)
  
        case 'latin1':
        case 'binary':
          return latin1Write(this, string, offset, length)
  
        case 'base64':
          // Warning: maxLength not taken into account in base64Write
          return base64Write(this, string, offset, length)
  
        case 'ucs2':
        case 'ucs-2':
        case 'utf16le':
        case 'utf-16le':
          return ucs2Write(this, string, offset, length)
  
        default:
          if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
          encoding = ('' + encoding).toLowerCase()
          loweredCase = true
      }
    }
  }
  
  Buffer.prototype.toJSON = function toJSON () {
    return {
      type: 'Buffer',
      data: Array.prototype.slice.call(this._arr || this, 0)
    }
  }
  
  function base64Slice (buf, start, end) {
    if (start === 0 && end === buf.length) {
      return base64.fromByteArray(buf)
    } else {
      return base64.fromByteArray(buf.slice(start, end))
    }
  }
  
  function utf8Slice (buf, start, end) {
    end = Math.min(buf.length, end)
    var res = []
  
    var i = start
    while (i < end) {
      var firstByte = buf[i]
      var codePoint = null
      var bytesPerSequence = (firstByte > 0xEF) ? 4
        : (firstByte > 0xDF) ? 3
        : (firstByte > 0xBF) ? 2
        : 1
  
      if (i + bytesPerSequence <= end) {
        var secondByte, thirdByte, fourthByte, tempCodePoint
  
        switch (bytesPerSequence) {
          case 1:
            if (firstByte < 0x80) {
              codePoint = firstByte
            }
            break
          case 2:
            secondByte = buf[i + 1]
            if ((secondByte & 0xC0) === 0x80) {
              tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
              if (tempCodePoint > 0x7F) {
                codePoint = tempCodePoint
              }
            }
            break
          case 3:
            secondByte = buf[i + 1]
            thirdByte = buf[i + 2]
            if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
              tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
              if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
                codePoint = tempCodePoint
              }
            }
            break
          case 4:
            secondByte = buf[i + 1]
            thirdByte = buf[i + 2]
            fourthByte = buf[i + 3]
            if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
              tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
              if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
                codePoint = tempCodePoint
              }
            }
        }
      }
  
      if (codePoint === null) {
        // we did not generate a valid codePoint so insert a
        // replacement char (U+FFFD) and advance only 1 byte
        codePoint = 0xFFFD
        bytesPerSequence = 1
      } else if (codePoint > 0xFFFF) {
        // encode to utf16 (surrogate pair dance)
        codePoint -= 0x10000
        res.push(codePoint >>> 10 & 0x3FF | 0xD800)
        codePoint = 0xDC00 | codePoint & 0x3FF
      }
  
      res.push(codePoint)
      i += bytesPerSequence
    }
  
    return decodeCodePointsArray(res)
  }
  
  // Based on http://stackoverflow.com/a/22747272/680742, the browser with
  // the lowest limit is Chrome, with 0x10000 args.
  // We go 1 magnitude less, for safety
  var MAX_ARGUMENTS_LENGTH = 0x1000
  
  function decodeCodePointsArray (codePoints) {
    var len = codePoints.length
    if (len <= MAX_ARGUMENTS_LENGTH) {
      return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
    }
  
    // Decode in chunks to avoid "call stack size exceeded".
    var res = ''
    var i = 0
    while (i < len) {
      res += String.fromCharCode.apply(
        String,
        codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
      )
    }
    return res
  }
  
  function asciiSlice (buf, start, end) {
    var ret = ''
    end = Math.min(buf.length, end)
  
    for (var i = start; i < end; ++i) {
      ret += String.fromCharCode(buf[i] & 0x7F)
    }
    return ret
  }
  
  function latin1Slice (buf, start, end) {
    var ret = ''
    end = Math.min(buf.length, end)
  
    for (var i = start; i < end; ++i) {
      ret += String.fromCharCode(buf[i])
    }
    return ret
  }
  
  function hexSlice (buf, start, end) {
    var len = buf.length
  
    if (!start || start < 0) start = 0
    if (!end || end < 0 || end > len) end = len
  
    var out = ''
    for (var i = start; i < end; ++i) {
      out += toHex(buf[i])
    }
    return out
  }
  
  function utf16leSlice (buf, start, end) {
    var bytes = buf.slice(start, end)
    var res = ''
    for (var i = 0; i < bytes.length; i += 2) {
      res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))
    }
    return res
  }
  
  Buffer.prototype.slice = function slice (start, end) {
    var len = this.length
    start = ~~start
    end = end === undefined ? len : ~~end
  
    if (start < 0) {
      start += len
      if (start < 0) start = 0
    } else if (start > len) {
      start = len
    }
  
    if (end < 0) {
      end += len
      if (end < 0) end = 0
    } else if (end > len) {
      end = len
    }
  
    if (end < start) end = start
  
    var newBuf = this.subarray(start, end)
    // Return an augmented `Uint8Array` instance
    newBuf.__proto__ = Buffer.prototype
    return newBuf
  }
  
  /*
   * Need to make sure that buffer isn't trying to write out of bounds.
   */
  function checkOffset (offset, ext, length) {
    if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
    if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
  }
  
  Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
    offset = offset >>> 0
    byteLength = byteLength >>> 0
    if (!noAssert) checkOffset(offset, byteLength, this.length)
  
    var val = this[offset]
    var mul = 1
    var i = 0
    while (++i < byteLength && (mul *= 0x100)) {
      val += this[offset + i] * mul
    }
  
    return val
  }
  
  Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
    offset = offset >>> 0
    byteLength = byteLength >>> 0
    if (!noAssert) {
      checkOffset(offset, byteLength, this.length)
    }
  
    var val = this[offset + --byteLength]
    var mul = 1
    while (byteLength > 0 && (mul *= 0x100)) {
      val += this[offset + --byteLength] * mul
    }
  
    return val
  }
  
  Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
    offset = offset >>> 0
    if (!noAssert) checkOffset(offset, 1, this.length)
    return this[offset]
  }
  
  Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
    offset = offset >>> 0
    if (!noAssert) checkOffset(offset, 2, this.length)
    return this[offset] | (this[offset + 1] << 8)
  }
  
  Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
    offset = offset >>> 0
    if (!noAssert) checkOffset(offset, 2, this.length)
    return (this[offset] << 8) | this[offset + 1]
  }
  
  Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
    offset = offset >>> 0
    if (!noAssert) checkOffset(offset, 4, this.length)
  
    return ((this[offset]) |
        (this[offset + 1] << 8) |
        (this[offset + 2] << 16)) +
        (this[offset + 3] * 0x1000000)
  }
  
  Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
    offset = offset >>> 0
    if (!noAssert) checkOffset(offset, 4, this.length)
  
    return (this[offset] * 0x1000000) +
      ((this[offset + 1] << 16) |
      (this[offset + 2] << 8) |
      this[offset + 3])
  }
  
  Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
    offset = offset >>> 0
    byteLength = byteLength >>> 0
    if (!noAssert) checkOffset(offset, byteLength, this.length)
  
    var val = this[offset]
    var mul = 1
    var i = 0
    while (++i < byteLength && (mul *= 0x100)) {
      val += this[offset + i] * mul
    }
    mul *= 0x80
  
    if (val >= mul) val -= Math.pow(2, 8 * byteLength)
  
    return val
  }
  
  Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
    offset = offset >>> 0
    byteLength = byteLength >>> 0
    if (!noAssert) checkOffset(offset, byteLength, this.length)
  
    var i = byteLength
    var mul = 1
    var val = this[offset + --i]
    while (i > 0 && (mul *= 0x100)) {
      val += this[offset + --i] * mul
    }
    mul *= 0x80
  
    if (val >= mul) val -= Math.pow(2, 8 * byteLength)
  
    return val
  }
  
  Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
    offset = offset >>> 0
    if (!noAssert) checkOffset(offset, 1, this.length)
    if (!(this[offset] & 0x80)) return (this[offset])
    return ((0xff - this[offset] + 1) * -1)
  }
  
  Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
    offset = offset >>> 0
    if (!noAssert) checkOffset(offset, 2, this.length)
    var val = this[offset] | (this[offset + 1] << 8)
    return (val & 0x8000) ? val | 0xFFFF0000 : val
  }
  
  Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
    offset = offset >>> 0
    if (!noAssert) checkOffset(offset, 2, this.length)
    var val = this[offset + 1] | (this[offset] << 8)
    return (val & 0x8000) ? val | 0xFFFF0000 : val
  }
  
  Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
    offset = offset >>> 0
    if (!noAssert) checkOffset(offset, 4, this.length)
  
    return (this[offset]) |
      (this[offset + 1] << 8) |
      (this[offset + 2] << 16) |
      (this[offset + 3] << 24)
  }
  
  Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
    offset = offset >>> 0
    if (!noAssert) checkOffset(offset, 4, this.length)
  
    return (this[offset] << 24) |
      (this[offset + 1] << 16) |
      (this[offset + 2] << 8) |
      (this[offset + 3])
  }
  
  Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
    offset = offset >>> 0
    if (!noAssert) checkOffset(offset, 4, this.length)
    return ieee754.read(this, offset, true, 23, 4)
  }
  
  Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
    offset = offset >>> 0
    if (!noAssert) checkOffset(offset, 4, this.length)
    return ieee754.read(this, offset, false, 23, 4)
  }
  
  Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
    offset = offset >>> 0
    if (!noAssert) checkOffset(offset, 8, this.length)
    return ieee754.read(this, offset, true, 52, 8)
  }
  
  Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
    offset = offset >>> 0
    if (!noAssert) checkOffset(offset, 8, this.length)
    return ieee754.read(this, offset, false, 52, 8)
  }
  
  function checkInt (buf, value, offset, ext, max, min) {
    if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
    if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
    if (offset + ext > buf.length) throw new RangeError('Index out of range')
  }
  
  Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
    value = +value
    offset = offset >>> 0
    byteLength = byteLength >>> 0
    if (!noAssert) {
      var maxBytes = Math.pow(2, 8 * byteLength) - 1
      checkInt(this, value, offset, byteLength, maxBytes, 0)
    }
  
    var mul = 1
    var i = 0
    this[offset] = value & 0xFF
    while (++i < byteLength && (mul *= 0x100)) {
      this[offset + i] = (value / mul) & 0xFF
    }
  
    return offset + byteLength
  }
  
  Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
    value = +value
    offset = offset >>> 0
    byteLength = byteLength >>> 0
    if (!noAssert) {
      var maxBytes = Math.pow(2, 8 * byteLength) - 1
      checkInt(this, value, offset, byteLength, maxBytes, 0)
    }
  
    var i = byteLength - 1
    var mul = 1
    this[offset + i] = value & 0xFF
    while (--i >= 0 && (mul *= 0x100)) {
      this[offset + i] = (value / mul) & 0xFF
    }
  
    return offset + byteLength
  }
  
  Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
    value = +value
    offset = offset >>> 0
    if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
    this[offset] = (value & 0xff)
    return offset + 1
  }
  
  Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
    value = +value
    offset = offset >>> 0
    if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
    this[offset] = (value & 0xff)
    this[offset + 1] = (value >>> 8)
    return offset + 2
  }
  
  Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
    value = +value
    offset = offset >>> 0
    if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
    this[offset] = (value >>> 8)
    this[offset + 1] = (value & 0xff)
    return offset + 2
  }
  
  Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
    value = +value
    offset = offset >>> 0
    if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
    this[offset + 3] = (value >>> 24)
    this[offset + 2] = (value >>> 16)
    this[offset + 1] = (value >>> 8)
    this[offset] = (value & 0xff)
    return offset + 4
  }
  
  Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
    value = +value
    offset = offset >>> 0
    if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
    this[offset] = (value >>> 24)
    this[offset + 1] = (value >>> 16)
    this[offset + 2] = (value >>> 8)
    this[offset + 3] = (value & 0xff)
    return offset + 4
  }
  
  Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
    value = +value
    offset = offset >>> 0
    if (!noAssert) {
      var limit = Math.pow(2, (8 * byteLength) - 1)
  
      checkInt(this, value, offset, byteLength, limit - 1, -limit)
    }
  
    var i = 0
    var mul = 1
    var sub = 0
    this[offset] = value & 0xFF
    while (++i < byteLength && (mul *= 0x100)) {
      if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
        sub = 1
      }
      this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
    }
  
    return offset + byteLength
  }
  
  Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
    value = +value
    offset = offset >>> 0
    if (!noAssert) {
      var limit = Math.pow(2, (8 * byteLength) - 1)
  
      checkInt(this, value, offset, byteLength, limit - 1, -limit)
    }
  
    var i = byteLength - 1
    var mul = 1
    var sub = 0
    this[offset + i] = value & 0xFF
    while (--i >= 0 && (mul *= 0x100)) {
      if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
        sub = 1
      }
      this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
    }
  
    return offset + byteLength
  }
  
  Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
    value = +value
    offset = offset >>> 0
    if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
    if (value < 0) value = 0xff + value + 1
    this[offset] = (value & 0xff)
    return offset + 1
  }
  
  Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
    value = +value
    offset = offset >>> 0
    if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
    this[offset] = (value & 0xff)
    this[offset + 1] = (value >>> 8)
    return offset + 2
  }
  
  Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
    value = +value
    offset = offset >>> 0
    if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
    this[offset] = (value >>> 8)
    this[offset + 1] = (value & 0xff)
    return offset + 2
  }
  
  Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
    value = +value
    offset = offset >>> 0
    if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
    this[offset] = (value & 0xff)
    this[offset + 1] = (value >>> 8)
    this[offset + 2] = (value >>> 16)
    this[offset + 3] = (value >>> 24)
    return offset + 4
  }
  
  Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
    value = +value
    offset = offset >>> 0
    if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
    if (value < 0) value = 0xffffffff + value + 1
    this[offset] = (value >>> 24)
    this[offset + 1] = (value >>> 16)
    this[offset + 2] = (value >>> 8)
    this[offset + 3] = (value & 0xff)
    return offset + 4
  }
  
  function checkIEEE754 (buf, value, offset, ext, max, min) {
    if (offset + ext > buf.length) throw new RangeError('Index out of range')
    if (offset < 0) throw new RangeError('Index out of range')
  }
  
  function writeFloat (buf, value, offset, littleEndian, noAssert) {
    value = +value
    offset = offset >>> 0
    if (!noAssert) {
      checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
    }
    ieee754.write(buf, value, offset, littleEndian, 23, 4)
    return offset + 4
  }
  
  Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
    return writeFloat(this, value, offset, true, noAssert)
  }
  
  Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
    return writeFloat(this, value, offset, false, noAssert)
  }
  
  function writeDouble (buf, value, offset, littleEndian, noAssert) {
    value = +value
    offset = offset >>> 0
    if (!noAssert) {
      checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
    }
    ieee754.write(buf, value, offset, littleEndian, 52, 8)
    return offset + 8
  }
  
  Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
    return writeDouble(this, value, offset, true, noAssert)
  }
  
  Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
    return writeDouble(this, value, offset, false, noAssert)
  }
  
  // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
  Buffer.prototype.copy = function copy (target, targetStart, start, end) {
    if (!start) start = 0
    if (!end && end !== 0) end = this.length
    if (targetStart >= target.length) targetStart = target.length
    if (!targetStart) targetStart = 0
    if (end > 0 && end < start) end = start
  
    // Copy 0 bytes; we're done
    if (end === start) return 0
    if (target.length === 0 || this.length === 0) return 0
  
    // Fatal error conditions
    if (targetStart < 0) {
      throw new RangeError('targetStart out of bounds')
    }
    if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
    if (end < 0) throw new RangeError('sourceEnd out of bounds')
  
    // Are we oob?
    if (end > this.length) end = this.length
    if (target.length - targetStart < end - start) {
      end = target.length - targetStart + start
    }
  
    var len = end - start
    var i
  
    if (this === target && start < targetStart && targetStart < end) {
      // descending copy from end
      for (i = len - 1; i >= 0; --i) {
        target[i + targetStart] = this[i + start]
      }
    } else if (len < 1000) {
      // ascending copy from start
      for (i = 0; i < len; ++i) {
        target[i + targetStart] = this[i + start]
      }
    } else {
      Uint8Array.prototype.set.call(
        target,
        this.subarray(start, start + len),
        targetStart
      )
    }
  
    return len
  }
  
  // Usage:
  //    buffer.fill(number[, offset[, end]])
  //    buffer.fill(buffer[, offset[, end]])
  //    buffer.fill(string[, offset[, end]][, encoding])
  Buffer.prototype.fill = function fill (val, start, end, encoding) {
    // Handle string cases:
    if (typeof val === 'string') {
      if (typeof start === 'string') {
        encoding = start
        start = 0
        end = this.length
      } else if (typeof end === 'string') {
        encoding = end
        end = this.length
      }
      if (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
    }
  
    // Invalid ranges are not set to a default, so can range check early.
    if (start < 0 || this.length < start || this.length < end) {
      throw new RangeError('Out of range index')
    }
  
    if (end <= start) {
      return this
    }
  
    start = start >>> 0
    end = end === undefined ? this.length : end >>> 0
  
    if (!val) val = 0
  
    var i
    if (typeof val === 'number') {
      for (i = start; i < end; ++i) {
        this[i] = val
      }
    } else {
      var bytes = Buffer.isBuffer(val)
        ? val
        : new Buffer(val, encoding)
      var len = bytes.length
      for (i = 0; i < end - start; ++i) {
        this[i + start] = bytes[i % len]
      }
    }
  
    return this
  }
  
  // HELPER FUNCTIONS
  // ================
  
  var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g
  
  function base64clean (str) {
    // Node strips out invalid characters like \n and \t from the string, base64-js does not
    str = str.trim().replace(INVALID_BASE64_RE, '')
    // Node converts strings with length < 2 to ''
    if (str.length < 2) return ''
    // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
    while (str.length % 4 !== 0) {
      str = str + '='
    }
    return str
  }
  
  function toHex (n) {
    if (n < 16) return '0' + n.toString(16)
    return n.toString(16)
  }
  
  function utf8ToBytes (string, units) {
    units = units || Infinity
    var codePoint
    var length = string.length
    var leadSurrogate = null
    var bytes = []
  
    for (var i = 0; i < length; ++i) {
      codePoint = string.charCodeAt(i)
  
      // is surrogate component
      if (codePoint > 0xD7FF && codePoint < 0xE000) {
        // last char was a lead
        if (!leadSurrogate) {
          // no lead yet
          if (codePoint > 0xDBFF) {
            // unexpected trail
            if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
            continue
          } else if (i + 1 === length) {
            // unpaired lead
            if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
            continue
          }
  
          // valid lead
          leadSurrogate = codePoint
  
          continue
        }
  
        // 2 leads in a row
        if (codePoint < 0xDC00) {
          if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
          leadSurrogate = codePoint
          continue
        }
  
        // valid surrogate pair
        codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
      } else if (leadSurrogate) {
        // valid bmp char, but last char was a lead
        if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
      }
  
      leadSurrogate = null
  
      // encode utf8
      if (codePoint < 0x80) {
        if ((units -= 1) < 0) break
        bytes.push(codePoint)
      } else if (codePoint < 0x800) {
        if ((units -= 2) < 0) break
        bytes.push(
          codePoint >> 0x6 | 0xC0,
          codePoint & 0x3F | 0x80
        )
      } else if (codePoint < 0x10000) {
        if ((units -= 3) < 0) break
        bytes.push(
          codePoint >> 0xC | 0xE0,
          codePoint >> 0x6 & 0x3F | 0x80,
          codePoint & 0x3F | 0x80
        )
      } else if (codePoint < 0x110000) {
        if ((units -= 4) < 0) break
        bytes.push(
          codePoint >> 0x12 | 0xF0,
          codePoint >> 0xC & 0x3F | 0x80,
          codePoint >> 0x6 & 0x3F | 0x80,
          codePoint & 0x3F | 0x80
        )
      } else {
        throw new Error('Invalid code point')
      }
    }
  
    return bytes
  }
  
  function asciiToBytes (str) {
    var byteArray = []
    for (var i = 0; i < str.length; ++i) {
      // Node's code seems to be doing this and not & 0x7F..
      byteArray.push(str.charCodeAt(i) & 0xFF)
    }
    return byteArray
  }
  
  function utf16leToBytes (str, units) {
    var c, hi, lo
    var byteArray = []
    for (var i = 0; i < str.length; ++i) {
      if ((units -= 2) < 0) break
  
      c = str.charCodeAt(i)
      hi = c >> 8
      lo = c % 256
      byteArray.push(lo)
      byteArray.push(hi)
    }
  
    return byteArray
  }
  
  function base64ToBytes (str) {
    return base64.toByteArray(base64clean(str))
  }
  
  function blitBuffer (src, dst, offset, length) {
    for (var i = 0; i < length; ++i) {
      if ((i + offset >= dst.length) || (i >= src.length)) break
      dst[i + offset] = src[i]
    }
    return i
  }
  
  // Node 0.10 supports `ArrayBuffer` but lacks `ArrayBuffer.isView`
  function isArrayBufferView (obj) {
    return (typeof ArrayBuffer.isView === 'function') && ArrayBuffer.isView(obj)
  }
  
  function numberIsNaN (obj) {
    return obj !== obj // eslint-disable-line no-self-compare
  }
  
  },{"base64-js":98,"ieee754":99}],98:[function(require,module,exports){
  'use strict'
  
  exports.byteLength = byteLength
  exports.toByteArray = toByteArray
  exports.fromByteArray = fromByteArray
  
  var lookup = []
  var revLookup = []
  var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
  
  var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
  for (var i = 0, len = code.length; i < len; ++i) {
    lookup[i] = code[i]
    revLookup[code.charCodeAt(i)] = i
  }
  
  revLookup['-'.charCodeAt(0)] = 62
  revLookup['_'.charCodeAt(0)] = 63
  
  function placeHoldersCount (b64) {
    var len = b64.length
    if (len % 4 > 0) {
      throw new Error('Invalid string. Length must be a multiple of 4')
    }
  
    // the number of equal signs (place holders)
    // if there are two placeholders, than the two characters before it
    // represent one byte
    // if there is only one, then the three characters before it represent 2 bytes
    // this is just a cheap hack to not do indexOf twice
    return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0
  }
  
  function byteLength (b64) {
    // base64 is 4/3 + up to two characters of the original data
    return b64.length * 3 / 4 - placeHoldersCount(b64)
  }
  
  function toByteArray (b64) {
    var i, j, l, tmp, placeHolders, arr
    var len = b64.length
    placeHolders = placeHoldersCount(b64)
  
    arr = new Arr(len * 3 / 4 - placeHolders)
  
    // if there are placeholders, only get up to the last complete 4 chars
    l = placeHolders > 0 ? len - 4 : len
  
    var L = 0
  
    for (i = 0, 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('')
  }
  
  },{}],99:[function(require,module,exports){
  exports.read = function (buffer, offset, isLE, mLen, nBytes) {
    var e, m
    var eLen = nBytes * 8 - mLen - 1
    var eMax = (1 << eLen) - 1
    var eBias = eMax >> 1
    var nBits = -7
    var i = isLE ? (nBytes - 1) : 0
    var d = isLE ? -1 : 1
    var s = buffer[offset + i]
  
    i += d
  
    e = s & ((1 << (-nBits)) - 1)
    s >>= (-nBits)
    nBits += eLen
    for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
  
    m = e & ((1 << (-nBits)) - 1)
    e >>= (-nBits)
    nBits += mLen
    for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
  
    if (e === 0) {
      e = 1 - eBias
    } else if (e === eMax) {
      return m ? NaN : ((s ? -1 : 1) * Infinity)
    } else {
      m = m + Math.pow(2, mLen)
      e = e - eBias
    }
    return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
  }
  
  exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
    var e, m, c
    var eLen = nBytes * 8 - mLen - 1
    var eMax = (1 << eLen) - 1
    var eBias = eMax >> 1
    var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
    var i = isLE ? 0 : (nBytes - 1)
    var d = isLE ? 1 : -1
    var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
  
    value = Math.abs(value)
  
    if (isNaN(value) || value === Infinity) {
      m = isNaN(value) ? 1 : 0
      e = eMax
    } else {
      e = Math.floor(Math.log(value) / Math.LN2)
      if (value * (c = Math.pow(2, -e)) < 1) {
        e--
        c *= 2
      }
      if (e + eBias >= 1) {
        value += rt / c
      } else {
        value += rt * Math.pow(2, 1 - eBias)
      }
      if (value * c >= 2) {
        e++
        c /= 2
      }
  
      if (e + eBias >= eMax) {
        m = 0
        e = eMax
      } else if (e + eBias >= 1) {
        m = (value * c - 1) * Math.pow(2, mLen)
        e = e + eBias
      } else {
        m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
        e = 0
      }
    }
  
    for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
  
    e = (e << mLen) | m
    eLen += mLen
    for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
  
    buffer[offset + i - d] |= s * 128
  }
  
  },{}],100:[function(require,module,exports){
  // Copyright Joyent, Inc. and other Node contributors.
  //
  // Permission is hereby granted, free of charge, to any person obtaining a
  // copy of this software and associated documentation files (the
  // "Software"), to deal in the Software without restriction, including
  // without limitation the rights to use, copy, modify, merge, publish,
  // distribute, sublicense, and/or sell copies of the Software, and to permit
  // persons to whom the Software is furnished to do so, subject to the
  // following conditions:
  //
  // The above copyright notice and this permission notice shall be included
  // in all copies or substantial portions of the Software.
  //
  // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  // USE OR OTHER DEALINGS IN THE SOFTWARE.
  
  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
        } 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;
        }
      }
    }
  
    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
        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);
    }
  
    return true;
  };
  
  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];
  
    // 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 (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();
        }
      }
    }
  
    return this;
  };
  
  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;
  
    function g() {
      this.removeListener(type, g);
  
      if (!fired) {
        fired = true;
        listener.apply(this, arguments);
      }
    }
  
    g.listener = listener;
    this.on(type, g);
  
    return this;
  };
  
  // emits a 'removeListener' event iff the listener was removed
  EventEmitter.prototype.removeListener = function(type, listener) {
    var list, position, length, i;
  
    if (!isFunction(listener))
      throw TypeError('listener must be a function');
  
    if (!this._events || !this._events[type])
      return this;
  
    list = this._events[type];
    length = list.length;
    position = -1;
  
    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;
        }
      }
  
      if (position < 0)
        return this;
  
      if (list.length === 1) {
        list.length = 0;
        delete this._events[type];
      } else {
        list.splice(position, 1);
      }
  
      if (this._events.removeListener)
        this.emit('removeListener', type, listener);
    }
  
    return this;
  };
  
  EventEmitter.prototype.removeAllListeners = function(type) {
    var key, listeners;
  
    if (!this._events)
      return this;
  
    // 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;
    }
  
    // 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;
    }
  
    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;
  };
  
  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;
  };
  
  EventEmitter.prototype.listenerCount = function(type) {
    if (this._events) {
      var evlistener = this._events[type];
  
      if (isFunction(evlistener))
        return 1;
      else if (evlistener)
        return evlistener.length;
    }
    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;
  }
  
  },{}],101:[function(require,module,exports){
  arguments[4][38][0].apply(exports,arguments)
  },{"dup":38}],102:[function(require,module,exports){
  /*!
   * Determine if an object is a Buffer
   *
   * @author   Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
   * @license  MIT
   */
  
  // The _isBuffer check is for Safari 5-7 support, because it's missing
  // Object.prototype.constructor. Remove this eventually
  module.exports = function (obj) {
    return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer)
  }
  
  function isBuffer (obj) {
    return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
  }
  
  // For Node v0.10 support. Remove this eventually.
  function isSlowBuffer (obj) {
    return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0))
  }
  
  },{}],103:[function(require,module,exports){
  // shim for using process in browser
  var process = module.exports = {};
  
  // cached from whatever global is present so that test runners that stub it
  // don't break things.  But we need to wrap it in a try catch in case it is
  // wrapped in strict mode code which doesn't define any globals.  It's inside a
  // function because try/catches deoptimize in certain engines.
  
  var cachedSetTimeout;
  var cachedClearTimeout;
  
  function defaultSetTimout() {
      throw new Error('setTimeout has not been defined');
  }
  function defaultClearTimeout () {
      throw new Error('clearTimeout has not been defined');
  }
  (function () {
      try {
          if (typeof setTimeout === 'function') {
              cachedSetTimeout = setTimeout;
          } else {
              cachedSetTimeout = defaultSetTimout;
          }
      } catch (e) {
          cachedSetTimeout = defaultSetTimout;
      }
      try {
          if (typeof clearTimeout === 'function') {
              cachedClearTimeout = clearTimeout;
          } else {
              cachedClearTimeout = defaultClearTimeout;
          }
      } catch (e) {
          cachedClearTimeout = defaultClearTimeout;
      }
  } ())
  function runTimeout(fun) {
      if (cachedSetTimeout === setTimeout) {
          //normal enviroments in sane situations
          return setTimeout(fun, 0);
      }
      // if setTimeout wasn't available but was latter defined
      if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
          cachedSetTimeout = setTimeout;
          return setTimeout(fun, 0);
      }
      try {
          // when when somebody has screwed with setTimeout but no I.E. maddness
          return cachedSetTimeout(fun, 0);
      } catch(e){
          try {
              // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
              return cachedSetTimeout.call(null, fun, 0);
          } catch(e){
              // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
              return cachedSetTimeout.call(this, fun, 0);
          }
      }
  
  
  }
  function runClearTimeout(marker) {
      if (cachedClearTimeout === clearTimeout) {
          //normal enviroments in sane situations
          return clearTimeout(marker);
      }
      // if clearTimeout wasn't available but was latter defined
      if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
          cachedClearTimeout = clearTimeout;
          return clearTimeout(marker);
      }
      try {
          // when when somebody has screwed with setTimeout but no I.E. maddness
          return cachedClearTimeout(marker);
      } catch (e){
          try {
              // When we are in I.E. but the script has been evaled so I.E. doesn't  trust the global object when called normally
              return cachedClearTimeout.call(null, marker);
          } catch (e){
              // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
              // Some versions of I.E. have different rules for clearTimeout vs setTimeout
              return cachedClearTimeout.call(this, marker);
          }
      }
  
  
  
  }
  var queue = [];
  var draining = false;
  var currentQueue;
  var queueIndex = -1;
  
  function cleanUpNextTick() {
      if (!draining || !currentQueue) {
          return;
      }
      draining = false;
      if (currentQueue.length) {
          queue = currentQueue.concat(queue);
      } else {
          queueIndex = -1;
      }
      if (queue.length) {
          drainQueue();
      }
  }
  
  function drainQueue() {
      if (draining) {
          return;
      }
      var timeout = runTimeout(cleanUpNextTick);
      draining = true;
  
      var len = queue.length;
      while(len) {
          currentQueue = queue;
          queue = [];
          while (++queueIndex < len) {
              if (currentQueue) {
                  currentQueue[queueIndex].run();
              }
          }
          queueIndex = -1;
          len = queue.length;
      }
      currentQueue = null;
      draining = false;
      runClearTimeout(timeout);
  }
  
  process.nextTick = function (fun) {
      var args = new Array(arguments.length - 1);
      if (arguments.length > 1) {
          for (var i = 1; i < arguments.length; i++) {
              args[i - 1] = arguments[i];
          }
      }
      queue.push(new Item(fun, args));
      if (queue.length === 1 && !draining) {
          runTimeout(drainQueue);
      }
  };
  
  // v8 likes predictible objects
  function Item(fun, array) {
      this.fun = fun;
      this.array = array;
  }
  Item.prototype.run = function () {
      this.fun.apply(null, this.array);
  };
  process.title = 'browser';
  process.browser = true;
  process.env = {};
  process.argv = [];
  process.version = ''; // empty string to avoid regexp issues
  process.versions = {};
  
  function noop() {}
  
  process.on = noop;
  process.addListener = noop;
  process.once = noop;
  process.off = noop;
  process.removeListener = noop;
  process.removeAllListeners = noop;
  process.emit = noop;
  process.prependListener = noop;
  process.prependOnceListener = noop;
  
  process.listeners = function (name) { return [] }
  
  process.binding = function (name) {
      throw new Error('process.binding is not supported');
  };
  
  process.cwd = function () { return '/' };
  process.chdir = function (dir) {
      throw new Error('process.chdir is not supported');
  };
  process.umask = function() { return 0; };
  
  },{}],104:[function(require,module,exports){
  (function (global){
  /*! https://mths.be/punycode v1.4.1 by @mathias */
  ;(function(root) {
  
  	/** Detect free variables */
  	var freeExports = typeof exports == 'object' && exports &&
  		!exports.nodeType && exports;
  	var freeModule = typeof module == 'object' && module &&
  		!module.nodeType && module;
  	var freeGlobal = typeof global == 'object' && global;
  	if (
  		freeGlobal.global === freeGlobal ||
  		freeGlobal.window === freeGlobal ||
  		freeGlobal.self === freeGlobal
  	) {
  		root = freeGlobal;
  	}
  
  	/**
  	 * The `punycode` object.
  	 * @name punycode
  	 * @type Object
  	 */
  	var punycode,
  
  	/** Highest positive signed 32-bit float value */
  	maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1
  
  	/** Bootstring parameters */
  	base = 36,
  	tMin = 1,
  	tMax = 26,
  	skew = 38,
  	damp = 700,
  	initialBias = 72,
  	initialN = 128, // 0x80
  	delimiter = '-', // '\x2D'
  
  	/** Regular expressions */
  	regexPunycode = /^xn--/,
  	regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars
  	regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators
  
  	/** Error messages */
  	errors = {
  		'overflow': 'Overflow: input needs wider integers to process',
  		'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
  		'invalid-input': 'Invalid input'
  	},
  
  	/** Convenience shortcuts */
  	baseMinusTMin = base - tMin,
  	floor = Math.floor,
  	stringFromCharCode = String.fromCharCode,
  
  	/** Temporary variable */
  	key;
  
  	/*--------------------------------------------------------------------------*/
  
  	/**
  	 * A generic error utility function.
  	 * @private
  	 * @param {String} type The error type.
  	 * @returns {Error} Throws a `RangeError` with the applicable error message.
  	 */
  	function error(type) {
  		throw new RangeError(errors[type]);
  	}
  
  	/**
  	 * A generic `Array#map` utility function.
  	 * @private
  	 * @param {Array} array The array to iterate over.
  	 * @param {Function} callback The function that gets called for every array
  	 * item.
  	 * @returns {Array} A new array of values returned by the callback function.
  	 */
  	function map(array, fn) {
  		var length = array.length;
  		var result = [];
  		while (length--) {
  			result[length] = fn(array[length]);
  		}
  		return result;
  	}
  
  	/**
  	 * A simple `Array#map`-like wrapper to work with domain name strings or email
  	 * addresses.
  	 * @private
  	 * @param {String} domain The domain name or email address.
  	 * @param {Function} callback The function that gets called for every
  	 * character.
  	 * @returns {Array} A new string of characters returned by the callback
  	 * function.
  	 */
  	function mapDomain(string, fn) {
  		var parts = string.split('@');
  		var result = '';
  		if (parts.length > 1) {
  			// In email addresses, only the domain name should be punycoded. Leave
  			// the local part (i.e. everything up to `@`) intact.
  			result = parts[0] + '@';
  			string = parts[1];
  		}
  		// Avoid `split(regex)` for IE8 compatibility. See #17.
  		string = string.replace(regexSeparators, '\x2E');
  		var labels = string.split('.');
  		var encoded = map(labels, fn).join('.');
  		return result + encoded;
  	}
  
  	/**
  	 * Creates an array containing the numeric code points of each Unicode
  	 * character in the string. While JavaScript uses UCS-2 internally,
  	 * this function will convert a pair of surrogate halves (each of which
  	 * UCS-2 exposes as separate characters) into a single code point,
  	 * matching UTF-16.
  	 * @see `punycode.ucs2.encode`
  	 * @see <https://mathiasbynens.be/notes/javascript-encoding>
  	 * @memberOf punycode.ucs2
  	 * @name decode
  	 * @param {String} string The Unicode input string (UCS-2).
  	 * @returns {Array} The new array of code points.
  	 */
  	function ucs2decode(string) {
  		var output = [],
  		    counter = 0,
  		    length = string.length,
  		    value,
  		    extra;
  		while (counter < length) {
  			value = string.charCodeAt(counter++);
  			if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
  				// high surrogate, and there is a next character
  				extra = string.charCodeAt(counter++);
  				if ((extra & 0xFC00) == 0xDC00) { // low surrogate
  					output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
  				} else {
  					// unmatched surrogate; only append this code unit, in case the next
  					// code unit is the high surrogate of a surrogate pair
  					output.push(value);
  					counter--;
  				}
  			} else {
  				output.push(value);
  			}
  		}
  		return output;
  	}
  
  	/**
  	 * Creates a string based on an array of numeric code points.
  	 * @see `punycode.ucs2.decode`
  	 * @memberOf punycode.ucs2
  	 * @name encode
  	 * @param {Array} codePoints The array of numeric code points.
  	 * @returns {String} The new Unicode string (UCS-2).
  	 */
  	function ucs2encode(array) {
  		return map(array, function(value) {
  			var output = '';
  			if (value > 0xFFFF) {
  				value -= 0x10000;
  				output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
  				value = 0xDC00 | value & 0x3FF;
  			}
  			output += stringFromCharCode(value);
  			return output;
  		}).join('');
  	}
  
  	/**
  	 * Converts a basic code point into a digit/integer.
  	 * @see `digitToBasic()`
  	 * @private
  	 * @param {Number} codePoint The basic numeric code point value.
  	 * @returns {Number} The numeric value of a basic code point (for use in
  	 * representing integers) in the range `0` to `base - 1`, or `base` if
  	 * the code point does not represent a value.
  	 */
  	function basicToDigit(codePoint) {
  		if (codePoint - 48 < 10) {
  			return codePoint - 22;
  		}
  		if (codePoint - 65 < 26) {
  			return codePoint - 65;
  		}
  		if (codePoint - 97 < 26) {
  			return codePoint - 97;
  		}
  		return base;
  	}
  
  	/**
  	 * Converts a digit/integer into a basic code point.
  	 * @see `basicToDigit()`
  	 * @private
  	 * @param {Number} digit The numeric value of a basic code point.
  	 * @returns {Number} The basic code point whose value (when used for
  	 * representing integers) is `digit`, which needs to be in the range
  	 * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
  	 * used; else, the lowercase form is used. The behavior is undefined
  	 * if `flag` is non-zero and `digit` has no uppercase form.
  	 */
  	function digitToBasic(digit, flag) {
  		//  0..25 map to ASCII a..z or A..Z
  		// 26..35 map to ASCII 0..9
  		return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
  	}
  
  	/**
  	 * Bias adaptation function as per section 3.4 of RFC 3492.
  	 * https://tools.ietf.org/html/rfc3492#section-3.4
  	 * @private
  	 */
  	function adapt(delta, numPoints, firstTime) {
  		var k = 0;
  		delta = firstTime ? floor(delta / damp) : delta >> 1;
  		delta += floor(delta / numPoints);
  		for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {
  			delta = floor(delta / baseMinusTMin);
  		}
  		return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
  	}
  
  	/**
  	 * Converts a Punycode string of ASCII-only symbols to a string of Unicode
  	 * symbols.
  	 * @memberOf punycode
  	 * @param {String} input The Punycode string of ASCII-only symbols.
  	 * @returns {String} The resulting string of Unicode symbols.
  	 */
  	function decode(input) {
  		// Don't use UCS-2
  		var output = [],
  		    inputLength = input.length,
  		    out,
  		    i = 0,
  		    n = initialN,
  		    bias = initialBias,
  		    basic,
  		    j,
  		    index,
  		    oldi,
  		    w,
  		    k,
  		    digit,
  		    t,
  		    /** Cached calculation results */
  		    baseMinusT;
  
  		// Handle the basic code points: let `basic` be the number of input code
  		// points before the last delimiter, or `0` if there is none, then copy
  		// the first basic code points to the output.
  
  		basic = input.lastIndexOf(delimiter);
  		if (basic < 0) {
  			basic = 0;
  		}
  
  		for (j = 0; j < basic; ++j) {
  			// if it's not a basic code point
  			if (input.charCodeAt(j) >= 0x80) {
  				error('not-basic');
  			}
  			output.push(input.charCodeAt(j));
  		}
  
  		// Main decoding loop: start just after the last delimiter if any basic code
  		// points were copied; start at the beginning otherwise.
  
  		for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) {
  
  			// `index` is the index of the next character to be consumed.
  			// Decode a generalized variable-length integer into `delta`,
  			// which gets added to `i`. The overflow checking is easier
  			// if we increase `i` as we go, then subtract off its starting
  			// value at the end to obtain `delta`.
  			for (oldi = i, w = 1, k = base; /* no condition */; k += base) {
  
  				if (index >= inputLength) {
  					error('invalid-input');
  				}
  
  				digit = basicToDigit(input.charCodeAt(index++));
  
  				if (digit >= base || digit > floor((maxInt - i) / w)) {
  					error('overflow');
  				}
  
  				i += digit * w;
  				t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
  
  				if (digit < t) {
  					break;
  				}
  
  				baseMinusT = base - t;
  				if (w > floor(maxInt / baseMinusT)) {
  					error('overflow');
  				}
  
  				w *= baseMinusT;
  
  			}
  
  			out = output.length + 1;
  			bias = adapt(i - oldi, out, oldi == 0);
  
  			// `i` was supposed to wrap around from `out` to `0`,
  			// incrementing `n` each time, so we'll fix that now:
  			if (floor(i / out) > maxInt - n) {
  				error('overflow');
  			}
  
  			n += floor(i / out);
  			i %= out;
  
  			// Insert `n` at position `i` of the output
  			output.splice(i++, 0, n);
  
  		}
  
  		return ucs2encode(output);
  	}
  
  	/**
  	 * Converts a string of Unicode symbols (e.g. a domain name label) to a
  	 * Punycode string of ASCII-only symbols.
  	 * @memberOf punycode
  	 * @param {String} input The string of Unicode symbols.
  	 * @returns {String} The resulting Punycode string of ASCII-only symbols.
  	 */
  	function encode(input) {
  		var n,
  		    delta,
  		    handledCPCount,
  		    basicLength,
  		    bias,
  		    j,
  		    m,
  		    q,
  		    k,
  		    t,
  		    currentValue,
  		    output = [],
  		    /** `inputLength` will hold the number of code points in `input`. */
  		    inputLength,
  		    /** Cached calculation results */
  		    handledCPCountPlusOne,
  		    baseMinusT,
  		    qMinusT;
  
  		// Convert the input in UCS-2 to Unicode
  		input = ucs2decode(input);
  
  		// Cache the length
  		inputLength = input.length;
  
  		// Initialize the state
  		n = initialN;
  		delta = 0;
  		bias = initialBias;
  
  		// Handle the basic code points
  		for (j = 0; j < inputLength; ++j) {
  			currentValue = input[j];
  			if (currentValue < 0x80) {
  				output.push(stringFromCharCode(currentValue));
  			}
  		}
  
  		handledCPCount = basicLength = output.length;
  
  		// `handledCPCount` is the number of code points that have been handled;
  		// `basicLength` is the number of basic code points.
  
  		// Finish the basic string - if it is not empty - with a delimiter
  		if (basicLength) {
  			output.push(delimiter);
  		}
  
  		// Main encoding loop:
  		while (handledCPCount < inputLength) {
  
  			// All non-basic code points < n have been handled already. Find the next
  			// larger one:
  			for (m = maxInt, j = 0; j < inputLength; ++j) {
  				currentValue = input[j];
  				if (currentValue >= n && currentValue < m) {
  					m = currentValue;
  				}
  			}
  
  			// Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,
  			// but guard against overflow
  			handledCPCountPlusOne = handledCPCount + 1;
  			if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
  				error('overflow');
  			}
  
  			delta += (m - n) * handledCPCountPlusOne;
  			n = m;
  
  			for (j = 0; j < inputLength; ++j) {
  				currentValue = input[j];
  
  				if (currentValue < n && ++delta > maxInt) {
  					error('overflow');
  				}
  
  				if (currentValue == n) {
  					// Represent delta as a generalized variable-length integer
  					for (q = delta, k = base; /* no condition */; k += base) {
  						t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
  						if (q < t) {
  							break;
  						}
  						qMinusT = q - t;
  						baseMinusT = base - t;
  						output.push(
  							stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))
  						);
  						q = floor(qMinusT / baseMinusT);
  					}
  
  					output.push(stringFromCharCode(digitToBasic(q, 0)));
  					bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
  					delta = 0;
  					++handledCPCount;
  				}
  			}
  
  			++delta;
  			++n;
  
  		}
  		return output.join('');
  	}
  
  	/**
  	 * Converts a Punycode string representing a domain name or an email address
  	 * to Unicode. Only the Punycoded parts of the input will be converted, i.e.
  	 * it doesn't matter if you call it on a string that has already been
  	 * converted to Unicode.
  	 * @memberOf punycode
  	 * @param {String} input The Punycoded domain name or email address to
  	 * convert to Unicode.
  	 * @returns {String} The Unicode representation of the given Punycode
  	 * string.
  	 */
  	function toUnicode(input) {
  		return mapDomain(input, function(string) {
  			return regexPunycode.test(string)
  				? decode(string.slice(4).toLowerCase())
  				: string;
  		});
  	}
  
  	/**
  	 * Converts a Unicode string representing a domain name or an email address to
  	 * Punycode. Only the non-ASCII parts of the domain name will be converted,
  	 * i.e. it doesn't matter if you call it with a domain that's already in
  	 * ASCII.
  	 * @memberOf punycode
  	 * @param {String} input The domain name or email address to convert, as a
  	 * Unicode string.
  	 * @returns {String} The Punycode representation of the given domain name or
  	 * email address.
  	 */
  	function toASCII(input) {
  		return mapDomain(input, function(string) {
  			return regexNonASCII.test(string)
  				? 'xn--' + encode(string)
  				: string;
  		});
  	}
  
  	/*--------------------------------------------------------------------------*/
  
  	/** Define the public API */
  	punycode = {
  		/**
  		 * A string representing the current Punycode.js version number.
  		 * @memberOf punycode
  		 * @type String
  		 */
  		'version': '1.4.1',
  		/**
  		 * An object of methods to convert from JavaScript's internal character
  		 * representation (UCS-2) to Unicode code points, and back.
  		 * @see <https://mathiasbynens.be/notes/javascript-encoding>
  		 * @memberOf punycode
  		 * @type Object
  		 */
  		'ucs2': {
  			'decode': ucs2decode,
  			'encode': ucs2encode
  		},
  		'decode': decode,
  		'encode': encode,
  		'toASCII': toASCII,
  		'toUnicode': toUnicode
  	};
  
  	/** Expose `punycode` */
  	// Some AMD build optimizers, like r.js, check for specific condition patterns
  	// like the following:
  	if (
  		typeof define == 'function' &&
  		typeof define.amd == 'object' &&
  		define.amd
  	) {
  		define('punycode', function() {
  			return punycode;
  		});
  	} else if (freeExports && freeModule) {
  		if (module.exports == freeExports) {
  			// in Node.js, io.js, or RingoJS v0.8.0+
  			freeModule.exports = punycode;
  		} else {
  			// in Narwhal or RingoJS v0.7.0-
  			for (key in punycode) {
  				punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]);
  			}
  		}
  	} else {
  		// in Rhino or a web browser
  		root.punycode = punycode;
  	}
  
  }(this));
  
  }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  },{}],105:[function(require,module,exports){
  // Copyright Joyent, Inc. and other Node contributors.
  //
  // Permission is hereby granted, free of charge, to any person obtaining a
  // copy of this software and associated documentation files (the
  // "Software"), to deal in the Software without restriction, including
  // without limitation the rights to use, copy, modify, merge, publish,
  // distribute, sublicense, and/or sell copies of the Software, and to permit
  // persons to whom the Software is furnished to do so, subject to the
  // following conditions:
  //
  // The above copyright notice and this permission notice shall be included
  // in all copies or substantial portions of the Software.
  //
  // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  // USE OR OTHER DEALINGS IN THE SOFTWARE.
  
  'use strict';
  
  // If obj.hasOwnProperty has been overridden, then calling
  // obj.hasOwnProperty(prop) will break.
  // See: https://github.com/joyent/node/issues/1707
  function hasOwnProperty(obj, prop) {
    return Object.prototype.hasOwnProperty.call(obj, prop);
  }
  
  module.exports = function(qs, sep, eq, options) {
    sep = sep || '&';
    eq = eq || '=';
    var obj = {};
  
    if (typeof qs !== 'string' || qs.length === 0) {
      return obj;
    }
  
    var regexp = /\+/g;
    qs = qs.split(sep);
  
    var maxKeys = 1000;
    if (options && typeof options.maxKeys === 'number') {
      maxKeys = options.maxKeys;
    }
  
    var len = qs.length;
    // maxKeys <= 0 means that we should not limit keys count
    if (maxKeys > 0 && len > maxKeys) {
      len = maxKeys;
    }
  
    for (var i = 0; i < len; ++i) {
      var x = qs[i].replace(regexp, '%20'),
          idx = x.indexOf(eq),
          kstr, vstr, k, v;
  
      if (idx >= 0) {
        kstr = x.substr(0, idx);
        vstr = x.substr(idx + 1);
      } else {
        kstr = x;
        vstr = '';
      }
  
      k = decodeURIComponent(kstr);
      v = decodeURIComponent(vstr);
  
      if (!hasOwnProperty(obj, k)) {
        obj[k] = v;
      } else if (isArray(obj[k])) {
        obj[k].push(v);
      } else {
        obj[k] = [obj[k], v];
      }
    }
  
    return obj;
  };
  
  var isArray = Array.isArray || function (xs) {
    return Object.prototype.toString.call(xs) === '[object Array]';
  };
  
  },{}],106:[function(require,module,exports){
  // Copyright Joyent, Inc. and other Node contributors.
  //
  // Permission is hereby granted, free of charge, to any person obtaining a
  // copy of this software and associated documentation files (the
  // "Software"), to deal in the Software without restriction, including
  // without limitation the rights to use, copy, modify, merge, publish,
  // distribute, sublicense, and/or sell copies of the Software, and to permit
  // persons to whom the Software is furnished to do so, subject to the
  // following conditions:
  //
  // The above copyright notice and this permission notice shall be included
  // in all copies or substantial portions of the Software.
  //
  // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  // USE OR OTHER DEALINGS IN THE SOFTWARE.
  
  'use strict';
  
  var stringifyPrimitive = function(v) {
    switch (typeof v) {
      case 'string':
        return v;
  
      case 'boolean':
        return v ? 'true' : 'false';
  
      case 'number':
        return isFinite(v) ? v : '';
  
      default:
        return '';
    }
  };
  
  module.exports = function(obj, sep, eq, name) {
    sep = sep || '&';
    eq = eq || '=';
    if (obj === null) {
      obj = undefined;
    }
  
    if (typeof obj === 'object') {
      return map(objectKeys(obj), function(k) {
        var ks = encodeURIComponent(stringifyPrimitive(k)) + eq;
        if (isArray(obj[k])) {
          return map(obj[k], function(v) {
            return ks + encodeURIComponent(stringifyPrimitive(v));
          }).join(sep);
        } else {
          return ks + encodeURIComponent(stringifyPrimitive(obj[k]));
        }
      }).join(sep);
  
    }
  
    if (!name) return '';
    return encodeURIComponent(stringifyPrimitive(name)) + eq +
           encodeURIComponent(stringifyPrimitive(obj));
  };
  
  var isArray = Array.isArray || function (xs) {
    return Object.prototype.toString.call(xs) === '[object Array]';
  };
  
  function map (xs, f) {
    if (xs.map) return xs.map(f);
    var res = [];
    for (var i = 0; i < xs.length; i++) {
      res.push(f(xs[i], i));
    }
    return res;
  }
  
  var objectKeys = Object.keys || function (obj) {
    var res = [];
    for (var key in obj) {
      if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key);
    }
    return res;
  };
  
  },{}],107:[function(require,module,exports){
  'use strict';
  
  exports.decode = exports.parse = require('./decode');
  exports.encode = exports.stringify = require('./encode');
  
  },{"./decode":105,"./encode":106}],108:[function(require,module,exports){
  module.exports = require('./lib/_stream_duplex.js');
  
  },{"./lib/_stream_duplex.js":109}],109:[function(require,module,exports){
  arguments[4][59][0].apply(exports,arguments)
  },{"./_stream_readable":111,"./_stream_writable":113,"core-util-is":117,"dup":59,"inherits":101,"process-nextick-args":119}],110:[function(require,module,exports){
  arguments[4][60][0].apply(exports,arguments)
  },{"./_stream_transform":112,"core-util-is":117,"dup":60,"inherits":101}],111:[function(require,module,exports){
  arguments[4][61][0].apply(exports,arguments)
  },{"./_stream_duplex":109,"./internal/streams/BufferList":114,"./internal/streams/stream":115,"_process":103,"buffer":97,"buffer-shims":116,"core-util-is":117,"dup":61,"events":100,"inherits":101,"isarray":118,"process-nextick-args":119,"string_decoder/":126,"util":96}],112:[function(require,module,exports){
  arguments[4][62][0].apply(exports,arguments)
  },{"./_stream_duplex":109,"core-util-is":117,"dup":62,"inherits":101}],113:[function(require,module,exports){
  arguments[4][63][0].apply(exports,arguments)
  },{"./_stream_duplex":109,"./internal/streams/stream":115,"_process":103,"buffer":97,"buffer-shims":116,"core-util-is":117,"dup":63,"inherits":101,"process-nextick-args":119,"util-deprecate":120}],114:[function(require,module,exports){
  arguments[4][64][0].apply(exports,arguments)
  },{"buffer":97,"buffer-shims":116,"dup":64}],115:[function(require,module,exports){
  arguments[4][65][0].apply(exports,arguments)
  },{"dup":65,"events":100}],116:[function(require,module,exports){
  arguments[4][66][0].apply(exports,arguments)
  },{"buffer":97,"dup":66}],117:[function(require,module,exports){
  (function (Buffer){
  // Copyright Joyent, Inc. and other Node contributors.
  //
  // Permission is hereby granted, free of charge, to any person obtaining a
  // copy of this software and associated documentation files (the
  // "Software"), to deal in the Software without restriction, including
  // without limitation the rights to use, copy, modify, merge, publish,
  // distribute, sublicense, and/or sell copies of the Software, and to permit
  // persons to whom the Software is furnished to do so, subject to the
  // following conditions:
  //
  // The above copyright notice and this permission notice shall be included
  // in all copies or substantial portions of the Software.
  //
  // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  // USE OR OTHER DEALINGS IN THE SOFTWARE.
  
  // NOTE: These type checking functions intentionally don't use `instanceof`
  // because it is fragile and can be easily faked with `Object.create()`.
  
  function isArray(arg) {
    if (Array.isArray) {
      return Array.isArray(arg);
    }
    return objectToString(arg) === '[object Array]';
  }
  exports.isArray = isArray;
  
  function isBoolean(arg) {
    return typeof arg === 'boolean';
  }
  exports.isBoolean = isBoolean;
  
  function isNull(arg) {
    return arg === null;
  }
  exports.isNull = isNull;
  
  function isNullOrUndefined(arg) {
    return arg == null;
  }
  exports.isNullOrUndefined = isNullOrUndefined;
  
  function isNumber(arg) {
    return typeof arg === 'number';
  }
  exports.isNumber = isNumber;
  
  function isString(arg) {
    return typeof arg === 'string';
  }
  exports.isString = isString;
  
  function isSymbol(arg) {
    return typeof arg === 'symbol';
  }
  exports.isSymbol = isSymbol;
  
  function isUndefined(arg) {
    return arg === void 0;
  }
  exports.isUndefined = isUndefined;
  
  function isRegExp(re) {
    return objectToString(re) === '[object RegExp]';
  }
  exports.isRegExp = isRegExp;
  
  function isObject(arg) {
    return typeof arg === 'object' && arg !== null;
  }
  exports.isObject = isObject;
  
  function isDate(d) {
    return objectToString(d) === '[object Date]';
  }
  exports.isDate = isDate;
  
  function isError(e) {
    return (objectToString(e) === '[object Error]' || e instanceof Error);
  }
  exports.isError = isError;
  
  function isFunction(arg) {
    return typeof arg === 'function';
  }
  exports.isFunction = isFunction;
  
  function isPrimitive(arg) {
    return arg === null ||
           typeof arg === 'boolean' ||
           typeof arg === 'number' ||
           typeof arg === 'string' ||
           typeof arg === 'symbol' ||  // ES6 symbol
           typeof arg === 'undefined';
  }
  exports.isPrimitive = isPrimitive;
  
  exports.isBuffer = Buffer.isBuffer;
  
  function objectToString(o) {
    return Object.prototype.toString.call(o);
  }
  
  }).call(this,{"isBuffer":require("../../../../insert-module-globals/node_modules/is-buffer/index.js")})
  },{"../../../../insert-module-globals/node_modules/is-buffer/index.js":102}],118:[function(require,module,exports){
  arguments[4][68][0].apply(exports,arguments)
  },{"dup":68}],119:[function(require,module,exports){
  arguments[4][69][0].apply(exports,arguments)
  },{"_process":103,"dup":69}],120:[function(require,module,exports){
  arguments[4][72][0].apply(exports,arguments)
  },{"dup":72}],121:[function(require,module,exports){
  module.exports = require('./readable').PassThrough
  
  },{"./readable":122}],122:[function(require,module,exports){
  arguments[4][73][0].apply(exports,arguments)
  },{"./lib/_stream_duplex.js":109,"./lib/_stream_passthrough.js":110,"./lib/_stream_readable.js":111,"./lib/_stream_transform.js":112,"./lib/_stream_writable.js":113,"dup":73}],123:[function(require,module,exports){
  arguments[4][90][0].apply(exports,arguments)
  },{"./readable":122,"dup":90}],124:[function(require,module,exports){
  module.exports = require('./lib/_stream_writable.js');
  
  },{"./lib/_stream_writable.js":113}],125:[function(require,module,exports){
  // Copyright Joyent, Inc. and other Node contributors.
  //
  // Permission is hereby granted, free of charge, to any person obtaining a
  // copy of this software and associated documentation files (the
  // "Software"), to deal in the Software without restriction, including
  // without limitation the rights to use, copy, modify, merge, publish,
  // distribute, sublicense, and/or sell copies of the Software, and to permit
  // persons to whom the Software is furnished to do so, subject to the
  // following conditions:
  //
  // The above copyright notice and this permission notice shall be included
  // in all copies or substantial portions of the Software.
  //
  // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  // USE OR OTHER DEALINGS IN THE SOFTWARE.
  
  module.exports = Stream;
  
  var EE = require('events').EventEmitter;
  var inherits = require('inherits');
  
  inherits(Stream, EE);
  Stream.Readable = require('readable-stream/readable.js');
  Stream.Writable = require('readable-stream/writable.js');
  Stream.Duplex = require('readable-stream/duplex.js');
  Stream.Transform = require('readable-stream/transform.js');
  Stream.PassThrough = require('readable-stream/passthrough.js');
  
  // Backwards-compat with node 0.4.x
  Stream.Stream = Stream;
  
  
  
  // old-style streams.  Note that the pipe method (the only relevant
  // part of this class) is overridden in the Readable class.
  
  function Stream() {
    EE.call(this);
  }
  
  Stream.prototype.pipe = function(dest, options) {
    var source = this;
  
    function ondata(chunk) {
      if (dest.writable) {
        if (false === dest.write(chunk) && source.pause) {
          source.pause();
        }
      }
    }
  
    source.on('data', ondata);
  
    function ondrain() {
      if (source.readable && source.resume) {
        source.resume();
      }
    }
  
    dest.on('drain', ondrain);
  
    // If the 'end' option is not supplied, dest.end() will be called when
    // source gets the 'end' or 'close' events.  Only dest.end() once.
    if (!dest._isStdio && (!options || options.end !== false)) {
      source.on('end', onend);
      source.on('close', onclose);
    }
  
    var didOnEnd = false;
    function onend() {
      if (didOnEnd) return;
      didOnEnd = true;
  
      dest.end();
    }
  
  
    function onclose() {
      if (didOnEnd) return;
      didOnEnd = true;
  
      if (typeof dest.destroy === 'function') dest.destroy();
    }
  
    // don't leave dangling pipes when there are errors.
    function onerror(er) {
      cleanup();
      if (EE.listenerCount(this, 'error') === 0) {
        throw er; // Unhandled stream error in pipe.
      }
    }
  
    source.on('error', onerror);
    dest.on('error', onerror);
  
    // remove all the event listeners that were added.
    function cleanup() {
      source.removeListener('data', ondata);
      dest.removeListener('drain', ondrain);
  
      source.removeListener('end', onend);
      source.removeListener('close', onclose);
  
      source.removeListener('error', onerror);
      dest.removeListener('error', onerror);
  
      source.removeListener('end', cleanup);
      source.removeListener('close', cleanup);
  
      dest.removeListener('close', cleanup);
    }
  
    source.on('end', cleanup);
    source.on('close', cleanup);
  
    dest.on('close', cleanup);
  
    dest.emit('pipe', source);
  
    // Allow for unix-like usage: A.pipe(B).pipe(C)
    return dest;
  };
  
  },{"events":100,"inherits":101,"readable-stream/duplex.js":108,"readable-stream/passthrough.js":121,"readable-stream/readable.js":122,"readable-stream/transform.js":123,"readable-stream/writable.js":124}],126:[function(require,module,exports){
  arguments[4][70][0].apply(exports,arguments)
  },{"dup":70,"safe-buffer":127}],127:[function(require,module,exports){
  arguments[4][71][0].apply(exports,arguments)
  },{"buffer":97,"dup":71}],128:[function(require,module,exports){
  // Copyright Joyent, Inc. and other Node contributors.
  //
  // Permission is hereby granted, free of charge, to any person obtaining a
  // copy of this software and associated documentation files (the
  // "Software"), to deal in the Software without restriction, including
  // without limitation the rights to use, copy, modify, merge, publish,
  // distribute, sublicense, and/or sell copies of the Software, and to permit
  // persons to whom the Software is furnished to do so, subject to the
  // following conditions:
  //
  // The above copyright notice and this permission notice shall be included
  // in all copies or substantial portions of the Software.
  //
  // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  // USE OR OTHER DEALINGS IN THE SOFTWARE.
  
  'use strict';
  
  var punycode = require('punycode');
  var util = require('./util');
  
  exports.parse = urlParse;
  exports.resolve = urlResolve;
  exports.resolveObject = urlResolveObject;
  exports.format = urlFormat;
  
  exports.Url = Url;
  
  function Url() {
    this.protocol = null;
    this.slashes = null;
    this.auth = null;
    this.host = null;
    this.port = null;
    this.hostname = null;
    this.hash = null;
    this.search = null;
    this.query = null;
    this.pathname = null;
    this.path = null;
    this.href = null;
  }
  
  // Reference: RFC 3986, RFC 1808, RFC 2396
  
  // define these here so at least they only have to be
  // compiled once on the first module load.
  var protocolPattern = /^([a-z0-9.+-]+:)/i,
      portPattern = /:[0-9]*$/,
  
      // Special case for a simple path URL
      simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,
  
      // RFC 2396: characters reserved for delimiting URLs.
      // We actually just auto-escape these.
      delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'],
  
      // RFC 2396: characters not allowed for various reasons.
      unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims),
  
      // Allowed by RFCs, but cause of XSS attacks.  Always escape these.
      autoEscape = ['\''].concat(unwise),
      // Characters that are never ever allowed in a hostname.
      // Note that any invalid chars are also handled, but these
      // are the ones that are *expected* to be seen, so we fast-path
      // them.
      nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape),
      hostEndingChars = ['/', '?', '#'],
      hostnameMaxLen = 255,
      hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/,
      hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/,
      // protocols that can allow "unsafe" and "unwise" chars.
      unsafeProtocol = {
        'javascript': true,
        'javascript:': true
      },
      // protocols that never have a hostname.
      hostlessProtocol = {
        'javascript': true,
        'javascript:': true
      },
      // protocols that always contain a // bit.
      slashedProtocol = {
        'http': true,
        'https': true,
        'ftp': true,
        'gopher': true,
        'file': true,
        'http:': true,
        'https:': true,
        'ftp:': true,
        'gopher:': true,
        'file:': true
      },
      querystring = require('querystring');
  
  function urlParse(url, parseQueryString, slashesDenoteHost) {
    if (url && util.isObject(url) && url instanceof Url) return url;
  
    var u = new Url;
    u.parse(url, parseQueryString, slashesDenoteHost);
    return u;
  }
  
  Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) {
    if (!util.isString(url)) {
      throw new TypeError("Parameter 'url' must be a string, not " + typeof url);
    }
  
    // Copy chrome, IE, opera backslash-handling behavior.
    // Back slashes before the query string get converted to forward slashes
    // See: https://code.google.com/p/chromium/issues/detail?id=25916
    var queryIndex = url.indexOf('?'),
        splitter =
            (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#',
        uSplit = url.split(splitter),
        slashRegex = /\\/g;
    uSplit[0] = uSplit[0].replace(slashRegex, '/');
    url = uSplit.join(splitter);
  
    var rest = url;
  
    // trim before proceeding.
    // This is to support parse stuff like "  http://foo.com  \n"
    rest = rest.trim();
  
    if (!slashesDenoteHost && url.split('#').length === 1) {
      // Try fast path regexp
      var simplePath = simplePathPattern.exec(rest);
      if (simplePath) {
        this.path = rest;
        this.href = rest;
        this.pathname = simplePath[1];
        if (simplePath[2]) {
          this.search = simplePath[2];
          if (parseQueryString) {
            this.query = querystring.parse(this.search.substr(1));
          } else {
            this.query = this.search.substr(1);
          }
        } else if (parseQueryString) {
          this.search = '';
          this.query = {};
        }
        return this;
      }
    }
  
    var proto = protocolPattern.exec(rest);
    if (proto) {
      proto = proto[0];
      var lowerProto = proto.toLowerCase();
      this.protocol = lowerProto;
      rest = rest.substr(proto.length);
    }
  
    // figure out if it's got a host
    // user@server is *always* interpreted as a hostname, and url
    // resolution will treat //foo/bar as host=foo,path=bar because that's
    // how the browser resolves relative URLs.
    if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) {
      var slashes = rest.substr(0, 2) === '//';
      if (slashes && !(proto && hostlessProtocol[proto])) {
        rest = rest.substr(2);
        this.slashes = true;
      }
    }
  
    if (!hostlessProtocol[proto] &&
        (slashes || (proto && !slashedProtocol[proto]))) {
  
      // there's a hostname.
      // the first instance of /, ?, ;, or # ends the host.
      //
      // If there is an @ in the hostname, then non-host chars *are* allowed
      // to the left of the last @ sign, unless some host-ending character
      // comes *before* the @-sign.
      // URLs are obnoxious.
      //
      // ex:
      // http://a@b@c/ => user:a@b host:c
      // http://a@b?@c => user:a host:c path:/?@c
  
      // v0.12 TODO(isaacs): This is not quite how Chrome does things.
      // Review our test case against browsers more comprehensively.
  
      // find the first instance of any hostEndingChars
      var hostEnd = -1;
      for (var i = 0; i < hostEndingChars.length; i++) {
        var hec = rest.indexOf(hostEndingChars[i]);
        if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
          hostEnd = hec;
      }
  
      // at this point, either we have an explicit point where the
      // auth portion cannot go past, or the last @ char is the decider.
      var auth, atSign;
      if (hostEnd === -1) {
        // atSign can be anywhere.
        atSign = rest.lastIndexOf('@');
      } else {
        // atSign must be in auth portion.
        // http://a@b/c@d => host:b auth:a path:/c@d
        atSign = rest.lastIndexOf('@', hostEnd);
      }
  
      // Now we have a portion which is definitely the auth.
      // Pull that off.
      if (atSign !== -1) {
        auth = rest.slice(0, atSign);
        rest = rest.slice(atSign + 1);
        this.auth = decodeURIComponent(auth);
      }
  
      // the host is the remaining to the left of the first non-host char
      hostEnd = -1;
      for (var i = 0; i < nonHostChars.length; i++) {
        var hec = rest.indexOf(nonHostChars[i]);
        if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
          hostEnd = hec;
      }
      // if we still have not hit it, then the entire thing is a host.
      if (hostEnd === -1)
        hostEnd = rest.length;
  
      this.host = rest.slice(0, hostEnd);
      rest = rest.slice(hostEnd);
  
      // pull out port.
      this.parseHost();
  
      // we've indicated that there is a hostname,
      // so even if it's empty, it has to be present.
      this.hostname = this.hostname || '';
  
      // if hostname begins with [ and ends with ]
      // assume that it's an IPv6 address.
      var ipv6Hostname = this.hostname[0] === '[' &&
          this.hostname[this.hostname.length - 1] === ']';
  
      // validate a little.
      if (!ipv6Hostname) {
        var hostparts = this.hostname.split(/\./);
        for (var i = 0, l = hostparts.length; i < l; i++) {
          var part = hostparts[i];
          if (!part) continue;
          if (!part.match(hostnamePartPattern)) {
            var newpart = '';
            for (var j = 0, k = part.length; j < k; j++) {
              if (part.charCodeAt(j) > 127) {
                // we replace non-ASCII char with a temporary placeholder
                // we need this to make sure size of hostname is not
                // broken by replacing non-ASCII by nothing
                newpart += 'x';
              } else {
                newpart += part[j];
              }
            }
            // we test again with ASCII char only
            if (!newpart.match(hostnamePartPattern)) {
              var validParts = hostparts.slice(0, i);
              var notHost = hostparts.slice(i + 1);
              var bit = part.match(hostnamePartStart);
              if (bit) {
                validParts.push(bit[1]);
                notHost.unshift(bit[2]);
              }
              if (notHost.length) {
                rest = '/' + notHost.join('.') + rest;
              }
              this.hostname = validParts.join('.');
              break;
            }
          }
        }
      }
  
      if (this.hostname.length > hostnameMaxLen) {
        this.hostname = '';
      } else {
        // hostnames are always lower case.
        this.hostname = this.hostname.toLowerCase();
      }
  
      if (!ipv6Hostname) {
        // IDNA Support: Returns a punycoded representation of "domain".
        // It only converts parts of the domain name that
        // have non-ASCII characters, i.e. it doesn't matter if
        // you call it with a domain that already is ASCII-only.
        this.hostname = punycode.toASCII(this.hostname);
      }
  
      var p = this.port ? ':' + this.port : '';
      var h = this.hostname || '';
      this.host = h + p;
      this.href += this.host;
  
      // strip [ and ] from the hostname
      // the host field still retains them, though
      if (ipv6Hostname) {
        this.hostname = this.hostname.substr(1, this.hostname.length - 2);
        if (rest[0] !== '/') {
          rest = '/' + rest;
        }
      }
    }
  
    // now rest is set to the post-host stuff.
    // chop off any delim chars.
    if (!unsafeProtocol[lowerProto]) {
  
      // First, make 100% sure that any "autoEscape" chars get
      // escaped, even if encodeURIComponent doesn't think they
      // need to be.
      for (var i = 0, l = autoEscape.length; i < l; i++) {
        var ae = autoEscape[i];
        if (rest.indexOf(ae) === -1)
          continue;
        var esc = encodeURIComponent(ae);
        if (esc === ae) {
          esc = escape(ae);
        }
        rest = rest.split(ae).join(esc);
      }
    }
  
  
    // chop off from the tail first.
    var hash = rest.indexOf('#');
    if (hash !== -1) {
      // got a fragment string.
      this.hash = rest.substr(hash);
      rest = rest.slice(0, hash);
    }
    var qm = rest.indexOf('?');
    if (qm !== -1) {
      this.search = rest.substr(qm);
      this.query = rest.substr(qm + 1);
      if (parseQueryString) {
        this.query = querystring.parse(this.query);
      }
      rest = rest.slice(0, qm);
    } else if (parseQueryString) {
      // no query string, but parseQueryString still requested
      this.search = '';
      this.query = {};
    }
    if (rest) this.pathname = rest;
    if (slashedProtocol[lowerProto] &&
        this.hostname && !this.pathname) {
      this.pathname = '/';
    }
  
    //to support http.request
    if (this.pathname || this.search) {
      var p = this.pathname || '';
      var s = this.search || '';
      this.path = p + s;
    }
  
    // finally, reconstruct the href based on what has been validated.
    this.href = this.format();
    return this;
  };
  
  // format a parsed object into a url string
  function urlFormat(obj) {
    // ensure it's an object, and not a string url.
    // If it's an obj, this is a no-op.
    // this way, you can call url_format() on strings
    // to clean up potentially wonky urls.
    if (util.isString(obj)) obj = urlParse(obj);
    if (!(obj instanceof Url)) return Url.prototype.format.call(obj);
    return obj.format();
  }
  
  Url.prototype.format = function() {
    var auth = this.auth || '';
    if (auth) {
      auth = encodeURIComponent(auth);
      auth = auth.replace(/%3A/i, ':');
      auth += '@';
    }
  
    var protocol = this.protocol || '',
        pathname = this.pathname || '',
        hash = this.hash || '',
        host = false,
        query = '';
  
    if (this.host) {
      host = auth + this.host;
    } else if (this.hostname) {
      host = auth + (this.hostname.indexOf(':') === -1 ?
          this.hostname :
          '[' + this.hostname + ']');
      if (this.port) {
        host += ':' + this.port;
      }
    }
  
    if (this.query &&
        util.isObject(this.query) &&
        Object.keys(this.query).length) {
      query = querystring.stringify(this.query);
    }
  
    var search = this.search || (query && ('?' + query)) || '';
  
    if (protocol && protocol.substr(-1) !== ':') protocol += ':';
  
    // only the slashedProtocols get the //.  Not mailto:, xmpp:, etc.
    // unless they had them to begin with.
    if (this.slashes ||
        (!protocol || slashedProtocol[protocol]) && host !== false) {
      host = '//' + (host || '');
      if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname;
    } else if (!host) {
      host = '';
    }
  
    if (hash && hash.charAt(0) !== '#') hash = '#' + hash;
    if (search && search.charAt(0) !== '?') search = '?' + search;
  
    pathname = pathname.replace(/[?#]/g, function(match) {
      return encodeURIComponent(match);
    });
    search = search.replace('#', '%23');
  
    return protocol + host + pathname + search + hash;
  };
  
  function urlResolve(source, relative) {
    return urlParse(source, false, true).resolve(relative);
  }
  
  Url.prototype.resolve = function(relative) {
    return this.resolveObject(urlParse(relative, false, true)).format();
  };
  
  function urlResolveObject(source, relative) {
    if (!source) return relative;
    return urlParse(source, false, true).resolveObject(relative);
  }
  
  Url.prototype.resolveObject = function(relative) {
    if (util.isString(relative)) {
      var rel = new Url();
      rel.parse(relative, false, true);
      relative = rel;
    }
  
    var result = new Url();
    var tkeys = Object.keys(this);
    for (var tk = 0; tk < tkeys.length; tk++) {
      var tkey = tkeys[tk];
      result[tkey] = this[tkey];
    }
  
    // hash is always overridden, no matter what.
    // even href="" will remove it.
    result.hash = relative.hash;
  
    // if the relative url is empty, then there's nothing left to do here.
    if (relative.href === '') {
      result.href = result.format();
      return result;
    }
  
    // hrefs like //foo/bar always cut to the protocol.
    if (relative.slashes && !relative.protocol) {
      // take everything except the protocol from relative
      var rkeys = Object.keys(relative);
      for (var rk = 0; rk < rkeys.length; rk++) {
        var rkey = rkeys[rk];
        if (rkey !== 'protocol')
          result[rkey] = relative[rkey];
      }
  
      //urlParse appends trailing / to urls like http://www.example.com
      if (slashedProtocol[result.protocol] &&
          result.hostname && !result.pathname) {
        result.path = result.pathname = '/';
      }
  
      result.href = result.format();
      return result;
    }
  
    if (relative.protocol && relative.protocol !== result.protocol) {
      // if it's a known url protocol, then changing
      // the protocol does weird things
      // first, if it's not file:, then we MUST have a host,
      // and if there was a path
      // to begin with, then we MUST have a path.
      // if it is file:, then the host is dropped,
      // because that's known to be hostless.
      // anything else is assumed to be absolute.
      if (!slashedProtocol[relative.protocol]) {
        var keys = Object.keys(relative);
        for (var v = 0; v < keys.length; v++) {
          var k = keys[v];
          result[k] = relative[k];
        }
        result.href = result.format();
        return result;
      }
  
      result.protocol = relative.protocol;
      if (!relative.host && !hostlessProtocol[relative.protocol]) {
        var relPath = (relative.pathname || '').split('/');
        while (relPath.length && !(relative.host = relPath.shift()));
        if (!relative.host) relative.host = '';
        if (!relative.hostname) relative.hostname = '';
        if (relPath[0] !== '') relPath.unshift('');
        if (relPath.length < 2) relPath.unshift('');
        result.pathname = relPath.join('/');
      } else {
        result.pathname = relative.pathname;
      }
      result.search = relative.search;
      result.query = relative.query;
      result.host = relative.host || '';
      result.auth = relative.auth;
      result.hostname = relative.hostname || relative.host;
      result.port = relative.port;
      // to support http.request
      if (result.pathname || result.search) {
        var p = result.pathname || '';
        var s = result.search || '';
        result.path = p + s;
      }
      result.slashes = result.slashes || relative.slashes;
      result.href = result.format();
      return result;
    }
  
    var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'),
        isRelAbs = (
            relative.host ||
            relative.pathname && relative.pathname.charAt(0) === '/'
        ),
        mustEndAbs = (isRelAbs || isSourceAbs ||
                      (result.host && relative.pathname)),
        removeAllDots = mustEndAbs,
        srcPath = result.pathname && result.pathname.split('/') || [],
        relPath = relative.pathname && relative.pathname.split('/') || [],
        psychotic = result.protocol && !slashedProtocol[result.protocol];
  
    // if the url is a non-slashed url, then relative
    // links like ../.. should be able
    // to crawl up to the hostname, as well.  This is strange.
    // result.protocol has already been set by now.
    // Later on, put the first path part into the host field.
    if (psychotic) {
      result.hostname = '';
      result.port = null;
      if (result.host) {
        if (srcPath[0] === '') srcPath[0] = result.host;
        else srcPath.unshift(result.host);
      }
      result.host = '';
      if (relative.protocol) {
        relative.hostname = null;
        relative.port = null;
        if (relative.host) {
          if (relPath[0] === '') relPath[0] = relative.host;
          else relPath.unshift(relative.host);
        }
        relative.host = null;
      }
      mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === '');
    }
  
    if (isRelAbs) {
      // it's absolute.
      result.host = (relative.host || relative.host === '') ?
                    relative.host : result.host;
      result.hostname = (relative.hostname || relative.hostname === '') ?
                        relative.hostname : result.hostname;
      result.search = relative.search;
      result.query = relative.query;
      srcPath = relPath;
      // fall through to the dot-handling below.
    } else if (relPath.length) {
      // it's relative
      // throw away the existing file, and take the new path instead.
      if (!srcPath) srcPath = [];
      srcPath.pop();
      srcPath = srcPath.concat(relPath);
      result.search = relative.search;
      result.query = relative.query;
    } else if (!util.isNullOrUndefined(relative.search)) {
      // just pull out the search.
      // like href='?foo'.
      // Put this after the other two cases because it simplifies the booleans
      if (psychotic) {
        result.hostname = result.host = srcPath.shift();
        //occationaly the auth can get stuck only in host
        //this especially happens in cases like
        //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
        var authInHost = result.host && result.host.indexOf('@') > 0 ?
                         result.host.split('@') : false;
        if (authInHost) {
          result.auth = authInHost.shift();
          result.host = result.hostname = authInHost.shift();
        }
      }
      result.search = relative.search;
      result.query = relative.query;
      //to support http.request
      if (!util.isNull(result.pathname) || !util.isNull(result.search)) {
        result.path = (result.pathname ? result.pathname : '') +
                      (result.search ? result.search : '');
      }
      result.href = result.format();
      return result;
    }
  
    if (!srcPath.length) {
      // no path at all.  easy.
      // we've already handled the other stuff above.
      result.pathname = null;
      //to support http.request
      if (result.search) {
        result.path = '/' + result.search;
      } else {
        result.path = null;
      }
      result.href = result.format();
      return result;
    }
  
    // if a url ENDs in . or .., then it must get a trailing slash.
    // however, if it ends in anything else non-slashy,
    // then it must NOT get a trailing slash.
    var last = srcPath.slice(-1)[0];
    var hasTrailingSlash = (
        (result.host || relative.host || srcPath.length > 1) &&
        (last === '.' || last === '..') || last === '');
  
    // strip single dots, resolve double dots to parent dir
    // if the path tries to go above the root, `up` ends up > 0
    var up = 0;
    for (var i = srcPath.length; i >= 0; i--) {
      last = srcPath[i];
      if (last === '.') {
        srcPath.splice(i, 1);
      } else if (last === '..') {
        srcPath.splice(i, 1);
        up++;
      } else if (up) {
        srcPath.splice(i, 1);
        up--;
      }
    }
  
    // if the path is allowed to go above the root, restore leading ..s
    if (!mustEndAbs && !removeAllDots) {
      for (; up--; up) {
        srcPath.unshift('..');
      }
    }
  
    if (mustEndAbs && srcPath[0] !== '' &&
        (!srcPath[0] || srcPath[0].charAt(0) !== '/')) {
      srcPath.unshift('');
    }
  
    if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) {
      srcPath.push('');
    }
  
    var isAbsolute = srcPath[0] === '' ||
        (srcPath[0] && srcPath[0].charAt(0) === '/');
  
    // put the host back
    if (psychotic) {
      result.hostname = result.host = isAbsolute ? '' :
                                      srcPath.length ? srcPath.shift() : '';
      //occationaly the auth can get stuck only in host
      //this especially happens in cases like
      //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
      var authInHost = result.host && result.host.indexOf('@') > 0 ?
                       result.host.split('@') : false;
      if (authInHost) {
        result.auth = authInHost.shift();
        result.host = result.hostname = authInHost.shift();
      }
    }
  
    mustEndAbs = mustEndAbs || (result.host && srcPath.length);
  
    if (mustEndAbs && !isAbsolute) {
      srcPath.unshift('');
    }
  
    if (!srcPath.length) {
      result.pathname = null;
      result.path = null;
    } else {
      result.pathname = srcPath.join('/');
    }
  
    //to support request.http
    if (!util.isNull(result.pathname) || !util.isNull(result.search)) {
      result.path = (result.pathname ? result.pathname : '') +
                    (result.search ? result.search : '');
    }
    result.auth = relative.auth || result.auth;
    result.slashes = result.slashes || relative.slashes;
    result.href = result.format();
    return result;
  };
  
  Url.prototype.parseHost = function() {
    var host = this.host;
    var port = portPattern.exec(host);
    if (port) {
      port = port[0];
      if (port !== ':') {
        this.port = port.substr(1);
      }
      host = host.substr(0, host.length - port.length);
    }
    if (host) this.hostname = host;
  };
  
  },{"./util":129,"punycode":104,"querystring":107}],129:[function(require,module,exports){
  'use strict';
  
  module.exports = {
    isString: function(arg) {
      return typeof(arg) === 'string';
    },
    isObject: function(arg) {
      return typeof(arg) === 'object' && arg !== null;
    },
    isNull: function(arg) {
      return arg === null;
    },
    isNullOrUndefined: function(arg) {
      return arg == null;
    }
  };
  
  },{}],130:[function(require,module,exports){
  arguments[4][38][0].apply(exports,arguments)
  },{"dup":38}],131:[function(require,module,exports){
  module.exports = function isBuffer(arg) {
    return arg && typeof arg === 'object'
      && typeof arg.copy === 'function'
      && typeof arg.fill === 'function'
      && typeof arg.readUInt8 === 'function';
  }
  },{}],132:[function(require,module,exports){
  (function (process,global){
  // Copyright Joyent, Inc. and other Node contributors.
  //
  // Permission is hereby granted, free of charge, to any person obtaining a
  // copy of this software and associated documentation files (the
  // "Software"), to deal in the Software without restriction, including
  // without limitation the rights to use, copy, modify, merge, publish,
  // distribute, sublicense, and/or sell copies of the Software, and to permit
  // persons to whom the Software is furnished to do so, subject to the
  // following conditions:
  //
  // The above copyright notice and this permission notice shall be included
  // in all copies or substantial portions of the Software.
  //
  // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  // USE OR OTHER DEALINGS IN THE SOFTWARE.
  
  var formatRegExp = /%[sdj%]/g;
  exports.format = function(f) {
    if (!isString(f)) {
      var objects = [];
      for (var i = 0; i < arguments.length; i++) {
        objects.push(inspect(arguments[i]));
      }
      return objects.join(' ');
    }
  
    var i = 1;
    var args = arguments;
    var len = args.length;
    var str = String(f).replace(formatRegExp, function(x) {
      if (x === '%%') return '%';
      if (i >= len) return x;
      switch (x) {
        case '%s': return String(args[i++]);
        case '%d': return Number(args[i++]);
        case '%j':
          try {
            return JSON.stringify(args[i++]);
          } catch (_) {
            return '[Circular]';
          }
        default:
          return x;
      }
    });
    for (var x = args[i]; i < len; x = args[++i]) {
      if (isNull(x) || !isObject(x)) {
        str += ' ' + x;
      } else {
        str += ' ' + inspect(x);
      }
    }
    return str;
  };
  
  
  // Mark that a method should not be used.
  // Returns a modified function which warns once by default.
  // If --no-deprecation is set, then it is a no-op.
  exports.deprecate = function(fn, msg) {
    // Allow for deprecating things in the process of starting up.
    if (isUndefined(global.process)) {
      return function() {
        return exports.deprecate(fn, msg).apply(this, arguments);
      };
    }
  
    if (process.noDeprecation === true) {
      return fn;
    }
  
    var warned = false;
    function deprecated() {
      if (!warned) {
        if (process.throwDeprecation) {
          throw new Error(msg);
        } else if (process.traceDeprecation) {
          console.trace(msg);
        } else {
          console.error(msg);
        }
        warned = true;
      }
      return fn.apply(this, arguments);
    }
  
    return deprecated;
  };
  
  
  var debugs = {};
  var debugEnviron;
  exports.debuglog = function(set) {
    if (isUndefined(debugEnviron))
      debugEnviron = process.env.NODE_DEBUG || '';
    set = set.toUpperCase();
    if (!debugs[set]) {
      if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
        var pid = process.pid;
        debugs[set] = function() {
          var msg = exports.format.apply(exports, arguments);
          console.error('%s %d: %s', set, pid, msg);
        };
      } else {
        debugs[set] = function() {};
      }
    }
    return debugs[set];
  };
  
  
  /**
   * Echos the value of a value. Trys to print the value out
   * in the best way possible given the different types.
   *
   * @param {Object} obj The object to print out.
   * @param {Object} opts Optional options object that alters the output.
   */
  /* legacy: obj, showHidden, depth, colors*/
  function inspect(obj, opts) {
    // default options
    var ctx = {
      seen: [],
      stylize: stylizeNoColor
    };
    // legacy...
    if (arguments.length >= 3) ctx.depth = arguments[2];
    if (arguments.length >= 4) ctx.colors = arguments[3];
    if (isBoolean(opts)) {
      // legacy...
      ctx.showHidden = opts;
    } else if (opts) {
      // got an "options" object
      exports._extend(ctx, opts);
    }
    // set default options
    if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
    if (isUndefined(ctx.depth)) ctx.depth = 2;
    if (isUndefined(ctx.colors)) ctx.colors = false;
    if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
    if (ctx.colors) ctx.stylize = stylizeWithColor;
    return formatValue(ctx, obj, ctx.depth);
  }
  exports.inspect = inspect;
  
  
  // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
  inspect.colors = {
    'bold' : [1, 22],
    'italic' : [3, 23],
    'underline' : [4, 24],
    'inverse' : [7, 27],
    'white' : [37, 39],
    'grey' : [90, 39],
    'black' : [30, 39],
    'blue' : [34, 39],
    'cyan' : [36, 39],
    'green' : [32, 39],
    'magenta' : [35, 39],
    'red' : [31, 39],
    'yellow' : [33, 39]
  };
  
  // Don't use 'blue' not visible on cmd.exe
  inspect.styles = {
    'special': 'cyan',
    'number': 'yellow',
    'boolean': 'yellow',
    'undefined': 'grey',
    'null': 'bold',
    'string': 'green',
    'date': 'magenta',
    // "name": intentionally not styling
    'regexp': 'red'
  };
  
  
  function stylizeWithColor(str, styleType) {
    var style = inspect.styles[styleType];
  
    if (style) {
      return '\u001b[' + inspect.colors[style][0] + 'm' + str +
             '\u001b[' + inspect.colors[style][1] + 'm';
    } else {
      return str;
    }
  }
  
  
  function stylizeNoColor(str, styleType) {
    return str;
  }
  
  
  function arrayToHash(array) {
    var hash = {};
  
    array.forEach(function(val, idx) {
      hash[val] = true;
    });
  
    return hash;
  }
  
  
  function formatValue(ctx, value, recurseTimes) {
    // Provide a hook for user-specified inspect functions.
    // Check that value is an object with an inspect function on it
    if (ctx.customInspect &&
        value &&
        isFunction(value.inspect) &&
        // Filter out the util module, it's inspect function is special
        value.inspect !== exports.inspect &&
        // Also filter out any prototype objects using the circular check.
        !(value.constructor && value.constructor.prototype === value)) {
      var ret = value.inspect(recurseTimes, ctx);
      if (!isString(ret)) {
        ret = formatValue(ctx, ret, recurseTimes);
      }
      return ret;
    }
  
    // Primitive types cannot have properties
    var primitive = formatPrimitive(ctx, value);
    if (primitive) {
      return primitive;
    }
  
    // Look up the keys of the object.
    var keys = Object.keys(value);
    var visibleKeys = arrayToHash(keys);
  
    if (ctx.showHidden) {
      keys = Object.getOwnPropertyNames(value);
    }
  
    // IE doesn't make error fields non-enumerable
    // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
    if (isError(value)
        && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
      return formatError(value);
    }
  
    // Some type of object without properties can be shortcutted.
    if (keys.length === 0) {
      if (isFunction(value)) {
        var name = value.name ? ': ' + value.name : '';
        return ctx.stylize('[Function' + name + ']', 'special');
      }
      if (isRegExp(value)) {
        return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
      }
      if (isDate(value)) {
        return ctx.stylize(Date.prototype.toString.call(value), 'date');
      }
      if (isError(value)) {
        return formatError(value);
      }
    }
  
    var base = '', array = false, braces = ['{', '}'];
  
    // Make Array say that they are Array
    if (isArray(value)) {
      array = true;
      braces = ['[', ']'];
    }
  
    // Make functions say that they are functions
    if (isFunction(value)) {
      var n = value.name ? ': ' + value.name : '';
      base = ' [Function' + n + ']';
    }
  
    // Make RegExps say that they are RegExps
    if (isRegExp(value)) {
      base = ' ' + RegExp.prototype.toString.call(value);
    }
  
    // Make dates with properties first say the date
    if (isDate(value)) {
      base = ' ' + Date.prototype.toUTCString.call(value);
    }
  
    // Make error with message first say the error
    if (isError(value)) {
      base = ' ' + formatError(value);
    }
  
    if (keys.length === 0 && (!array || value.length == 0)) {
      return braces[0] + base + braces[1];
    }
  
    if (recurseTimes < 0) {
      if (isRegExp(value)) {
        return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
      } else {
        return ctx.stylize('[Object]', 'special');
      }
    }
  
    ctx.seen.push(value);
  
    var output;
    if (array) {
      output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
    } else {
      output = keys.map(function(key) {
        return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
      });
    }
  
    ctx.seen.pop();
  
    return reduceToSingleString(output, base, braces);
  }
  
  
  function formatPrimitive(ctx, value) {
    if (isUndefined(value))
      return ctx.stylize('undefined', 'undefined');
    if (isString(value)) {
      var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
                                               .replace(/'/g, "\\'")
                                               .replace(/\\"/g, '"') + '\'';
      return ctx.stylize(simple, 'string');
    }
    if (isNumber(value))
      return ctx.stylize('' + value, 'number');
    if (isBoolean(value))
      return ctx.stylize('' + value, 'boolean');
    // For some reason typeof null is "object", so special case here.
    if (isNull(value))
      return ctx.stylize('null', 'null');
  }
  
  
  function formatError(value) {
    return '[' + Error.prototype.toString.call(value) + ']';
  }
  
  
  function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
    var output = [];
    for (var i = 0, l = value.length; i < l; ++i) {
      if (hasOwnProperty(value, String(i))) {
        output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
            String(i), true));
      } else {
        output.push('');
      }
    }
    keys.forEach(function(key) {
      if (!key.match(/^\d+$/)) {
        output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
            key, true));
      }
    });
    return output;
  }
  
  
  function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
    var name, str, desc;
    desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
    if (desc.get) {
      if (desc.set) {
        str = ctx.stylize('[Getter/Setter]', 'special');
      } else {
        str = ctx.stylize('[Getter]', 'special');
      }
    } else {
      if (desc.set) {
        str = ctx.stylize('[Setter]', 'special');
      }
    }
    if (!hasOwnProperty(visibleKeys, key)) {
      name = '[' + key + ']';
    }
    if (!str) {
      if (ctx.seen.indexOf(desc.value) < 0) {
        if (isNull(recurseTimes)) {
          str = formatValue(ctx, desc.value, null);
        } else {
          str = formatValue(ctx, desc.value, recurseTimes - 1);
        }
        if (str.indexOf('\n') > -1) {
          if (array) {
            str = str.split('\n').map(function(line) {
              return '  ' + line;
            }).join('\n').substr(2);
          } else {
            str = '\n' + str.split('\n').map(function(line) {
              return '   ' + line;
            }).join('\n');
          }
        }
      } else {
        str = ctx.stylize('[Circular]', 'special');
      }
    }
    if (isUndefined(name)) {
      if (array && key.match(/^\d+$/)) {
        return str;
      }
      name = JSON.stringify('' + key);
      if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
        name = name.substr(1, name.length - 2);
        name = ctx.stylize(name, 'name');
      } else {
        name = name.replace(/'/g, "\\'")
                   .replace(/\\"/g, '"')
                   .replace(/(^"|"$)/g, "'");
        name = ctx.stylize(name, 'string');
      }
    }
  
    return name + ': ' + str;
  }
  
  
  function reduceToSingleString(output, base, braces) {
    var numLinesEst = 0;
    var length = output.reduce(function(prev, cur) {
      numLinesEst++;
      if (cur.indexOf('\n') >= 0) numLinesEst++;
      return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
    }, 0);
  
    if (length > 60) {
      return braces[0] +
             (base === '' ? '' : base + '\n ') +
             ' ' +
             output.join(',\n  ') +
             ' ' +
             braces[1];
    }
  
    return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
  }
  
  
  // NOTE: These type checking functions intentionally don't use `instanceof`
  // because it is fragile and can be easily faked with `Object.create()`.
  function isArray(ar) {
    return Array.isArray(ar);
  }
  exports.isArray = isArray;
  
  function isBoolean(arg) {
    return typeof arg === 'boolean';
  }
  exports.isBoolean = isBoolean;
  
  function isNull(arg) {
    return arg === null;
  }
  exports.isNull = isNull;
  
  function isNullOrUndefined(arg) {
    return arg == null;
  }
  exports.isNullOrUndefined = isNullOrUndefined;
  
  function isNumber(arg) {
    return typeof arg === 'number';
  }
  exports.isNumber = isNumber;
  
  function isString(arg) {
    return typeof arg === 'string';
  }
  exports.isString = isString;
  
  function isSymbol(arg) {
    return typeof arg === 'symbol';
  }
  exports.isSymbol = isSymbol;
  
  function isUndefined(arg) {
    return arg === void 0;
  }
  exports.isUndefined = isUndefined;
  
  function isRegExp(re) {
    return isObject(re) && objectToString(re) === '[object RegExp]';
  }
  exports.isRegExp = isRegExp;
  
  function isObject(arg) {
    return typeof arg === 'object' && arg !== null;
  }
  exports.isObject = isObject;
  
  function isDate(d) {
    return isObject(d) && objectToString(d) === '[object Date]';
  }
  exports.isDate = isDate;
  
  function isError(e) {
    return isObject(e) &&
        (objectToString(e) === '[object Error]' || e instanceof Error);
  }
  exports.isError = isError;
  
  function isFunction(arg) {
    return typeof arg === 'function';
  }
  exports.isFunction = isFunction;
  
  function isPrimitive(arg) {
    return arg === null ||
           typeof arg === 'boolean' ||
           typeof arg === 'number' ||
           typeof arg === 'string' ||
           typeof arg === 'symbol' ||  // ES6 symbol
           typeof arg === 'undefined';
  }
  exports.isPrimitive = isPrimitive;
  
  exports.isBuffer = require('./support/isBuffer');
  
  function objectToString(o) {
    return Object.prototype.toString.call(o);
  }
  
  
  function pad(n) {
    return n < 10 ? '0' + n.toString(10) : n.toString(10);
  }
  
  
  var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
                'Oct', 'Nov', 'Dec'];
  
  // 26 Feb 16:19:34
  function timestamp() {
    var d = new Date();
    var time = [pad(d.getHours()),
                pad(d.getMinutes()),
                pad(d.getSeconds())].join(':');
    return [d.getDate(), months[d.getMonth()], time].join(' ');
  }
  
  
  // log is just a thin wrapper to console.log that prepends a timestamp
  exports.log = function() {
    console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
  };
  
  
  /**
   * Inherit the prototype methods from one constructor into another.
   *
   * The Function.prototype.inherits from lang.js rewritten as a standalone
   * function (not on Function.prototype). NOTE: If this file is to be loaded
   * during bootstrapping this function needs to be rewritten using some native
   * functions as prototype setup using normal JavaScript does not work as
   * expected during bootstrapping (see mirror.js in r114903).
   *
   * @param {function} ctor Constructor function which needs to inherit the
   *     prototype.
   * @param {function} superCtor Constructor function to inherit prototype from.
   */
  exports.inherits = require('inherits');
  
  exports._extend = function(origin, add) {
    // Don't do anything if add isn't an object
    if (!add || !isObject(add)) return origin;
  
    var keys = Object.keys(add);
    var i = keys.length;
    while (i--) {
      origin[keys[i]] = add[keys[i]];
    }
    return origin;
  };
  
  function hasOwnProperty(obj, prop) {
    return Object.prototype.hasOwnProperty.call(obj, prop);
  }
  
  }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  },{"./support/isBuffer":131,"_process":103,"inherits":130}]},{},[1]);
  