[
  {
    "path": ".gitignore",
    "content": ".DS_Store\n*.swp\n*.swo\nnode_modules/\n"
  },
  {
    "path": ".travis.yml",
    "content": "language: node_js\nnode_js:\n  - 0.8\nbefore_install:\n  - npm install -g npm@'>=1.4.3'\n"
  },
  {
    "path": "Cakefile",
    "content": "# Taken almost entirely from https://github.com/twilson63/cakefile-template\n# \n# Il y a 5 tasks:\n#\n# * build - compiles your src directory to your lib directory\n# * watch - watches any changes in your src directory and automatically compiles to the lib directory\n# * test  - runs mocha test framework, you can edit this task to use your favorite test framework\n# * docs  - generates annotated documentation using docco\n# * clean - clean generated .js files\nfiles = [\n  'lib'\n  'src'\n]\n\nfs = require 'fs'\n{print} = require 'util'\n{spawn, exec} = require 'child_process'\n\ntry\n  which = require('which').sync\ncatch err\n  which = null\n\n# ANSI Terminal Colors\nbold = '\\x1b[0;1m'\ngreen = '\\x1b[0;32m'\nreset = '\\x1b[0m'\nred = '\\x1b[0;31m'\n\n# Cakefile Tasks\n#\n# ## *docs*\n#\n# Generate Annotated Documentation\n#\n# <small>Usage</small>\n#\n# ```\n# cake docs\n# ```\ntask 'docs', 'generate documentation', -> docco()\n\n# ## *build*\n#\n# Builds Source\n#\n# <small>Usage</small>\n#\n# ```\n# cake build\n# ```\ntask 'build', 'compile source', -> build -> log \":)\", green\n\n# ## *watch*\n#\n# Builds your source whenever it changes\n#\n# <small>Usage</small>\n#\n# ```\n# cake watch\n# ```\ntask 'watch', 'compile and watch', -> build true, -> log \":-)\", green\n\n# ## *test*\n#\n# Runs your test suite.\n#\n# <small>Usage</small>\n#\n# ```\n# cake test\n# ```\ntask 'test', 'run tests', -> build -> expresso [ 'test/*' ], -> log \":)\", green\n\n# ## *clean*\n#\n# Cleans up generated js files\n#\n# <small>Ussage</small>\n#\n# ```\n# cake clean\n# ```\ntask 'clean', 'clean generated files', -> clean -> log \";)\", green\n\n\n# Internal Functions\n#\n# ## *walk* \n#\n# **given** string as dir which represents a directory in relation to local directory\n# **and** callback as done in the form of (err, results)\n# **then** recurse through directory returning an array of files\nwalk = (dir, done) ->\n  results = []\n  fs.readdir dir, (err, list) ->\n    return done(err, []) if err\n    pending = list.length\n    return done(null, results) unless pending\n    for name in list\n      file = \"#{dir}/#{name}\"\n      try\n        stat = fs.statSync file\n      catch err\n        stat = null\n      if stat?.isDirectory()\n        walk file, (err, res) ->\n          results.push name for name in res\n          done(null, results) unless --pending\n      else\n        results.push file\n        done(null, results) unless --pending\n\n# ## *log* \n# \n# **given** string as a message\n# **and** string as a color\n# **and** optional string as an explaination\n# **then** builds a statement and logs to console.\nlog = (message, color, explanation) -> console.log color + message + reset + ' ' + (explanation or '')\n\n# ## *launch*\n#\n# **given** string as a cmd\n# **and** optional array and option flags\n# **and** optional callback\n# **then** spawn cmd with options\n# **and** pipe to process stdout and stderr respectively\n# **and** on child process exit emit callback if set and status is 0\nlaunch = (cmd, options=[], callback) ->\n  cmd = which(cmd) if which\n  app = spawn cmd, options\n  app.stdout.pipe(process.stdout)\n  app.stderr.pipe(process.stderr)\n  app.on 'exit', (status) -> callback?() if status is 0\n\n# ## *build*\n#\n# **given** optional boolean as watch\n# **and** optional function as callback\n# **then** invoke launch passing coffee command\n# **and** defaulted options to compile src to lib\nbuild = (watch, callback) ->\n  if typeof watch is 'function'\n    callback = watch\n    watch = false\n\n  options = ['-c', '-b', '-o' ]\n  options = options.concat files\n  options.unshift '-w' if watch\n  launch 'coffee', options, callback\n\n# ## *unlinkIfCoffeeFile*\n#\n# **given** string as file\n# **and** file ends in '.coffee'\n# **then** convert '.coffee' to '.js'\n# **and** remove the result\nunlinkIfCoffeeFile = (file) ->\n  if file.match /\\.coffee$/\n    fs.unlink file.replace(/\\.coffee$/, '.js')\n    true\n  else false\n\n# ## *clean*\n#\n# **given** optional function as callback\n# **then** loop through files variable\n# **and** call unlinkIfCoffeeFile on each\nclean = (callback) ->\n  try\n    for file in files\n      unless unlinkIfCoffeeFile file\n        walk file, (err, results) ->\n          for f in results\n            unlinkIfCoffeeFile f\n\n    callback?()\n  catch err\n\n# ## *moduleExists*\n#\n# **given** name for module\n# **when** trying to require module\n# **and** not found\n# **then* print not found message with install helper in red\n# **and* return false if not found\nmoduleExists = (name) ->\n  try \n    require name \n  catch err \n    log \"#{name} required: npm install #{name}\", red\n    false\n\n\n# ## *expresso*\n#\n# **given** optional array of option flags\n# **and** optional function as callback\n# **then** invoke launch passing expresso command\nexpresso = (options, callback) ->\n  if typeof options is 'function'\n    callback = options\n    options = []\n  \n  launch './node_modules/expresso/bin/expresso', options, callback\n\n# ## *docco*\n#\n# **given** optional function as callback\n# **then** invoke launch passing docco command\ndocco = (callback) ->\n  #if moduleExists('docco')\n  walk 'src', (err, files) -> launch 'docco', files, callback\n\n"
  },
  {
    "path": "README.textile",
    "content": "h1. soda-js \"!https://secure.travis-ci.org/socrata/soda-js.png!\":http://travis-ci.org/socrata/soda-js\n\nA client implementation of the Socrata Open Data API in Coffeescript and Javascript.\n\nh2. Important Note\n\nIn order to access the SODA API via HTTPS, clients must now \"support the Server Name Indication (SNI)\":https://dev.socrata.com/changelog/2016/08/24/sni-now-required-for-https-connections.html extension to the TLS protocol. What does this mean? It means that if you're using @soda-js@, you must use a JavaScript VM that supports SNI:\n\n* \"Internet Explorer 7+\":https://en.wikipedia.org/wiki/Server_Name_Indication#Support\n* \"Mozilla Firefox 2+\":https://en.wikipedia.org/wiki/Server_Name_Indication#Support\n* \"Apple Safari (all versions)\":https://en.wikipedia.org/wiki/Server_Name_Indication#Support\n* \"Google Chrome 6.0+\":https://en.wikipedia.org/wiki/Server_Name_Indication#Support\n* \"node.js 0.5.3+\":https://github.com/nodejs/node/blob/e1643ccc5a5ecf7cb779472d244459469c9971a1/doc/changelogs/CHANGELOG_ARCHIVE.md#20110801-version-053-unstable\n\nh2. Supported Operations\n\nSupports both consumer and producer API, but does not currently support creating datasets or the import workflow.\n\nh2. Usage\n\nSee the @sample/@ directory for sample code, but here's the general idea:\n\nbc.. var soda = require('soda-js');\n\nh3. Consumer API\n\nYou can query a dataset by SODA2 clauses, or supply a custom SoQL query to be run.\n\nbc.. var consumer = new soda.Consumer('explore.data.gov');\n\nconsumer.query()\n  .withDataset('644b-gaut')\n  .limit(5)\n  .where({ namelast: 'SMITH' })\n  .order('namelast')\n  .getRows()\n    .on('success', function(rows) { console.log(rows); })\n    .on('error', function(error) { console.error(error); });\n\np. Using 'like' in a where clause:\n\nbc.. .where(\"namelast like '%MITH'\")\n\nh3. Producer API\n\nYou can add, update, replace, delete, and upsert rows, as well as truncate a dataset.\n\nbc.. var producer = new soda.Producer('sandbox.demo.socrata.com', sodaConnectionOptions);\n\nvar data = { mynum : 42, mytext: \"hello world\" }\n\nproducer.operation()\n  .withDataset('rphc-ayt9')\n  .add(data)\n    .on('success', function(row) { console.log(row); })\n    .on('error', function(error) { console.error(error); })\n\nh2. License\n\nProvided under the MIT license.\n\n"
  },
  {
    "path": "lib/README",
    "content": "this directory contains autogenerated files. do not edit them! edit the files in src/ instead.\n"
  },
  {
    "path": "lib/soda-js.bundle.js",
    "content": "(function(f){if(typeof exports===\"object\"&&typeof module!==\"undefined\"){module.exports=f()}else if(typeof define===\"function\"&&define.amd){define([],f)}else{var g;if(typeof window!==\"undefined\"){g=window}else if(typeof global!==\"undefined\"){g=global}else if(typeof self!==\"undefined\"){g=self}else{g=this}g.soda = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require==\"function\"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error(\"Cannot find module '\"+o+\"'\");throw f.code=\"MODULE_NOT_FOUND\",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require==\"function\"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){\n(function (Buffer){\n// Generated by CoffeeScript 1.6.3\nvar Connection, Consumer, Dataset, EventEmitter, Operation, Producer, Query, addExpr, base64Lookup, eelib, expr, extend, handleLiteral, handleOrder, httpClient, isArray, isNumber, isString, rawToBase64, toBase64, toQuerystring,\n  __slice = [].slice,\n  __hasProp = {}.hasOwnProperty;\n\neelib = require('eventemitter2');\n\nEventEmitter = eelib.EventEmitter2 || eelib;\n\nhttpClient = require('superagent');\n\nisString = function(obj) {\n  return typeof obj === 'string';\n};\n\nisArray = function(obj) {\n  return Array.isArray(obj);\n};\n\nisNumber = function(obj) {\n  return !isNaN(parseFloat(obj));\n};\n\nextend = function() {\n  var k, source, sources, target, v, _i, _len;\n  target = arguments[0], sources = 2 <= arguments.length ? __slice.call(arguments, 1) : [];\n  for (_i = 0, _len = sources.length; _i < _len; _i++) {\n    source = sources[_i];\n    for (k in source) {\n      v = source[k];\n      target[k] = v;\n    }\n  }\n  return null;\n};\n\ntoBase64 = typeof Buffer !== \"undefined\" && Buffer !== null ? function(str) {\n  return new Buffer(str).toString('base64');\n} : (base64Lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='.split(''), rawToBase64 = typeof btoa !== \"undefined\" && btoa !== null ? btoa : function(str) {\n  var chr1, chr2, chr3, enc1, enc2, enc3, enc4, i, result;\n  result = [];\n  i = 0;\n  while (i < str.length) {\n    chr1 = str.charCodeAt(i++);\n    chr2 = str.charCodeAt(i++);\n    chr3 = str.charCodeAt(i++);\n    if (Math.max(chr1, chr2, chr3) > 0xFF) {\n      throw new Error('Invalid character!');\n    }\n    enc1 = chr1 >> 2;\n    enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);\n    enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);\n    enc4 = chr3 & 63;\n    if (isNaN(chr2)) {\n      enc3 = enc4 = 64;\n    } else if (isNaN(chr3)) {\n      enc4 = 64;\n    }\n    result.push(base64Lookup[enc1]);\n    result.push(base64Lookup[enc2]);\n    result.push(base64Lookup[enc3]);\n    result.push(base64Lookup[enc4]);\n  }\n  return result.join('');\n}, function(str) {\n  return rawToBase64(unescape(encodeURIComponent(str)));\n});\n\nhandleLiteral = function(literal) {\n  if (isString(literal)) {\n    return \"'\" + literal + \"'\";\n  } else if (isNumber(literal)) {\n    return literal;\n  } else {\n    return literal;\n  }\n};\n\nhandleOrder = function(order) {\n  if (/( asc$| desc$)/i.test(order)) {\n    return order;\n  } else {\n    return order + ' asc';\n  }\n};\n\naddExpr = function(target, args) {\n  var arg, k, v, _i, _len, _results;\n  _results = [];\n  for (_i = 0, _len = args.length; _i < _len; _i++) {\n    arg = args[_i];\n    if (isString(arg)) {\n      _results.push(target.push(arg));\n    } else {\n      _results.push((function() {\n        var _results1;\n        _results1 = [];\n        for (k in arg) {\n          v = arg[k];\n          _results1.push(target.push(\"\" + k + \" = \" + (handleLiteral(v))));\n        }\n        return _results1;\n      })());\n    }\n  }\n  return _results;\n};\n\nexpr = {\n  and: function() {\n    var clause, clauses;\n    clauses = 1 <= arguments.length ? __slice.call(arguments, 0) : [];\n    return ((function() {\n      var _i, _len, _results;\n      _results = [];\n      for (_i = 0, _len = clauses.length; _i < _len; _i++) {\n        clause = clauses[_i];\n        _results.push(\"(\" + clause + \")\");\n      }\n      return _results;\n    })()).join(' and ');\n  },\n  or: function() {\n    var clause, clauses;\n    clauses = 1 <= arguments.length ? __slice.call(arguments, 0) : [];\n    return ((function() {\n      var _i, _len, _results;\n      _results = [];\n      for (_i = 0, _len = clauses.length; _i < _len; _i++) {\n        clause = clauses[_i];\n        _results.push(\"(\" + clause + \")\");\n      }\n      return _results;\n    })()).join(' or ');\n  },\n  gt: function(column, literal) {\n    return \"\" + column + \" > \" + (handleLiteral(literal));\n  },\n  gte: function(column, literal) {\n    return \"\" + column + \" >= \" + (handleLiteral(literal));\n  },\n  lt: function(column, literal) {\n    return \"\" + column + \" < \" + (handleLiteral(literal));\n  },\n  lte: function(column, literal) {\n    return \"\" + column + \" <= \" + (handleLiteral(literal));\n  },\n  eq: function(column, literal) {\n    return \"\" + column + \" = \" + (handleLiteral(literal));\n  }\n};\n\ntoQuerystring = function(obj) {\n  var key, str, val;\n  str = [];\n  for (key in obj) {\n    if (!__hasProp.call(obj, key)) continue;\n    val = obj[key];\n    str.push(encodeURIComponent(key) + '=' + encodeURIComponent(val));\n  }\n  return str.join('&');\n};\n\nConnection = (function() {\n  function Connection(dataSite, sodaOpts) {\n    var _ref;\n    this.dataSite = dataSite;\n    this.sodaOpts = sodaOpts != null ? sodaOpts : {};\n    if (!/^[a-z0-9-_.]+(:[0-9]+)?$/i.test(this.dataSite)) {\n      throw new Error('dataSite does not appear to be valid! Please supply a domain name, eg data.seattle.gov');\n    }\n    this.emitterOpts = (_ref = this.sodaOpts.emitterOpts) != null ? _ref : {\n      wildcard: true,\n      delimiter: '.',\n      maxListeners: 15\n    };\n    this.networker = function(opts, data) {\n      var client, url,\n        _this = this;\n      url = \"https://\" + this.dataSite + opts.path;\n      client = httpClient(opts.method, url);\n      if (data != null) {\n        client.set('Accept', \"application/json\");\n      }\n      if (data != null) {\n        client.set('Content-type', \"application/json\");\n      }\n      if (this.sodaOpts.apiToken != null) {\n        client.set('X-App-Token', this.sodaOpts.apiToken);\n      }\n      if ((this.sodaOpts.username != null) && (this.sodaOpts.password != null)) {\n        client.set('Authorization', \"Basic \" + toBase64(\"\" + this.sodaOpts.username + \":\" + this.sodaOpts.password));\n      }\n      if (this.sodaOpts.accessToken != null) {\n        client.set('Authorization', \"OAuth \" + accessToken);\n      }\n      if (opts.query != null) {\n        client.query(opts.query);\n      }\n      if (data != null) {\n        client.send(data);\n      }\n      return function(responseHandler) {\n        return client.end(responseHandler || _this.getDefaultHandler());\n      };\n    };\n  }\n\n  Connection.prototype.getDefaultHandler = function() {\n    var emitter, handler;\n    this.emitter = emitter = new EventEmitter(this.emitterOpts);\n    return handler = function(error, response) {\n      var _ref;\n      if (response.ok) {\n        if (response.accepted) {\n          emitter.emit('progress', response.body);\n          setTimeout((function() {\n            return this.consumer.networker(opts)(handler);\n          }), 5000);\n        } else {\n          emitter.emit('success', response.body);\n        }\n      } else {\n        emitter.emit('error', (_ref = response.body) != null ? _ref : response.text);\n      }\n      return emitter.emit('complete', response);\n    };\n  };\n\n  return Connection;\n\n})();\n\nConsumer = (function() {\n  function Consumer(dataSite, sodaOpts) {\n    this.dataSite = dataSite;\n    this.sodaOpts = sodaOpts != null ? sodaOpts : {};\n    this.connection = new Connection(this.dataSite, this.sodaOpts);\n  }\n\n  Consumer.prototype.query = function() {\n    return new Query(this);\n  };\n\n  Consumer.prototype.getDataset = function(id) {\n    var emitter;\n    return emitter = new EventEmitter(this.emitterOpts);\n  };\n\n  return Consumer;\n\n})();\n\nProducer = (function() {\n  function Producer(dataSite, sodaOpts) {\n    this.dataSite = dataSite;\n    this.sodaOpts = sodaOpts != null ? sodaOpts : {};\n    this.connection = new Connection(this.dataSite, this.sodaOpts);\n  }\n\n  Producer.prototype.operation = function() {\n    return new Operation(this);\n  };\n\n  return Producer;\n\n})();\n\nOperation = (function() {\n  function Operation(producer) {\n    this.producer = producer;\n  }\n\n  Operation.prototype.withDataset = function(datasetId) {\n    this._datasetId = datasetId;\n    return this;\n  };\n\n  Operation.prototype.truncate = function() {\n    var opts;\n    opts = {\n      method: 'delete'\n    };\n    opts.path = \"/resource/\" + this._datasetId;\n    return this._exec(opts);\n  };\n\n  Operation.prototype.add = function(data) {\n    var obj, opts, _data, _i, _len;\n    opts = {\n      method: 'post'\n    };\n    opts.path = \"/resource/\" + this._datasetId;\n    _data = JSON.parse(JSON.stringify(data));\n    delete _data[':id'];\n    delete _data[':delete'];\n    for (_i = 0, _len = _data.length; _i < _len; _i++) {\n      obj = _data[_i];\n      delete obj[':id'];\n      delete obj[':delete'];\n    }\n    return this._exec(opts, _data);\n  };\n\n  Operation.prototype[\"delete\"] = function(id) {\n    var opts;\n    opts = {\n      method: 'delete'\n    };\n    opts.path = \"/resource/\" + this._datasetId + \"/\" + id;\n    return this._exec(opts);\n  };\n\n  Operation.prototype.update = function(id, data) {\n    var opts;\n    opts = {\n      method: 'post'\n    };\n    opts.path = \"/resource/\" + this._datasetId + \"/\" + id;\n    return this._exec(opts, data);\n  };\n\n  Operation.prototype.replace = function(id, data) {\n    var opts;\n    opts = {\n      method: 'put'\n    };\n    opts.path = \"/resource/\" + this._datasetId + \"/\" + id;\n    return this._exec(opts, data);\n  };\n\n  Operation.prototype.upsert = function(data) {\n    var opts;\n    opts = {\n      method: 'post'\n    };\n    opts.path = \"/resource/\" + this._datasetId;\n    return this._exec(opts, data);\n  };\n\n  Operation.prototype._exec = function(opts, data) {\n    if (this._datasetId == null) {\n      throw new Error('no dataset given to work against!');\n    }\n    this.producer.connection.networker(opts, data)();\n    return this.producer.connection.emitter;\n  };\n\n  return Operation;\n\n})();\n\nQuery = (function() {\n  function Query(consumer) {\n    this.consumer = consumer;\n    this._select = [];\n    this._where = [];\n    this._group = [];\n    this._having = [];\n    this._order = [];\n    this._offset = this._limit = this._q = null;\n  }\n\n  Query.prototype.withDataset = function(datasetId) {\n    this._datasetId = datasetId;\n    return this;\n  };\n\n  Query.prototype.soql = function(query) {\n    this._soql = query;\n    return this;\n  };\n\n  Query.prototype.select = function() {\n    var select, selects, _i, _len;\n    selects = 1 <= arguments.length ? __slice.call(arguments, 0) : [];\n    for (_i = 0, _len = selects.length; _i < _len; _i++) {\n      select = selects[_i];\n      this._select.push(select);\n    }\n    return this;\n  };\n\n  Query.prototype.where = function() {\n    var args;\n    args = 1 <= arguments.length ? __slice.call(arguments, 0) : [];\n    addExpr(this._where, args);\n    return this;\n  };\n\n  Query.prototype.having = function() {\n    var args;\n    args = 1 <= arguments.length ? __slice.call(arguments, 0) : [];\n    addExpr(this._having, args);\n    return this;\n  };\n\n  Query.prototype.group = function() {\n    var group, groups, _i, _len;\n    groups = 1 <= arguments.length ? __slice.call(arguments, 0) : [];\n    for (_i = 0, _len = groups.length; _i < _len; _i++) {\n      group = groups[_i];\n      this._group.push(group);\n    }\n    return this;\n  };\n\n  Query.prototype.order = function() {\n    var order, orders, _i, _len;\n    orders = 1 <= arguments.length ? __slice.call(arguments, 0) : [];\n    for (_i = 0, _len = orders.length; _i < _len; _i++) {\n      order = orders[_i];\n      this._order.push(handleOrder(order));\n    }\n    return this;\n  };\n\n  Query.prototype.offset = function(offset) {\n    this._offset = offset;\n    return this;\n  };\n\n  Query.prototype.limit = function(limit) {\n    this._limit = limit;\n    return this;\n  };\n\n  Query.prototype.q = function(q) {\n    this._q = q;\n    return this;\n  };\n\n  Query.prototype.getOpts = function() {\n    var k, opts, queryComponents, v;\n    opts = {\n      method: 'get'\n    };\n    if (this._datasetId == null) {\n      throw new Error('no dataset given to work against!');\n    }\n    opts.path = \"/resource/\" + this._datasetId + \".json\";\n    queryComponents = this._buildQueryComponents();\n    opts.query = {};\n    for (k in queryComponents) {\n      v = queryComponents[k];\n      opts.query['$' + k] = v;\n    }\n    return opts;\n  };\n\n  Query.prototype.getURL = function() {\n    var opts, query;\n    opts = this.getOpts();\n    query = toQuerystring(opts.query);\n    return (\"https://\" + this.consumer.dataSite + opts.path) + (query ? \"?\" + query : \"\");\n  };\n\n  Query.prototype.getRows = function() {\n    var opts;\n    opts = this.getOpts();\n    this.consumer.connection.networker(opts)();\n    return this.consumer.connection.emitter;\n  };\n\n  Query.prototype._buildQueryComponents = function() {\n    var query;\n    query = {};\n    if (this._soql != null) {\n      query.query = this._soql;\n    } else {\n      if (this._select.length > 0) {\n        query.select = this._select.join(', ');\n      }\n      if (this._where.length > 0) {\n        query.where = expr.and.apply(this, this._where);\n      }\n      if (this._group.length > 0) {\n        query.group = this._group.join(', ');\n      }\n      if (this._having.length > 0) {\n        if (!(this._group.length > 0)) {\n          throw new Error('Having provided without group by!');\n        }\n        query.having = expr.and.apply(this, this._having);\n      }\n      if (this._order.length > 0) {\n        query.order = this._order.join(', ');\n      }\n      if (isNumber(this._offset)) {\n        query.offset = this._offset;\n      }\n      if (isNumber(this._limit)) {\n        query.limit = this._limit;\n      }\n      if (this._q) {\n        query.q = this._q;\n      }\n    }\n    return query;\n  };\n\n  return Query;\n\n})();\n\nDataset = (function() {\n  function Dataset(data, client) {\n    this.data = data;\n    this.client = client;\n  }\n\n  return Dataset;\n\n})();\n\nextend(typeof exports !== \"undefined\" && exports !== null ? exports : this.soda, {\n  Consumer: Consumer,\n  Producer: Producer,\n  expr: expr,\n  _internal: {\n    Connection: Connection,\n    Query: Query,\n    Operation: Operation,\n    util: {\n      toBase64: toBase64,\n      handleLiteral: handleLiteral,\n      handleOrder: handleOrder\n    }\n  }\n});\n\n}).call(this,require(\"buffer\").Buffer)\n},{\"buffer\":3,\"eventemitter2\":6,\"superagent\":9}],2:[function(require,module,exports){\nvar lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\n\n;(function (exports) {\n\t'use strict';\n\n  var Arr = (typeof Uint8Array !== 'undefined')\n    ? Uint8Array\n    : Array\n\n\tvar PLUS   = '+'.charCodeAt(0)\n\tvar SLASH  = '/'.charCodeAt(0)\n\tvar NUMBER = '0'.charCodeAt(0)\n\tvar LOWER  = 'a'.charCodeAt(0)\n\tvar UPPER  = 'A'.charCodeAt(0)\n\tvar PLUS_URL_SAFE = '-'.charCodeAt(0)\n\tvar SLASH_URL_SAFE = '_'.charCodeAt(0)\n\n\tfunction decode (elt) {\n\t\tvar code = elt.charCodeAt(0)\n\t\tif (code === PLUS ||\n\t\t    code === PLUS_URL_SAFE)\n\t\t\treturn 62 // '+'\n\t\tif (code === SLASH ||\n\t\t    code === SLASH_URL_SAFE)\n\t\t\treturn 63 // '/'\n\t\tif (code < NUMBER)\n\t\t\treturn -1 //no match\n\t\tif (code < NUMBER + 10)\n\t\t\treturn code - NUMBER + 26 + 26\n\t\tif (code < UPPER + 26)\n\t\t\treturn code - UPPER\n\t\tif (code < LOWER + 26)\n\t\t\treturn code - LOWER + 26\n\t}\n\n\tfunction b64ToByteArray (b64) {\n\t\tvar i, j, l, tmp, placeHolders, arr\n\n\t\tif (b64.length % 4 > 0) {\n\t\t\tthrow new Error('Invalid string. Length must be a multiple of 4')\n\t\t}\n\n\t\t// the number of equal signs (place holders)\n\t\t// if there are two placeholders, than the two characters before it\n\t\t// represent one byte\n\t\t// if there is only one, then the three characters before it represent 2 bytes\n\t\t// this is just a cheap hack to not do indexOf twice\n\t\tvar len = b64.length\n\t\tplaceHolders = '=' === b64.charAt(len - 2) ? 2 : '=' === b64.charAt(len - 1) ? 1 : 0\n\n\t\t// base64 is 4/3 + up to two characters of the original data\n\t\tarr = new Arr(b64.length * 3 / 4 - placeHolders)\n\n\t\t// if there are placeholders, only get up to the last complete 4 chars\n\t\tl = placeHolders > 0 ? b64.length - 4 : b64.length\n\n\t\tvar L = 0\n\n\t\tfunction push (v) {\n\t\t\tarr[L++] = v\n\t\t}\n\n\t\tfor (i = 0, j = 0; i < l; i += 4, j += 3) {\n\t\t\ttmp = (decode(b64.charAt(i)) << 18) | (decode(b64.charAt(i + 1)) << 12) | (decode(b64.charAt(i + 2)) << 6) | decode(b64.charAt(i + 3))\n\t\t\tpush((tmp & 0xFF0000) >> 16)\n\t\t\tpush((tmp & 0xFF00) >> 8)\n\t\t\tpush(tmp & 0xFF)\n\t\t}\n\n\t\tif (placeHolders === 2) {\n\t\t\ttmp = (decode(b64.charAt(i)) << 2) | (decode(b64.charAt(i + 1)) >> 4)\n\t\t\tpush(tmp & 0xFF)\n\t\t} else if (placeHolders === 1) {\n\t\t\ttmp = (decode(b64.charAt(i)) << 10) | (decode(b64.charAt(i + 1)) << 4) | (decode(b64.charAt(i + 2)) >> 2)\n\t\t\tpush((tmp >> 8) & 0xFF)\n\t\t\tpush(tmp & 0xFF)\n\t\t}\n\n\t\treturn arr\n\t}\n\n\tfunction uint8ToBase64 (uint8) {\n\t\tvar i,\n\t\t\textraBytes = uint8.length % 3, // if we have 1 byte left, pad 2 bytes\n\t\t\toutput = \"\",\n\t\t\ttemp, length\n\n\t\tfunction encode (num) {\n\t\t\treturn lookup.charAt(num)\n\t\t}\n\n\t\tfunction tripletToBase64 (num) {\n\t\t\treturn encode(num >> 18 & 0x3F) + encode(num >> 12 & 0x3F) + encode(num >> 6 & 0x3F) + encode(num & 0x3F)\n\t\t}\n\n\t\t// go through the array every three bytes, we'll deal with trailing stuff later\n\t\tfor (i = 0, length = uint8.length - extraBytes; i < length; i += 3) {\n\t\t\ttemp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2])\n\t\t\toutput += tripletToBase64(temp)\n\t\t}\n\n\t\t// pad the end with zeros, but make sure to not forget the extra bytes\n\t\tswitch (extraBytes) {\n\t\t\tcase 1:\n\t\t\t\ttemp = uint8[uint8.length - 1]\n\t\t\t\toutput += encode(temp >> 2)\n\t\t\t\toutput += encode((temp << 4) & 0x3F)\n\t\t\t\toutput += '=='\n\t\t\t\tbreak\n\t\t\tcase 2:\n\t\t\t\ttemp = (uint8[uint8.length - 2] << 8) + (uint8[uint8.length - 1])\n\t\t\t\toutput += encode(temp >> 10)\n\t\t\t\toutput += encode((temp >> 4) & 0x3F)\n\t\t\t\toutput += encode((temp << 2) & 0x3F)\n\t\t\t\toutput += '='\n\t\t\t\tbreak\n\t\t}\n\n\t\treturn output\n\t}\n\n\texports.toByteArray = b64ToByteArray\n\texports.fromByteArray = uint8ToBase64\n}(typeof exports === 'undefined' ? (this.base64js = {}) : exports))\n\n},{}],3:[function(require,module,exports){\n(function (global){\n/*!\n * The buffer module from node.js, for the browser.\n *\n * @author   Feross Aboukhadijeh <feross@feross.org> <http://feross.org>\n * @license  MIT\n */\n/* eslint-disable no-proto */\n\n'use strict'\n\nvar base64 = require('base64-js')\nvar ieee754 = require('ieee754')\nvar isArray = require('isarray')\n\nexports.Buffer = Buffer\nexports.SlowBuffer = SlowBuffer\nexports.INSPECT_MAX_BYTES = 50\nBuffer.poolSize = 8192 // not used by this implementation\n\nvar rootParent = {}\n\n/**\n * If `Buffer.TYPED_ARRAY_SUPPORT`:\n *   === true    Use Uint8Array implementation (fastest)\n *   === false   Use Object implementation (most compatible, even IE6)\n *\n * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,\n * Opera 11.6+, iOS 4.2+.\n *\n * Due to various browser bugs, sometimes the Object implementation will be used even\n * when the browser supports typed arrays.\n *\n * Note:\n *\n *   - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,\n *     See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.\n *\n *   - Safari 5-7 lacks support for changing the `Object.prototype.constructor` property\n *     on objects.\n *\n *   - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.\n *\n *   - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of\n *     incorrect length in some situations.\n\n * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they\n * get the Object implementation, which is slower but behaves correctly.\n */\nBuffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined\n  ? global.TYPED_ARRAY_SUPPORT\n  : typedArraySupport()\n\nfunction typedArraySupport () {\n  function Bar () {}\n  try {\n    var arr = new Uint8Array(1)\n    arr.foo = function () { return 42 }\n    arr.constructor = Bar\n    return arr.foo() === 42 && // typed array instances can be augmented\n        arr.constructor === Bar && // constructor can be set\n        typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`\n        arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`\n  } catch (e) {\n    return false\n  }\n}\n\nfunction kMaxLength () {\n  return Buffer.TYPED_ARRAY_SUPPORT\n    ? 0x7fffffff\n    : 0x3fffffff\n}\n\n/**\n * Class: Buffer\n * =============\n *\n * The Buffer constructor returns instances of `Uint8Array` that are augmented\n * with function properties for all the node `Buffer` API functions. We use\n * `Uint8Array` so that square bracket notation works as expected -- it returns\n * a single octet.\n *\n * By augmenting the instances, we can avoid modifying the `Uint8Array`\n * prototype.\n */\nfunction Buffer (arg) {\n  if (!(this instanceof Buffer)) {\n    // Avoid going through an ArgumentsAdaptorTrampoline in the common case.\n    if (arguments.length > 1) return new Buffer(arg, arguments[1])\n    return new Buffer(arg)\n  }\n\n  if (!Buffer.TYPED_ARRAY_SUPPORT) {\n    this.length = 0\n    this.parent = undefined\n  }\n\n  // Common case.\n  if (typeof arg === 'number') {\n    return fromNumber(this, arg)\n  }\n\n  // Slightly less common case.\n  if (typeof arg === 'string') {\n    return fromString(this, arg, arguments.length > 1 ? arguments[1] : 'utf8')\n  }\n\n  // Unusual.\n  return fromObject(this, arg)\n}\n\nfunction fromNumber (that, length) {\n  that = allocate(that, length < 0 ? 0 : checked(length) | 0)\n  if (!Buffer.TYPED_ARRAY_SUPPORT) {\n    for (var i = 0; i < length; i++) {\n      that[i] = 0\n    }\n  }\n  return that\n}\n\nfunction fromString (that, string, encoding) {\n  if (typeof encoding !== 'string' || encoding === '') encoding = 'utf8'\n\n  // Assumption: byteLength() return value is always < kMaxLength.\n  var length = byteLength(string, encoding) | 0\n  that = allocate(that, length)\n\n  that.write(string, encoding)\n  return that\n}\n\nfunction fromObject (that, object) {\n  if (Buffer.isBuffer(object)) return fromBuffer(that, object)\n\n  if (isArray(object)) return fromArray(that, object)\n\n  if (object == null) {\n    throw new TypeError('must start with number, buffer, array or string')\n  }\n\n  if (typeof ArrayBuffer !== 'undefined') {\n    if (object.buffer instanceof ArrayBuffer) {\n      return fromTypedArray(that, object)\n    }\n    if (object instanceof ArrayBuffer) {\n      return fromArrayBuffer(that, object)\n    }\n  }\n\n  if (object.length) return fromArrayLike(that, object)\n\n  return fromJsonObject(that, object)\n}\n\nfunction fromBuffer (that, buffer) {\n  var length = checked(buffer.length) | 0\n  that = allocate(that, length)\n  buffer.copy(that, 0, 0, length)\n  return that\n}\n\nfunction fromArray (that, array) {\n  var length = checked(array.length) | 0\n  that = allocate(that, length)\n  for (var i = 0; i < length; i += 1) {\n    that[i] = array[i] & 255\n  }\n  return that\n}\n\n// Duplicate of fromArray() to keep fromArray() monomorphic.\nfunction fromTypedArray (that, array) {\n  var length = checked(array.length) | 0\n  that = allocate(that, length)\n  // Truncating the elements is probably not what people expect from typed\n  // arrays with BYTES_PER_ELEMENT > 1 but it's compatible with the behavior\n  // of the old Buffer constructor.\n  for (var i = 0; i < length; i += 1) {\n    that[i] = array[i] & 255\n  }\n  return that\n}\n\nfunction fromArrayBuffer (that, array) {\n  if (Buffer.TYPED_ARRAY_SUPPORT) {\n    // Return an augmented `Uint8Array` instance, for best performance\n    array.byteLength\n    that = Buffer._augment(new Uint8Array(array))\n  } else {\n    // Fallback: Return an object instance of the Buffer class\n    that = fromTypedArray(that, new Uint8Array(array))\n  }\n  return that\n}\n\nfunction fromArrayLike (that, array) {\n  var length = checked(array.length) | 0\n  that = allocate(that, length)\n  for (var i = 0; i < length; i += 1) {\n    that[i] = array[i] & 255\n  }\n  return that\n}\n\n// Deserialize { type: 'Buffer', data: [1,2,3,...] } into a Buffer object.\n// Returns a zero-length buffer for inputs that don't conform to the spec.\nfunction fromJsonObject (that, object) {\n  var array\n  var length = 0\n\n  if (object.type === 'Buffer' && isArray(object.data)) {\n    array = object.data\n    length = checked(array.length) | 0\n  }\n  that = allocate(that, length)\n\n  for (var i = 0; i < length; i += 1) {\n    that[i] = array[i] & 255\n  }\n  return that\n}\n\nif (Buffer.TYPED_ARRAY_SUPPORT) {\n  Buffer.prototype.__proto__ = Uint8Array.prototype\n  Buffer.__proto__ = Uint8Array\n} else {\n  // pre-set for values that may exist in the future\n  Buffer.prototype.length = undefined\n  Buffer.prototype.parent = undefined\n}\n\nfunction allocate (that, length) {\n  if (Buffer.TYPED_ARRAY_SUPPORT) {\n    // Return an augmented `Uint8Array` instance, for best performance\n    that = Buffer._augment(new Uint8Array(length))\n    that.__proto__ = Buffer.prototype\n  } else {\n    // Fallback: Return an object instance of the Buffer class\n    that.length = length\n    that._isBuffer = true\n  }\n\n  var fromPool = length !== 0 && length <= Buffer.poolSize >>> 1\n  if (fromPool) that.parent = rootParent\n\n  return that\n}\n\nfunction checked (length) {\n  // Note: cannot use `length < kMaxLength` here because that fails when\n  // length is NaN (which is otherwise coerced to zero.)\n  if (length >= kMaxLength()) {\n    throw new RangeError('Attempt to allocate Buffer larger than maximum ' +\n                         'size: 0x' + kMaxLength().toString(16) + ' bytes')\n  }\n  return length | 0\n}\n\nfunction SlowBuffer (subject, encoding) {\n  if (!(this instanceof SlowBuffer)) return new SlowBuffer(subject, encoding)\n\n  var buf = new Buffer(subject, encoding)\n  delete buf.parent\n  return buf\n}\n\nBuffer.isBuffer = function isBuffer (b) {\n  return !!(b != null && b._isBuffer)\n}\n\nBuffer.compare = function compare (a, b) {\n  if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {\n    throw new TypeError('Arguments must be Buffers')\n  }\n\n  if (a === b) return 0\n\n  var x = a.length\n  var y = b.length\n\n  var i = 0\n  var len = Math.min(x, y)\n  while (i < len) {\n    if (a[i] !== b[i]) break\n\n    ++i\n  }\n\n  if (i !== len) {\n    x = a[i]\n    y = b[i]\n  }\n\n  if (x < y) return -1\n  if (y < x) return 1\n  return 0\n}\n\nBuffer.isEncoding = function isEncoding (encoding) {\n  switch (String(encoding).toLowerCase()) {\n    case 'hex':\n    case 'utf8':\n    case 'utf-8':\n    case 'ascii':\n    case 'binary':\n    case 'base64':\n    case 'raw':\n    case 'ucs2':\n    case 'ucs-2':\n    case 'utf16le':\n    case 'utf-16le':\n      return true\n    default:\n      return false\n  }\n}\n\nBuffer.concat = function concat (list, length) {\n  if (!isArray(list)) throw new TypeError('list argument must be an Array of Buffers.')\n\n  if (list.length === 0) {\n    return new Buffer(0)\n  }\n\n  var i\n  if (length === undefined) {\n    length = 0\n    for (i = 0; i < list.length; i++) {\n      length += list[i].length\n    }\n  }\n\n  var buf = new Buffer(length)\n  var pos = 0\n  for (i = 0; i < list.length; i++) {\n    var item = list[i]\n    item.copy(buf, pos)\n    pos += item.length\n  }\n  return buf\n}\n\nfunction byteLength (string, encoding) {\n  if (typeof string !== 'string') string = '' + string\n\n  var len = string.length\n  if (len === 0) return 0\n\n  // Use a for loop to avoid recursion\n  var loweredCase = false\n  for (;;) {\n    switch (encoding) {\n      case 'ascii':\n      case 'binary':\n      // Deprecated\n      case 'raw':\n      case 'raws':\n        return len\n      case 'utf8':\n      case 'utf-8':\n        return utf8ToBytes(string).length\n      case 'ucs2':\n      case 'ucs-2':\n      case 'utf16le':\n      case 'utf-16le':\n        return len * 2\n      case 'hex':\n        return len >>> 1\n      case 'base64':\n        return base64ToBytes(string).length\n      default:\n        if (loweredCase) return utf8ToBytes(string).length // assume utf8\n        encoding = ('' + encoding).toLowerCase()\n        loweredCase = true\n    }\n  }\n}\nBuffer.byteLength = byteLength\n\nfunction slowToString (encoding, start, end) {\n  var loweredCase = false\n\n  start = start | 0\n  end = end === undefined || end === Infinity ? this.length : end | 0\n\n  if (!encoding) encoding = 'utf8'\n  if (start < 0) start = 0\n  if (end > this.length) end = this.length\n  if (end <= start) return ''\n\n  while (true) {\n    switch (encoding) {\n      case 'hex':\n        return hexSlice(this, start, end)\n\n      case 'utf8':\n      case 'utf-8':\n        return utf8Slice(this, start, end)\n\n      case 'ascii':\n        return asciiSlice(this, start, end)\n\n      case 'binary':\n        return binarySlice(this, start, end)\n\n      case 'base64':\n        return base64Slice(this, start, end)\n\n      case 'ucs2':\n      case 'ucs-2':\n      case 'utf16le':\n      case 'utf-16le':\n        return utf16leSlice(this, start, end)\n\n      default:\n        if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)\n        encoding = (encoding + '').toLowerCase()\n        loweredCase = true\n    }\n  }\n}\n\nBuffer.prototype.toString = function toString () {\n  var length = this.length | 0\n  if (length === 0) return ''\n  if (arguments.length === 0) return utf8Slice(this, 0, length)\n  return slowToString.apply(this, arguments)\n}\n\nBuffer.prototype.equals = function equals (b) {\n  if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')\n  if (this === b) return true\n  return Buffer.compare(this, b) === 0\n}\n\nBuffer.prototype.inspect = function inspect () {\n  var str = ''\n  var max = exports.INSPECT_MAX_BYTES\n  if (this.length > 0) {\n    str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')\n    if (this.length > max) str += ' ... '\n  }\n  return '<Buffer ' + str + '>'\n}\n\nBuffer.prototype.compare = function compare (b) {\n  if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')\n  if (this === b) return 0\n  return Buffer.compare(this, b)\n}\n\nBuffer.prototype.indexOf = function indexOf (val, byteOffset) {\n  if (byteOffset > 0x7fffffff) byteOffset = 0x7fffffff\n  else if (byteOffset < -0x80000000) byteOffset = -0x80000000\n  byteOffset >>= 0\n\n  if (this.length === 0) return -1\n  if (byteOffset >= this.length) return -1\n\n  // Negative offsets start from the end of the buffer\n  if (byteOffset < 0) byteOffset = Math.max(this.length + byteOffset, 0)\n\n  if (typeof val === 'string') {\n    if (val.length === 0) return -1 // special case: looking for empty string always fails\n    return String.prototype.indexOf.call(this, val, byteOffset)\n  }\n  if (Buffer.isBuffer(val)) {\n    return arrayIndexOf(this, val, byteOffset)\n  }\n  if (typeof val === 'number') {\n    if (Buffer.TYPED_ARRAY_SUPPORT && Uint8Array.prototype.indexOf === 'function') {\n      return Uint8Array.prototype.indexOf.call(this, val, byteOffset)\n    }\n    return arrayIndexOf(this, [ val ], byteOffset)\n  }\n\n  function arrayIndexOf (arr, val, byteOffset) {\n    var foundIndex = -1\n    for (var i = 0; byteOffset + i < arr.length; i++) {\n      if (arr[byteOffset + i] === val[foundIndex === -1 ? 0 : i - foundIndex]) {\n        if (foundIndex === -1) foundIndex = i\n        if (i - foundIndex + 1 === val.length) return byteOffset + foundIndex\n      } else {\n        foundIndex = -1\n      }\n    }\n    return -1\n  }\n\n  throw new TypeError('val must be string, number or Buffer')\n}\n\n// `get` is deprecated\nBuffer.prototype.get = function get (offset) {\n  console.log('.get() is deprecated. Access using array indexes instead.')\n  return this.readUInt8(offset)\n}\n\n// `set` is deprecated\nBuffer.prototype.set = function set (v, offset) {\n  console.log('.set() is deprecated. Access using array indexes instead.')\n  return this.writeUInt8(v, offset)\n}\n\nfunction hexWrite (buf, string, offset, length) {\n  offset = Number(offset) || 0\n  var remaining = buf.length - offset\n  if (!length) {\n    length = remaining\n  } else {\n    length = Number(length)\n    if (length > remaining) {\n      length = remaining\n    }\n  }\n\n  // must be an even number of digits\n  var strLen = string.length\n  if (strLen % 2 !== 0) throw new Error('Invalid hex string')\n\n  if (length > strLen / 2) {\n    length = strLen / 2\n  }\n  for (var i = 0; i < length; i++) {\n    var parsed = parseInt(string.substr(i * 2, 2), 16)\n    if (isNaN(parsed)) throw new Error('Invalid hex string')\n    buf[offset + i] = parsed\n  }\n  return i\n}\n\nfunction utf8Write (buf, string, offset, length) {\n  return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)\n}\n\nfunction asciiWrite (buf, string, offset, length) {\n  return blitBuffer(asciiToBytes(string), buf, offset, length)\n}\n\nfunction binaryWrite (buf, string, offset, length) {\n  return asciiWrite(buf, string, offset, length)\n}\n\nfunction base64Write (buf, string, offset, length) {\n  return blitBuffer(base64ToBytes(string), buf, offset, length)\n}\n\nfunction ucs2Write (buf, string, offset, length) {\n  return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)\n}\n\nBuffer.prototype.write = function write (string, offset, length, encoding) {\n  // Buffer#write(string)\n  if (offset === undefined) {\n    encoding = 'utf8'\n    length = this.length\n    offset = 0\n  // Buffer#write(string, encoding)\n  } else if (length === undefined && typeof offset === 'string') {\n    encoding = offset\n    length = this.length\n    offset = 0\n  // Buffer#write(string, offset[, length][, encoding])\n  } else if (isFinite(offset)) {\n    offset = offset | 0\n    if (isFinite(length)) {\n      length = length | 0\n      if (encoding === undefined) encoding = 'utf8'\n    } else {\n      encoding = length\n      length = undefined\n    }\n  // legacy write(string, encoding, offset, length) - remove in v0.13\n  } else {\n    var swap = encoding\n    encoding = offset\n    offset = length | 0\n    length = swap\n  }\n\n  var remaining = this.length - offset\n  if (length === undefined || length > remaining) length = remaining\n\n  if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {\n    throw new RangeError('attempt to write outside buffer bounds')\n  }\n\n  if (!encoding) encoding = 'utf8'\n\n  var loweredCase = false\n  for (;;) {\n    switch (encoding) {\n      case 'hex':\n        return hexWrite(this, string, offset, length)\n\n      case 'utf8':\n      case 'utf-8':\n        return utf8Write(this, string, offset, length)\n\n      case 'ascii':\n        return asciiWrite(this, string, offset, length)\n\n      case 'binary':\n        return binaryWrite(this, string, offset, length)\n\n      case 'base64':\n        // Warning: maxLength not taken into account in base64Write\n        return base64Write(this, string, offset, length)\n\n      case 'ucs2':\n      case 'ucs-2':\n      case 'utf16le':\n      case 'utf-16le':\n        return ucs2Write(this, string, offset, length)\n\n      default:\n        if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)\n        encoding = ('' + encoding).toLowerCase()\n        loweredCase = true\n    }\n  }\n}\n\nBuffer.prototype.toJSON = function toJSON () {\n  return {\n    type: 'Buffer',\n    data: Array.prototype.slice.call(this._arr || this, 0)\n  }\n}\n\nfunction base64Slice (buf, start, end) {\n  if (start === 0 && end === buf.length) {\n    return base64.fromByteArray(buf)\n  } else {\n    return base64.fromByteArray(buf.slice(start, end))\n  }\n}\n\nfunction utf8Slice (buf, start, end) {\n  end = Math.min(buf.length, end)\n  var res = []\n\n  var i = start\n  while (i < end) {\n    var firstByte = buf[i]\n    var codePoint = null\n    var bytesPerSequence = (firstByte > 0xEF) ? 4\n      : (firstByte > 0xDF) ? 3\n      : (firstByte > 0xBF) ? 2\n      : 1\n\n    if (i + bytesPerSequence <= end) {\n      var secondByte, thirdByte, fourthByte, tempCodePoint\n\n      switch (bytesPerSequence) {\n        case 1:\n          if (firstByte < 0x80) {\n            codePoint = firstByte\n          }\n          break\n        case 2:\n          secondByte = buf[i + 1]\n          if ((secondByte & 0xC0) === 0x80) {\n            tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)\n            if (tempCodePoint > 0x7F) {\n              codePoint = tempCodePoint\n            }\n          }\n          break\n        case 3:\n          secondByte = buf[i + 1]\n          thirdByte = buf[i + 2]\n          if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {\n            tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)\n            if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {\n              codePoint = tempCodePoint\n            }\n          }\n          break\n        case 4:\n          secondByte = buf[i + 1]\n          thirdByte = buf[i + 2]\n          fourthByte = buf[i + 3]\n          if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {\n            tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)\n            if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {\n              codePoint = tempCodePoint\n            }\n          }\n      }\n    }\n\n    if (codePoint === null) {\n      // we did not generate a valid codePoint so insert a\n      // replacement char (U+FFFD) and advance only 1 byte\n      codePoint = 0xFFFD\n      bytesPerSequence = 1\n    } else if (codePoint > 0xFFFF) {\n      // encode to utf16 (surrogate pair dance)\n      codePoint -= 0x10000\n      res.push(codePoint >>> 10 & 0x3FF | 0xD800)\n      codePoint = 0xDC00 | codePoint & 0x3FF\n    }\n\n    res.push(codePoint)\n    i += bytesPerSequence\n  }\n\n  return decodeCodePointsArray(res)\n}\n\n// Based on http://stackoverflow.com/a/22747272/680742, the browser with\n// the lowest limit is Chrome, with 0x10000 args.\n// We go 1 magnitude less, for safety\nvar MAX_ARGUMENTS_LENGTH = 0x1000\n\nfunction decodeCodePointsArray (codePoints) {\n  var len = codePoints.length\n  if (len <= MAX_ARGUMENTS_LENGTH) {\n    return String.fromCharCode.apply(String, codePoints) // avoid extra slice()\n  }\n\n  // Decode in chunks to avoid \"call stack size exceeded\".\n  var res = ''\n  var i = 0\n  while (i < len) {\n    res += String.fromCharCode.apply(\n      String,\n      codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)\n    )\n  }\n  return res\n}\n\nfunction asciiSlice (buf, start, end) {\n  var ret = ''\n  end = Math.min(buf.length, end)\n\n  for (var i = start; i < end; i++) {\n    ret += String.fromCharCode(buf[i] & 0x7F)\n  }\n  return ret\n}\n\nfunction binarySlice (buf, start, end) {\n  var ret = ''\n  end = Math.min(buf.length, end)\n\n  for (var i = start; i < end; i++) {\n    ret += String.fromCharCode(buf[i])\n  }\n  return ret\n}\n\nfunction hexSlice (buf, start, end) {\n  var len = buf.length\n\n  if (!start || start < 0) start = 0\n  if (!end || end < 0 || end > len) end = len\n\n  var out = ''\n  for (var i = start; i < end; i++) {\n    out += toHex(buf[i])\n  }\n  return out\n}\n\nfunction utf16leSlice (buf, start, end) {\n  var bytes = buf.slice(start, end)\n  var res = ''\n  for (var i = 0; i < bytes.length; i += 2) {\n    res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)\n  }\n  return res\n}\n\nBuffer.prototype.slice = function slice (start, end) {\n  var len = this.length\n  start = ~~start\n  end = end === undefined ? len : ~~end\n\n  if (start < 0) {\n    start += len\n    if (start < 0) start = 0\n  } else if (start > len) {\n    start = len\n  }\n\n  if (end < 0) {\n    end += len\n    if (end < 0) end = 0\n  } else if (end > len) {\n    end = len\n  }\n\n  if (end < start) end = start\n\n  var newBuf\n  if (Buffer.TYPED_ARRAY_SUPPORT) {\n    newBuf = Buffer._augment(this.subarray(start, end))\n  } else {\n    var sliceLen = end - start\n    newBuf = new Buffer(sliceLen, undefined)\n    for (var i = 0; i < sliceLen; i++) {\n      newBuf[i] = this[i + start]\n    }\n  }\n\n  if (newBuf.length) newBuf.parent = this.parent || this\n\n  return newBuf\n}\n\n/*\n * Need to make sure that buffer isn't trying to write out of bounds.\n */\nfunction checkOffset (offset, ext, length) {\n  if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')\n  if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')\n}\n\nBuffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {\n  offset = offset | 0\n  byteLength = byteLength | 0\n  if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n  var val = this[offset]\n  var mul = 1\n  var i = 0\n  while (++i < byteLength && (mul *= 0x100)) {\n    val += this[offset + i] * mul\n  }\n\n  return val\n}\n\nBuffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {\n  offset = offset | 0\n  byteLength = byteLength | 0\n  if (!noAssert) {\n    checkOffset(offset, byteLength, this.length)\n  }\n\n  var val = this[offset + --byteLength]\n  var mul = 1\n  while (byteLength > 0 && (mul *= 0x100)) {\n    val += this[offset + --byteLength] * mul\n  }\n\n  return val\n}\n\nBuffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {\n  if (!noAssert) checkOffset(offset, 1, this.length)\n  return this[offset]\n}\n\nBuffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {\n  if (!noAssert) checkOffset(offset, 2, this.length)\n  return this[offset] | (this[offset + 1] << 8)\n}\n\nBuffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {\n  if (!noAssert) checkOffset(offset, 2, this.length)\n  return (this[offset] << 8) | this[offset + 1]\n}\n\nBuffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {\n  if (!noAssert) checkOffset(offset, 4, this.length)\n\n  return ((this[offset]) |\n      (this[offset + 1] << 8) |\n      (this[offset + 2] << 16)) +\n      (this[offset + 3] * 0x1000000)\n}\n\nBuffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {\n  if (!noAssert) checkOffset(offset, 4, this.length)\n\n  return (this[offset] * 0x1000000) +\n    ((this[offset + 1] << 16) |\n    (this[offset + 2] << 8) |\n    this[offset + 3])\n}\n\nBuffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {\n  offset = offset | 0\n  byteLength = byteLength | 0\n  if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n  var val = this[offset]\n  var mul = 1\n  var i = 0\n  while (++i < byteLength && (mul *= 0x100)) {\n    val += this[offset + i] * mul\n  }\n  mul *= 0x80\n\n  if (val >= mul) val -= Math.pow(2, 8 * byteLength)\n\n  return val\n}\n\nBuffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {\n  offset = offset | 0\n  byteLength = byteLength | 0\n  if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n  var i = byteLength\n  var mul = 1\n  var val = this[offset + --i]\n  while (i > 0 && (mul *= 0x100)) {\n    val += this[offset + --i] * mul\n  }\n  mul *= 0x80\n\n  if (val >= mul) val -= Math.pow(2, 8 * byteLength)\n\n  return val\n}\n\nBuffer.prototype.readInt8 = function readInt8 (offset, noAssert) {\n  if (!noAssert) checkOffset(offset, 1, this.length)\n  if (!(this[offset] & 0x80)) return (this[offset])\n  return ((0xff - this[offset] + 1) * -1)\n}\n\nBuffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {\n  if (!noAssert) checkOffset(offset, 2, this.length)\n  var val = this[offset] | (this[offset + 1] << 8)\n  return (val & 0x8000) ? val | 0xFFFF0000 : val\n}\n\nBuffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {\n  if (!noAssert) checkOffset(offset, 2, this.length)\n  var val = this[offset + 1] | (this[offset] << 8)\n  return (val & 0x8000) ? val | 0xFFFF0000 : val\n}\n\nBuffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {\n  if (!noAssert) checkOffset(offset, 4, this.length)\n\n  return (this[offset]) |\n    (this[offset + 1] << 8) |\n    (this[offset + 2] << 16) |\n    (this[offset + 3] << 24)\n}\n\nBuffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {\n  if (!noAssert) checkOffset(offset, 4, this.length)\n\n  return (this[offset] << 24) |\n    (this[offset + 1] << 16) |\n    (this[offset + 2] << 8) |\n    (this[offset + 3])\n}\n\nBuffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {\n  if (!noAssert) checkOffset(offset, 4, this.length)\n  return ieee754.read(this, offset, true, 23, 4)\n}\n\nBuffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {\n  if (!noAssert) checkOffset(offset, 4, this.length)\n  return ieee754.read(this, offset, false, 23, 4)\n}\n\nBuffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {\n  if (!noAssert) checkOffset(offset, 8, this.length)\n  return ieee754.read(this, offset, true, 52, 8)\n}\n\nBuffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {\n  if (!noAssert) checkOffset(offset, 8, this.length)\n  return ieee754.read(this, offset, false, 52, 8)\n}\n\nfunction checkInt (buf, value, offset, ext, max, min) {\n  if (!Buffer.isBuffer(buf)) throw new TypeError('buffer must be a Buffer instance')\n  if (value > max || value < min) throw new RangeError('value is out of bounds')\n  if (offset + ext > buf.length) throw new RangeError('index out of range')\n}\n\nBuffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {\n  value = +value\n  offset = offset | 0\n  byteLength = byteLength | 0\n  if (!noAssert) checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0)\n\n  var mul = 1\n  var i = 0\n  this[offset] = value & 0xFF\n  while (++i < byteLength && (mul *= 0x100)) {\n    this[offset + i] = (value / mul) & 0xFF\n  }\n\n  return offset + byteLength\n}\n\nBuffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {\n  value = +value\n  offset = offset | 0\n  byteLength = byteLength | 0\n  if (!noAssert) checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0)\n\n  var i = byteLength - 1\n  var mul = 1\n  this[offset + i] = value & 0xFF\n  while (--i >= 0 && (mul *= 0x100)) {\n    this[offset + i] = (value / mul) & 0xFF\n  }\n\n  return offset + byteLength\n}\n\nBuffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {\n  value = +value\n  offset = offset | 0\n  if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)\n  if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)\n  this[offset] = (value & 0xff)\n  return offset + 1\n}\n\nfunction objectWriteUInt16 (buf, value, offset, littleEndian) {\n  if (value < 0) value = 0xffff + value + 1\n  for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; i++) {\n    buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>\n      (littleEndian ? i : 1 - i) * 8\n  }\n}\n\nBuffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {\n  value = +value\n  offset = offset | 0\n  if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)\n  if (Buffer.TYPED_ARRAY_SUPPORT) {\n    this[offset] = (value & 0xff)\n    this[offset + 1] = (value >>> 8)\n  } else {\n    objectWriteUInt16(this, value, offset, true)\n  }\n  return offset + 2\n}\n\nBuffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {\n  value = +value\n  offset = offset | 0\n  if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)\n  if (Buffer.TYPED_ARRAY_SUPPORT) {\n    this[offset] = (value >>> 8)\n    this[offset + 1] = (value & 0xff)\n  } else {\n    objectWriteUInt16(this, value, offset, false)\n  }\n  return offset + 2\n}\n\nfunction objectWriteUInt32 (buf, value, offset, littleEndian) {\n  if (value < 0) value = 0xffffffff + value + 1\n  for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; i++) {\n    buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff\n  }\n}\n\nBuffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {\n  value = +value\n  offset = offset | 0\n  if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)\n  if (Buffer.TYPED_ARRAY_SUPPORT) {\n    this[offset + 3] = (value >>> 24)\n    this[offset + 2] = (value >>> 16)\n    this[offset + 1] = (value >>> 8)\n    this[offset] = (value & 0xff)\n  } else {\n    objectWriteUInt32(this, value, offset, true)\n  }\n  return offset + 4\n}\n\nBuffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {\n  value = +value\n  offset = offset | 0\n  if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)\n  if (Buffer.TYPED_ARRAY_SUPPORT) {\n    this[offset] = (value >>> 24)\n    this[offset + 1] = (value >>> 16)\n    this[offset + 2] = (value >>> 8)\n    this[offset + 3] = (value & 0xff)\n  } else {\n    objectWriteUInt32(this, value, offset, false)\n  }\n  return offset + 4\n}\n\nBuffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {\n  value = +value\n  offset = offset | 0\n  if (!noAssert) {\n    var limit = Math.pow(2, 8 * byteLength - 1)\n\n    checkInt(this, value, offset, byteLength, limit - 1, -limit)\n  }\n\n  var i = 0\n  var mul = 1\n  var sub = value < 0 ? 1 : 0\n  this[offset] = value & 0xFF\n  while (++i < byteLength && (mul *= 0x100)) {\n    this[offset + i] = ((value / mul) >> 0) - sub & 0xFF\n  }\n\n  return offset + byteLength\n}\n\nBuffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {\n  value = +value\n  offset = offset | 0\n  if (!noAssert) {\n    var limit = Math.pow(2, 8 * byteLength - 1)\n\n    checkInt(this, value, offset, byteLength, limit - 1, -limit)\n  }\n\n  var i = byteLength - 1\n  var mul = 1\n  var sub = value < 0 ? 1 : 0\n  this[offset + i] = value & 0xFF\n  while (--i >= 0 && (mul *= 0x100)) {\n    this[offset + i] = ((value / mul) >> 0) - sub & 0xFF\n  }\n\n  return offset + byteLength\n}\n\nBuffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {\n  value = +value\n  offset = offset | 0\n  if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)\n  if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)\n  if (value < 0) value = 0xff + value + 1\n  this[offset] = (value & 0xff)\n  return offset + 1\n}\n\nBuffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {\n  value = +value\n  offset = offset | 0\n  if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)\n  if (Buffer.TYPED_ARRAY_SUPPORT) {\n    this[offset] = (value & 0xff)\n    this[offset + 1] = (value >>> 8)\n  } else {\n    objectWriteUInt16(this, value, offset, true)\n  }\n  return offset + 2\n}\n\nBuffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {\n  value = +value\n  offset = offset | 0\n  if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)\n  if (Buffer.TYPED_ARRAY_SUPPORT) {\n    this[offset] = (value >>> 8)\n    this[offset + 1] = (value & 0xff)\n  } else {\n    objectWriteUInt16(this, value, offset, false)\n  }\n  return offset + 2\n}\n\nBuffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {\n  value = +value\n  offset = offset | 0\n  if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)\n  if (Buffer.TYPED_ARRAY_SUPPORT) {\n    this[offset] = (value & 0xff)\n    this[offset + 1] = (value >>> 8)\n    this[offset + 2] = (value >>> 16)\n    this[offset + 3] = (value >>> 24)\n  } else {\n    objectWriteUInt32(this, value, offset, true)\n  }\n  return offset + 4\n}\n\nBuffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {\n  value = +value\n  offset = offset | 0\n  if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)\n  if (value < 0) value = 0xffffffff + value + 1\n  if (Buffer.TYPED_ARRAY_SUPPORT) {\n    this[offset] = (value >>> 24)\n    this[offset + 1] = (value >>> 16)\n    this[offset + 2] = (value >>> 8)\n    this[offset + 3] = (value & 0xff)\n  } else {\n    objectWriteUInt32(this, value, offset, false)\n  }\n  return offset + 4\n}\n\nfunction checkIEEE754 (buf, value, offset, ext, max, min) {\n  if (value > max || value < min) throw new RangeError('value is out of bounds')\n  if (offset + ext > buf.length) throw new RangeError('index out of range')\n  if (offset < 0) throw new RangeError('index out of range')\n}\n\nfunction writeFloat (buf, value, offset, littleEndian, noAssert) {\n  if (!noAssert) {\n    checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)\n  }\n  ieee754.write(buf, value, offset, littleEndian, 23, 4)\n  return offset + 4\n}\n\nBuffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {\n  return writeFloat(this, value, offset, true, noAssert)\n}\n\nBuffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {\n  return writeFloat(this, value, offset, false, noAssert)\n}\n\nfunction writeDouble (buf, value, offset, littleEndian, noAssert) {\n  if (!noAssert) {\n    checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)\n  }\n  ieee754.write(buf, value, offset, littleEndian, 52, 8)\n  return offset + 8\n}\n\nBuffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {\n  return writeDouble(this, value, offset, true, noAssert)\n}\n\nBuffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {\n  return writeDouble(this, value, offset, false, noAssert)\n}\n\n// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)\nBuffer.prototype.copy = function copy (target, targetStart, start, end) {\n  if (!start) start = 0\n  if (!end && end !== 0) end = this.length\n  if (targetStart >= target.length) targetStart = target.length\n  if (!targetStart) targetStart = 0\n  if (end > 0 && end < start) end = start\n\n  // Copy 0 bytes; we're done\n  if (end === start) return 0\n  if (target.length === 0 || this.length === 0) return 0\n\n  // Fatal error conditions\n  if (targetStart < 0) {\n    throw new RangeError('targetStart out of bounds')\n  }\n  if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')\n  if (end < 0) throw new RangeError('sourceEnd out of bounds')\n\n  // Are we oob?\n  if (end > this.length) end = this.length\n  if (target.length - targetStart < end - start) {\n    end = target.length - targetStart + start\n  }\n\n  var len = end - start\n  var i\n\n  if (this === target && start < targetStart && targetStart < end) {\n    // descending copy from end\n    for (i = len - 1; i >= 0; i--) {\n      target[i + targetStart] = this[i + start]\n    }\n  } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {\n    // ascending copy from start\n    for (i = 0; i < len; i++) {\n      target[i + targetStart] = this[i + start]\n    }\n  } else {\n    target._set(this.subarray(start, start + len), targetStart)\n  }\n\n  return len\n}\n\n// fill(value, start=0, end=buffer.length)\nBuffer.prototype.fill = function fill (value, start, end) {\n  if (!value) value = 0\n  if (!start) start = 0\n  if (!end) end = this.length\n\n  if (end < start) throw new RangeError('end < start')\n\n  // Fill 0 bytes; we're done\n  if (end === start) return\n  if (this.length === 0) return\n\n  if (start < 0 || start >= this.length) throw new RangeError('start out of bounds')\n  if (end < 0 || end > this.length) throw new RangeError('end out of bounds')\n\n  var i\n  if (typeof value === 'number') {\n    for (i = start; i < end; i++) {\n      this[i] = value\n    }\n  } else {\n    var bytes = utf8ToBytes(value.toString())\n    var len = bytes.length\n    for (i = start; i < end; i++) {\n      this[i] = bytes[i % len]\n    }\n  }\n\n  return this\n}\n\n/**\n * Creates a new `ArrayBuffer` with the *copied* memory of the buffer instance.\n * Added in Node 0.12. Only available in browsers that support ArrayBuffer.\n */\nBuffer.prototype.toArrayBuffer = function toArrayBuffer () {\n  if (typeof Uint8Array !== 'undefined') {\n    if (Buffer.TYPED_ARRAY_SUPPORT) {\n      return (new Buffer(this)).buffer\n    } else {\n      var buf = new Uint8Array(this.length)\n      for (var i = 0, len = buf.length; i < len; i += 1) {\n        buf[i] = this[i]\n      }\n      return buf.buffer\n    }\n  } else {\n    throw new TypeError('Buffer.toArrayBuffer not supported in this browser')\n  }\n}\n\n// HELPER FUNCTIONS\n// ================\n\nvar BP = Buffer.prototype\n\n/**\n * Augment a Uint8Array *instance* (not the Uint8Array class!) with Buffer methods\n */\nBuffer._augment = function _augment (arr) {\n  arr.constructor = Buffer\n  arr._isBuffer = true\n\n  // save reference to original Uint8Array set method before overwriting\n  arr._set = arr.set\n\n  // deprecated\n  arr.get = BP.get\n  arr.set = BP.set\n\n  arr.write = BP.write\n  arr.toString = BP.toString\n  arr.toLocaleString = BP.toString\n  arr.toJSON = BP.toJSON\n  arr.equals = BP.equals\n  arr.compare = BP.compare\n  arr.indexOf = BP.indexOf\n  arr.copy = BP.copy\n  arr.slice = BP.slice\n  arr.readUIntLE = BP.readUIntLE\n  arr.readUIntBE = BP.readUIntBE\n  arr.readUInt8 = BP.readUInt8\n  arr.readUInt16LE = BP.readUInt16LE\n  arr.readUInt16BE = BP.readUInt16BE\n  arr.readUInt32LE = BP.readUInt32LE\n  arr.readUInt32BE = BP.readUInt32BE\n  arr.readIntLE = BP.readIntLE\n  arr.readIntBE = BP.readIntBE\n  arr.readInt8 = BP.readInt8\n  arr.readInt16LE = BP.readInt16LE\n  arr.readInt16BE = BP.readInt16BE\n  arr.readInt32LE = BP.readInt32LE\n  arr.readInt32BE = BP.readInt32BE\n  arr.readFloatLE = BP.readFloatLE\n  arr.readFloatBE = BP.readFloatBE\n  arr.readDoubleLE = BP.readDoubleLE\n  arr.readDoubleBE = BP.readDoubleBE\n  arr.writeUInt8 = BP.writeUInt8\n  arr.writeUIntLE = BP.writeUIntLE\n  arr.writeUIntBE = BP.writeUIntBE\n  arr.writeUInt16LE = BP.writeUInt16LE\n  arr.writeUInt16BE = BP.writeUInt16BE\n  arr.writeUInt32LE = BP.writeUInt32LE\n  arr.writeUInt32BE = BP.writeUInt32BE\n  arr.writeIntLE = BP.writeIntLE\n  arr.writeIntBE = BP.writeIntBE\n  arr.writeInt8 = BP.writeInt8\n  arr.writeInt16LE = BP.writeInt16LE\n  arr.writeInt16BE = BP.writeInt16BE\n  arr.writeInt32LE = BP.writeInt32LE\n  arr.writeInt32BE = BP.writeInt32BE\n  arr.writeFloatLE = BP.writeFloatLE\n  arr.writeFloatBE = BP.writeFloatBE\n  arr.writeDoubleLE = BP.writeDoubleLE\n  arr.writeDoubleBE = BP.writeDoubleBE\n  arr.fill = BP.fill\n  arr.inspect = BP.inspect\n  arr.toArrayBuffer = BP.toArrayBuffer\n\n  return arr\n}\n\nvar INVALID_BASE64_RE = /[^+\\/0-9A-Za-z-_]/g\n\nfunction base64clean (str) {\n  // Node strips out invalid characters like \\n and \\t from the string, base64-js does not\n  str = stringtrim(str).replace(INVALID_BASE64_RE, '')\n  // Node converts strings with length < 2 to ''\n  if (str.length < 2) return ''\n  // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not\n  while (str.length % 4 !== 0) {\n    str = str + '='\n  }\n  return str\n}\n\nfunction stringtrim (str) {\n  if (str.trim) return str.trim()\n  return str.replace(/^\\s+|\\s+$/g, '')\n}\n\nfunction toHex (n) {\n  if (n < 16) return '0' + n.toString(16)\n  return n.toString(16)\n}\n\nfunction utf8ToBytes (string, units) {\n  units = units || Infinity\n  var codePoint\n  var length = string.length\n  var leadSurrogate = null\n  var bytes = []\n\n  for (var i = 0; i < length; i++) {\n    codePoint = string.charCodeAt(i)\n\n    // is surrogate component\n    if (codePoint > 0xD7FF && codePoint < 0xE000) {\n      // last char was a lead\n      if (!leadSurrogate) {\n        // no lead yet\n        if (codePoint > 0xDBFF) {\n          // unexpected trail\n          if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n          continue\n        } else if (i + 1 === length) {\n          // unpaired lead\n          if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n          continue\n        }\n\n        // valid lead\n        leadSurrogate = codePoint\n\n        continue\n      }\n\n      // 2 leads in a row\n      if (codePoint < 0xDC00) {\n        if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n        leadSurrogate = codePoint\n        continue\n      }\n\n      // valid surrogate pair\n      codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000\n    } else if (leadSurrogate) {\n      // valid bmp char, but last char was a lead\n      if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n    }\n\n    leadSurrogate = null\n\n    // encode utf8\n    if (codePoint < 0x80) {\n      if ((units -= 1) < 0) break\n      bytes.push(codePoint)\n    } else if (codePoint < 0x800) {\n      if ((units -= 2) < 0) break\n      bytes.push(\n        codePoint >> 0x6 | 0xC0,\n        codePoint & 0x3F | 0x80\n      )\n    } else if (codePoint < 0x10000) {\n      if ((units -= 3) < 0) break\n      bytes.push(\n        codePoint >> 0xC | 0xE0,\n        codePoint >> 0x6 & 0x3F | 0x80,\n        codePoint & 0x3F | 0x80\n      )\n    } else if (codePoint < 0x110000) {\n      if ((units -= 4) < 0) break\n      bytes.push(\n        codePoint >> 0x12 | 0xF0,\n        codePoint >> 0xC & 0x3F | 0x80,\n        codePoint >> 0x6 & 0x3F | 0x80,\n        codePoint & 0x3F | 0x80\n      )\n    } else {\n      throw new Error('Invalid code point')\n    }\n  }\n\n  return bytes\n}\n\nfunction asciiToBytes (str) {\n  var byteArray = []\n  for (var i = 0; i < str.length; i++) {\n    // Node's code seems to be doing this and not & 0x7F..\n    byteArray.push(str.charCodeAt(i) & 0xFF)\n  }\n  return byteArray\n}\n\nfunction utf16leToBytes (str, units) {\n  var c, hi, lo\n  var byteArray = []\n  for (var i = 0; i < str.length; i++) {\n    if ((units -= 2) < 0) break\n\n    c = str.charCodeAt(i)\n    hi = c >> 8\n    lo = c % 256\n    byteArray.push(lo)\n    byteArray.push(hi)\n  }\n\n  return byteArray\n}\n\nfunction base64ToBytes (str) {\n  return base64.toByteArray(base64clean(str))\n}\n\nfunction blitBuffer (src, dst, offset, length) {\n  for (var i = 0; i < length; i++) {\n    if ((i + offset >= dst.length) || (i >= src.length)) break\n    dst[i + offset] = src[i]\n  }\n  return i\n}\n\n}).call(this,typeof global !== \"undefined\" ? global : typeof self !== \"undefined\" ? self : typeof window !== \"undefined\" ? window : {})\n},{\"base64-js\":2,\"ieee754\":7,\"isarray\":4}],4:[function(require,module,exports){\nvar toString = {}.toString;\n\nmodule.exports = Array.isArray || function (arr) {\n  return toString.call(arr) == '[object Array]';\n};\n\n},{}],5:[function(require,module,exports){\n\n/**\n * Expose `Emitter`.\n */\n\nmodule.exports = Emitter;\n\n/**\n * Initialize a new `Emitter`.\n *\n * @api public\n */\n\nfunction Emitter(obj) {\n  if (obj) return mixin(obj);\n};\n\n/**\n * Mixin the emitter properties.\n *\n * @param {Object} obj\n * @return {Object}\n * @api private\n */\n\nfunction mixin(obj) {\n  for (var key in Emitter.prototype) {\n    obj[key] = Emitter.prototype[key];\n  }\n  return obj;\n}\n\n/**\n * Listen on the given `event` with `fn`.\n *\n * @param {String} event\n * @param {Function} fn\n * @return {Emitter}\n * @api public\n */\n\nEmitter.prototype.on =\nEmitter.prototype.addEventListener = function(event, fn){\n  this._callbacks = this._callbacks || {};\n  (this._callbacks[event] = this._callbacks[event] || [])\n    .push(fn);\n  return this;\n};\n\n/**\n * Adds an `event` listener that will be invoked a single\n * time then automatically removed.\n *\n * @param {String} event\n * @param {Function} fn\n * @return {Emitter}\n * @api public\n */\n\nEmitter.prototype.once = function(event, fn){\n  var self = this;\n  this._callbacks = this._callbacks || {};\n\n  function on() {\n    self.off(event, on);\n    fn.apply(this, arguments);\n  }\n\n  on.fn = fn;\n  this.on(event, on);\n  return this;\n};\n\n/**\n * Remove the given callback for `event` or all\n * registered callbacks.\n *\n * @param {String} event\n * @param {Function} fn\n * @return {Emitter}\n * @api public\n */\n\nEmitter.prototype.off =\nEmitter.prototype.removeListener =\nEmitter.prototype.removeAllListeners =\nEmitter.prototype.removeEventListener = function(event, fn){\n  this._callbacks = this._callbacks || {};\n\n  // all\n  if (0 == arguments.length) {\n    this._callbacks = {};\n    return this;\n  }\n\n  // specific event\n  var callbacks = this._callbacks[event];\n  if (!callbacks) return this;\n\n  // remove all handlers\n  if (1 == arguments.length) {\n    delete this._callbacks[event];\n    return this;\n  }\n\n  // remove specific handler\n  var cb;\n  for (var i = 0; i < callbacks.length; i++) {\n    cb = callbacks[i];\n    if (cb === fn || cb.fn === fn) {\n      callbacks.splice(i, 1);\n      break;\n    }\n  }\n  return this;\n};\n\n/**\n * Emit `event` with the given args.\n *\n * @param {String} event\n * @param {Mixed} ...\n * @return {Emitter}\n */\n\nEmitter.prototype.emit = function(event){\n  this._callbacks = this._callbacks || {};\n  var args = [].slice.call(arguments, 1)\n    , callbacks = this._callbacks[event];\n\n  if (callbacks) {\n    callbacks = callbacks.slice(0);\n    for (var i = 0, len = callbacks.length; i < len; ++i) {\n      callbacks[i].apply(this, args);\n    }\n  }\n\n  return this;\n};\n\n/**\n * Return array of callbacks for `event`.\n *\n * @param {String} event\n * @return {Array}\n * @api public\n */\n\nEmitter.prototype.listeners = function(event){\n  this._callbacks = this._callbacks || {};\n  return this._callbacks[event] || [];\n};\n\n/**\n * Check if this emitter has `event` handlers.\n *\n * @param {String} event\n * @return {Boolean}\n * @api public\n */\n\nEmitter.prototype.hasListeners = function(event){\n  return !! this.listeners(event).length;\n};\n\n},{}],6:[function(require,module,exports){\n/*!\n * EventEmitter2\n * https://github.com/hij1nx/EventEmitter2\n *\n * Copyright (c) 2013 hij1nx\n * Licensed under the MIT license.\n */\n;!function(undefined) {\n\n  var isArray = Array.isArray ? Array.isArray : function _isArray(obj) {\n    return Object.prototype.toString.call(obj) === \"[object Array]\";\n  };\n  var defaultMaxListeners = 10;\n\n  function init() {\n    this._events = {};\n    if (this._conf) {\n      configure.call(this, this._conf);\n    }\n  }\n\n  function configure(conf) {\n    if (conf) {\n\n      this._conf = conf;\n\n      conf.delimiter && (this.delimiter = conf.delimiter);\n      conf.maxListeners && (this._events.maxListeners = conf.maxListeners);\n      conf.wildcard && (this.wildcard = conf.wildcard);\n      conf.newListener && (this.newListener = conf.newListener);\n\n      if (this.wildcard) {\n        this.listenerTree = {};\n      }\n    }\n  }\n\n  function EventEmitter(conf) {\n    this._events = {};\n    this.newListener = false;\n    configure.call(this, conf);\n  }\n\n  //\n  // Attention, function return type now is array, always !\n  // It has zero elements if no any matches found and one or more\n  // elements (leafs) if there are matches\n  //\n  function searchListenerTree(handlers, type, tree, i) {\n    if (!tree) {\n      return [];\n    }\n    var listeners=[], leaf, len, branch, xTree, xxTree, isolatedBranch, endReached,\n        typeLength = type.length, currentType = type[i], nextType = type[i+1];\n    if (i === typeLength && tree._listeners) {\n      //\n      // If at the end of the event(s) list and the tree has listeners\n      // invoke those listeners.\n      //\n      if (typeof tree._listeners === 'function') {\n        handlers && handlers.push(tree._listeners);\n        return [tree];\n      } else {\n        for (leaf = 0, len = tree._listeners.length; leaf < len; leaf++) {\n          handlers && handlers.push(tree._listeners[leaf]);\n        }\n        return [tree];\n      }\n    }\n\n    if ((currentType === '*' || currentType === '**') || tree[currentType]) {\n      //\n      // If the event emitted is '*' at this part\n      // or there is a concrete match at this patch\n      //\n      if (currentType === '*') {\n        for (branch in tree) {\n          if (branch !== '_listeners' && tree.hasOwnProperty(branch)) {\n            listeners = listeners.concat(searchListenerTree(handlers, type, tree[branch], i+1));\n          }\n        }\n        return listeners;\n      } else if(currentType === '**') {\n        endReached = (i+1 === typeLength || (i+2 === typeLength && nextType === '*'));\n        if(endReached && tree._listeners) {\n          // The next element has a _listeners, add it to the handlers.\n          listeners = listeners.concat(searchListenerTree(handlers, type, tree, typeLength));\n        }\n\n        for (branch in tree) {\n          if (branch !== '_listeners' && tree.hasOwnProperty(branch)) {\n            if(branch === '*' || branch === '**') {\n              if(tree[branch]._listeners && !endReached) {\n                listeners = listeners.concat(searchListenerTree(handlers, type, tree[branch], typeLength));\n              }\n              listeners = listeners.concat(searchListenerTree(handlers, type, tree[branch], i));\n            } else if(branch === nextType) {\n              listeners = listeners.concat(searchListenerTree(handlers, type, tree[branch], i+2));\n            } else {\n              // No match on this one, shift into the tree but not in the type array.\n              listeners = listeners.concat(searchListenerTree(handlers, type, tree[branch], i));\n            }\n          }\n        }\n        return listeners;\n      }\n\n      listeners = listeners.concat(searchListenerTree(handlers, type, tree[currentType], i+1));\n    }\n\n    xTree = tree['*'];\n    if (xTree) {\n      //\n      // If the listener tree will allow any match for this part,\n      // then recursively explore all branches of the tree\n      //\n      searchListenerTree(handlers, type, xTree, i+1);\n    }\n\n    xxTree = tree['**'];\n    if(xxTree) {\n      if(i < typeLength) {\n        if(xxTree._listeners) {\n          // If we have a listener on a '**', it will catch all, so add its handler.\n          searchListenerTree(handlers, type, xxTree, typeLength);\n        }\n\n        // Build arrays of matching next branches and others.\n        for(branch in xxTree) {\n          if(branch !== '_listeners' && xxTree.hasOwnProperty(branch)) {\n            if(branch === nextType) {\n              // We know the next element will match, so jump twice.\n              searchListenerTree(handlers, type, xxTree[branch], i+2);\n            } else if(branch === currentType) {\n              // Current node matches, move into the tree.\n              searchListenerTree(handlers, type, xxTree[branch], i+1);\n            } else {\n              isolatedBranch = {};\n              isolatedBranch[branch] = xxTree[branch];\n              searchListenerTree(handlers, type, { '**': isolatedBranch }, i+1);\n            }\n          }\n        }\n      } else if(xxTree._listeners) {\n        // We have reached the end and still on a '**'\n        searchListenerTree(handlers, type, xxTree, typeLength);\n      } else if(xxTree['*'] && xxTree['*']._listeners) {\n        searchListenerTree(handlers, type, xxTree['*'], typeLength);\n      }\n    }\n\n    return listeners;\n  }\n\n  function growListenerTree(type, listener) {\n\n    type = typeof type === 'string' ? type.split(this.delimiter) : type.slice();\n\n    //\n    // Looks for two consecutive '**', if so, don't add the event at all.\n    //\n    for(var i = 0, len = type.length; i+1 < len; i++) {\n      if(type[i] === '**' && type[i+1] === '**') {\n        return;\n      }\n    }\n\n    var tree = this.listenerTree;\n    var name = type.shift();\n\n    while (name) {\n\n      if (!tree[name]) {\n        tree[name] = {};\n      }\n\n      tree = tree[name];\n\n      if (type.length === 0) {\n\n        if (!tree._listeners) {\n          tree._listeners = listener;\n        }\n        else if(typeof tree._listeners === 'function') {\n          tree._listeners = [tree._listeners, listener];\n        }\n        else if (isArray(tree._listeners)) {\n\n          tree._listeners.push(listener);\n\n          if (!tree._listeners.warned) {\n\n            var m = defaultMaxListeners;\n\n            if (typeof this._events.maxListeners !== 'undefined') {\n              m = this._events.maxListeners;\n            }\n\n            if (m > 0 && tree._listeners.length > m) {\n\n              tree._listeners.warned = true;\n              console.error('(node) warning: possible EventEmitter memory ' +\n                            'leak detected. %d listeners added. ' +\n                            'Use emitter.setMaxListeners() to increase limit.',\n                            tree._listeners.length);\n              console.trace();\n            }\n          }\n        }\n        return true;\n      }\n      name = type.shift();\n    }\n    return true;\n  }\n\n  // By default EventEmitters will print a warning if more than\n  // 10 listeners are added to it. This is a useful default which\n  // helps finding memory leaks.\n  //\n  // Obviously not all Emitters should be limited to 10. This function allows\n  // that to be increased. Set to zero for unlimited.\n\n  EventEmitter.prototype.delimiter = '.';\n\n  EventEmitter.prototype.setMaxListeners = function(n) {\n    this._events || init.call(this);\n    this._events.maxListeners = n;\n    if (!this._conf) this._conf = {};\n    this._conf.maxListeners = n;\n  };\n\n  EventEmitter.prototype.event = '';\n\n  EventEmitter.prototype.once = function(event, fn) {\n    this.many(event, 1, fn);\n    return this;\n  };\n\n  EventEmitter.prototype.many = function(event, ttl, fn) {\n    var self = this;\n\n    if (typeof fn !== 'function') {\n      throw new Error('many only accepts instances of Function');\n    }\n\n    function listener() {\n      if (--ttl === 0) {\n        self.off(event, listener);\n      }\n      fn.apply(this, arguments);\n    }\n\n    listener._origin = fn;\n\n    this.on(event, listener);\n\n    return self;\n  };\n\n  EventEmitter.prototype.emit = function() {\n\n    this._events || init.call(this);\n\n    var type = arguments[0];\n\n    if (type === 'newListener' && !this.newListener) {\n      if (!this._events.newListener) { return false; }\n    }\n\n    // Loop through the *_all* functions and invoke them.\n    if (this._all) {\n      var l = arguments.length;\n      var args = new Array(l - 1);\n      for (var i = 1; i < l; i++) args[i - 1] = arguments[i];\n      for (i = 0, l = this._all.length; i < l; i++) {\n        this.event = type;\n        this._all[i].apply(this, args);\n      }\n    }\n\n    // If there is no 'error' event listener then throw.\n    if (type === 'error') {\n\n      if (!this._all &&\n        !this._events.error &&\n        !(this.wildcard && this.listenerTree.error)) {\n\n        if (arguments[1] instanceof Error) {\n          throw arguments[1]; // Unhandled 'error' event\n        } else {\n          throw new Error(\"Uncaught, unspecified 'error' event.\");\n        }\n        return false;\n      }\n    }\n\n    var handler;\n\n    if(this.wildcard) {\n      handler = [];\n      var ns = typeof type === 'string' ? type.split(this.delimiter) : type.slice();\n      searchListenerTree.call(this, handler, ns, this.listenerTree, 0);\n    }\n    else {\n      handler = this._events[type];\n    }\n\n    if (typeof handler === 'function') {\n      this.event = type;\n      if (arguments.length === 1) {\n        handler.call(this);\n      }\n      else if (arguments.length > 1)\n        switch (arguments.length) {\n          case 2:\n            handler.call(this, arguments[1]);\n            break;\n          case 3:\n            handler.call(this, arguments[1], arguments[2]);\n            break;\n          // slower\n          default:\n            var l = arguments.length;\n            var args = new Array(l - 1);\n            for (var i = 1; i < l; i++) args[i - 1] = arguments[i];\n            handler.apply(this, args);\n        }\n      return true;\n    }\n    else if (handler) {\n      var l = arguments.length;\n      var args = new Array(l - 1);\n      for (var i = 1; i < l; i++) args[i - 1] = arguments[i];\n\n      var listeners = handler.slice();\n      for (var i = 0, l = listeners.length; i < l; i++) {\n        this.event = type;\n        listeners[i].apply(this, args);\n      }\n      return (listeners.length > 0) || !!this._all;\n    }\n    else {\n      return !!this._all;\n    }\n\n  };\n\n  EventEmitter.prototype.on = function(type, listener) {\n\n    if (typeof type === 'function') {\n      this.onAny(type);\n      return this;\n    }\n\n    if (typeof listener !== 'function') {\n      throw new Error('on only accepts instances of Function');\n    }\n    this._events || init.call(this);\n\n    // To avoid recursion in the case that type == \"newListeners\"! Before\n    // adding it to the listeners, first emit \"newListeners\".\n    this.emit('newListener', type, listener);\n\n    if(this.wildcard) {\n      growListenerTree.call(this, type, listener);\n      return this;\n    }\n\n    if (!this._events[type]) {\n      // Optimize the case of one listener. Don't need the extra array object.\n      this._events[type] = listener;\n    }\n    else if(typeof this._events[type] === 'function') {\n      // Adding the second element, need to change to array.\n      this._events[type] = [this._events[type], listener];\n    }\n    else if (isArray(this._events[type])) {\n      // If we've already got an array, just append.\n      this._events[type].push(listener);\n\n      // Check for listener leak\n      if (!this._events[type].warned) {\n\n        var m = defaultMaxListeners;\n\n        if (typeof this._events.maxListeners !== 'undefined') {\n          m = this._events.maxListeners;\n        }\n\n        if (m > 0 && this._events[type].length > m) {\n\n          this._events[type].warned = true;\n          console.error('(node) warning: possible EventEmitter memory ' +\n                        'leak detected. %d listeners added. ' +\n                        'Use emitter.setMaxListeners() to increase limit.',\n                        this._events[type].length);\n          console.trace();\n        }\n      }\n    }\n    return this;\n  };\n\n  EventEmitter.prototype.onAny = function(fn) {\n\n    if (typeof fn !== 'function') {\n      throw new Error('onAny only accepts instances of Function');\n    }\n\n    if(!this._all) {\n      this._all = [];\n    }\n\n    // Add the function to the event listener collection.\n    this._all.push(fn);\n    return this;\n  };\n\n  EventEmitter.prototype.addListener = EventEmitter.prototype.on;\n\n  EventEmitter.prototype.off = function(type, listener) {\n    if (typeof listener !== 'function') {\n      throw new Error('removeListener only takes instances of Function');\n    }\n\n    var handlers,leafs=[];\n\n    if(this.wildcard) {\n      var ns = typeof type === 'string' ? type.split(this.delimiter) : type.slice();\n      leafs = searchListenerTree.call(this, null, ns, this.listenerTree, 0);\n    }\n    else {\n      // does not use listeners(), so no side effect of creating _events[type]\n      if (!this._events[type]) return this;\n      handlers = this._events[type];\n      leafs.push({_listeners:handlers});\n    }\n\n    for (var iLeaf=0; iLeaf<leafs.length; iLeaf++) {\n      var leaf = leafs[iLeaf];\n      handlers = leaf._listeners;\n      if (isArray(handlers)) {\n\n        var position = -1;\n\n        for (var i = 0, length = handlers.length; i < length; i++) {\n          if (handlers[i] === listener ||\n            (handlers[i].listener && handlers[i].listener === listener) ||\n            (handlers[i]._origin && handlers[i]._origin === listener)) {\n            position = i;\n            break;\n          }\n        }\n\n        if (position < 0) {\n          continue;\n        }\n\n        if(this.wildcard) {\n          leaf._listeners.splice(position, 1);\n        }\n        else {\n          this._events[type].splice(position, 1);\n        }\n\n        if (handlers.length === 0) {\n          if(this.wildcard) {\n            delete leaf._listeners;\n          }\n          else {\n            delete this._events[type];\n          }\n        }\n        return this;\n      }\n      else if (handlers === listener ||\n        (handlers.listener && handlers.listener === listener) ||\n        (handlers._origin && handlers._origin === listener)) {\n        if(this.wildcard) {\n          delete leaf._listeners;\n        }\n        else {\n          delete this._events[type];\n        }\n      }\n    }\n\n    return this;\n  };\n\n  EventEmitter.prototype.offAny = function(fn) {\n    var i = 0, l = 0, fns;\n    if (fn && this._all && this._all.length > 0) {\n      fns = this._all;\n      for(i = 0, l = fns.length; i < l; i++) {\n        if(fn === fns[i]) {\n          fns.splice(i, 1);\n          return this;\n        }\n      }\n    } else {\n      this._all = [];\n    }\n    return this;\n  };\n\n  EventEmitter.prototype.removeListener = EventEmitter.prototype.off;\n\n  EventEmitter.prototype.removeAllListeners = function(type) {\n    if (arguments.length === 0) {\n      !this._events || init.call(this);\n      return this;\n    }\n\n    if(this.wildcard) {\n      var ns = typeof type === 'string' ? type.split(this.delimiter) : type.slice();\n      var leafs = searchListenerTree.call(this, null, ns, this.listenerTree, 0);\n\n      for (var iLeaf=0; iLeaf<leafs.length; iLeaf++) {\n        var leaf = leafs[iLeaf];\n        leaf._listeners = null;\n      }\n    }\n    else {\n      if (!this._events[type]) return this;\n      this._events[type] = null;\n    }\n    return this;\n  };\n\n  EventEmitter.prototype.listeners = function(type) {\n    if(this.wildcard) {\n      var handlers = [];\n      var ns = typeof type === 'string' ? type.split(this.delimiter) : type.slice();\n      searchListenerTree.call(this, handlers, ns, this.listenerTree, 0);\n      return handlers;\n    }\n\n    this._events || init.call(this);\n\n    if (!this._events[type]) this._events[type] = [];\n    if (!isArray(this._events[type])) {\n      this._events[type] = [this._events[type]];\n    }\n    return this._events[type];\n  };\n\n  EventEmitter.prototype.listenersAny = function() {\n\n    if(this._all) {\n      return this._all;\n    }\n    else {\n      return [];\n    }\n\n  };\n\n  if (typeof define === 'function' && define.amd) {\n     // AMD. Register as an anonymous module.\n    define(function() {\n      return EventEmitter;\n    });\n  } else if (typeof exports === 'object') {\n    // CommonJS\n    exports.EventEmitter2 = EventEmitter;\n  }\n  else {\n    // Browser global.\n    window.EventEmitter2 = EventEmitter;\n  }\n}();\n\n},{}],7:[function(require,module,exports){\nexports.read = function (buffer, offset, isLE, mLen, nBytes) {\n  var e, m\n  var eLen = nBytes * 8 - mLen - 1\n  var eMax = (1 << eLen) - 1\n  var eBias = eMax >> 1\n  var nBits = -7\n  var i = isLE ? (nBytes - 1) : 0\n  var d = isLE ? -1 : 1\n  var s = buffer[offset + i]\n\n  i += d\n\n  e = s & ((1 << (-nBits)) - 1)\n  s >>= (-nBits)\n  nBits += eLen\n  for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}\n\n  m = e & ((1 << (-nBits)) - 1)\n  e >>= (-nBits)\n  nBits += mLen\n  for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}\n\n  if (e === 0) {\n    e = 1 - eBias\n  } else if (e === eMax) {\n    return m ? NaN : ((s ? -1 : 1) * Infinity)\n  } else {\n    m = m + Math.pow(2, mLen)\n    e = e - eBias\n  }\n  return (s ? -1 : 1) * m * Math.pow(2, e - mLen)\n}\n\nexports.write = function (buffer, value, offset, isLE, mLen, nBytes) {\n  var e, m, c\n  var eLen = nBytes * 8 - mLen - 1\n  var eMax = (1 << eLen) - 1\n  var eBias = eMax >> 1\n  var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)\n  var i = isLE ? 0 : (nBytes - 1)\n  var d = isLE ? 1 : -1\n  var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0\n\n  value = Math.abs(value)\n\n  if (isNaN(value) || value === Infinity) {\n    m = isNaN(value) ? 1 : 0\n    e = eMax\n  } else {\n    e = Math.floor(Math.log(value) / Math.LN2)\n    if (value * (c = Math.pow(2, -e)) < 1) {\n      e--\n      c *= 2\n    }\n    if (e + eBias >= 1) {\n      value += rt / c\n    } else {\n      value += rt * Math.pow(2, 1 - eBias)\n    }\n    if (value * c >= 2) {\n      e++\n      c /= 2\n    }\n\n    if (e + eBias >= eMax) {\n      m = 0\n      e = eMax\n    } else if (e + eBias >= 1) {\n      m = (value * c - 1) * Math.pow(2, mLen)\n      e = e + eBias\n    } else {\n      m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)\n      e = 0\n    }\n  }\n\n  for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}\n\n  e = (e << mLen) | m\n  eLen += mLen\n  for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}\n\n  buffer[offset + i - d] |= s * 128\n}\n\n},{}],8:[function(require,module,exports){\n\n/**\n * Reduce `arr` with `fn`.\n *\n * @param {Array} arr\n * @param {Function} fn\n * @param {Mixed} initial\n *\n * TODO: combatible error handling?\n */\n\nmodule.exports = function(arr, fn, initial){  \n  var idx = 0;\n  var len = arr.length;\n  var curr = arguments.length == 3\n    ? initial\n    : arr[idx++];\n\n  while (idx < len) {\n    curr = fn.call(null, curr, arr[idx], ++idx, arr);\n  }\n  \n  return curr;\n};\n},{}],9:[function(require,module,exports){\n/**\n * Module dependencies.\n */\n\nvar Emitter = require('emitter');\nvar reduce = require('reduce');\n\n/**\n * Root reference for iframes.\n */\n\nvar root = 'undefined' == typeof window\n  ? this\n  : window;\n\n/**\n * Noop.\n */\n\nfunction noop(){};\n\n/**\n * Check if `obj` is a host object,\n * we don't want to serialize these :)\n *\n * TODO: future proof, move to compoent land\n *\n * @param {Object} obj\n * @return {Boolean}\n * @api private\n */\n\nfunction isHost(obj) {\n  var str = {}.toString.call(obj);\n\n  switch (str) {\n    case '[object File]':\n    case '[object Blob]':\n    case '[object FormData]':\n      return true;\n    default:\n      return false;\n  }\n}\n\n/**\n * Determine XHR.\n */\n\nfunction getXHR() {\n  if (root.XMLHttpRequest\n    && ('file:' != root.location.protocol || !root.ActiveXObject)) {\n    return new XMLHttpRequest;\n  } else {\n    try { return new ActiveXObject('Microsoft.XMLHTTP'); } catch(e) {}\n    try { return new ActiveXObject('Msxml2.XMLHTTP.6.0'); } catch(e) {}\n    try { return new ActiveXObject('Msxml2.XMLHTTP.3.0'); } catch(e) {}\n    try { return new ActiveXObject('Msxml2.XMLHTTP'); } catch(e) {}\n  }\n  return false;\n}\n\n/**\n * Removes leading and trailing whitespace, added to support IE.\n *\n * @param {String} s\n * @return {String}\n * @api private\n */\n\nvar trim = ''.trim\n  ? function(s) { return s.trim(); }\n  : function(s) { return s.replace(/(^\\s*|\\s*$)/g, ''); };\n\n/**\n * Check if `obj` is an object.\n *\n * @param {Object} obj\n * @return {Boolean}\n * @api private\n */\n\nfunction isObject(obj) {\n  return obj === Object(obj);\n}\n\n/**\n * Serialize the given `obj`.\n *\n * @param {Object} obj\n * @return {String}\n * @api private\n */\n\nfunction serialize(obj) {\n  if (!isObject(obj)) return obj;\n  var pairs = [];\n  for (var key in obj) {\n    if (null != obj[key]) {\n      pairs.push(encodeURIComponent(key)\n        + '=' + encodeURIComponent(obj[key]));\n    }\n  }\n  return pairs.join('&');\n}\n\n/**\n * Expose serialization method.\n */\n\n request.serializeObject = serialize;\n\n /**\n  * Parse the given x-www-form-urlencoded `str`.\n  *\n  * @param {String} str\n  * @return {Object}\n  * @api private\n  */\n\nfunction parseString(str) {\n  var obj = {};\n  var pairs = str.split('&');\n  var parts;\n  var pair;\n\n  for (var i = 0, len = pairs.length; i < len; ++i) {\n    pair = pairs[i];\n    parts = pair.split('=');\n    obj[decodeURIComponent(parts[0])] = decodeURIComponent(parts[1]);\n  }\n\n  return obj;\n}\n\n/**\n * Expose parser.\n */\n\nrequest.parseString = parseString;\n\n/**\n * Default MIME type map.\n *\n *     superagent.types.xml = 'application/xml';\n *\n */\n\nrequest.types = {\n  html: 'text/html',\n  json: 'application/json',\n  xml: 'application/xml',\n  urlencoded: 'application/x-www-form-urlencoded',\n  'form': 'application/x-www-form-urlencoded',\n  'form-data': 'application/x-www-form-urlencoded'\n};\n\n/**\n * Default serialization map.\n *\n *     superagent.serialize['application/xml'] = function(obj){\n *       return 'generated xml here';\n *     };\n *\n */\n\n request.serialize = {\n   'application/x-www-form-urlencoded': serialize,\n   'application/json': JSON.stringify\n };\n\n /**\n  * Default parsers.\n  *\n  *     superagent.parse['application/xml'] = function(str){\n  *       return { object parsed from str };\n  *     };\n  *\n  */\n\nrequest.parse = {\n  'application/x-www-form-urlencoded': parseString,\n  'application/json': JSON.parse\n};\n\n/**\n * Parse the given header `str` into\n * an object containing the mapped fields.\n *\n * @param {String} str\n * @return {Object}\n * @api private\n */\n\nfunction parseHeader(str) {\n  var lines = str.split(/\\r?\\n/);\n  var fields = {};\n  var index;\n  var line;\n  var field;\n  var val;\n\n  lines.pop(); // trailing CRLF\n\n  for (var i = 0, len = lines.length; i < len; ++i) {\n    line = lines[i];\n    index = line.indexOf(':');\n    field = line.slice(0, index).toLowerCase();\n    val = trim(line.slice(index + 1));\n    fields[field] = val;\n  }\n\n  return fields;\n}\n\n/**\n * Return the mime type for the given `str`.\n *\n * @param {String} str\n * @return {String}\n * @api private\n */\n\nfunction type(str){\n  return str.split(/ *; */).shift();\n};\n\n/**\n * Return header field parameters.\n *\n * @param {String} str\n * @return {Object}\n * @api private\n */\n\nfunction params(str){\n  return reduce(str.split(/ *; */), function(obj, str){\n    var parts = str.split(/ *= */)\n      , key = parts.shift()\n      , val = parts.shift();\n\n    if (key && val) obj[key] = val;\n    return obj;\n  }, {});\n};\n\n/**\n * Initialize a new `Response` with the given `xhr`.\n *\n *  - set flags (.ok, .error, etc)\n *  - parse header\n *\n * Examples:\n *\n *  Aliasing `superagent` as `request` is nice:\n *\n *      request = superagent;\n *\n *  We can use the promise-like API, or pass callbacks:\n *\n *      request.get('/').end(function(res){});\n *      request.get('/', function(res){});\n *\n *  Sending data can be chained:\n *\n *      request\n *        .post('/user')\n *        .send({ name: 'tj' })\n *        .end(function(res){});\n *\n *  Or passed to `.send()`:\n *\n *      request\n *        .post('/user')\n *        .send({ name: 'tj' }, function(res){});\n *\n *  Or passed to `.post()`:\n *\n *      request\n *        .post('/user', { name: 'tj' })\n *        .end(function(res){});\n *\n * Or further reduced to a single call for simple cases:\n *\n *      request\n *        .post('/user', { name: 'tj' }, function(res){});\n *\n * @param {XMLHTTPRequest} xhr\n * @param {Object} options\n * @api private\n */\n\nfunction Response(req, options) {\n  options = options || {};\n  this.req = req;\n  this.xhr = this.req.xhr;\n  this.text = this.req.method !='HEAD' \n     ? this.xhr.responseText \n     : null;\n  this.setStatusProperties(this.xhr.status);\n  this.header = this.headers = parseHeader(this.xhr.getAllResponseHeaders());\n  // getAllResponseHeaders sometimes falsely returns \"\" for CORS requests, but\n  // getResponseHeader still works. so we get content-type even if getting\n  // other headers fails.\n  this.header['content-type'] = this.xhr.getResponseHeader('content-type');\n  this.setHeaderProperties(this.header);\n  this.body = this.req.method != 'HEAD'\n    ? this.parseBody(this.text)\n    : null;\n}\n\n/**\n * Get case-insensitive `field` value.\n *\n * @param {String} field\n * @return {String}\n * @api public\n */\n\nResponse.prototype.get = function(field){\n  return this.header[field.toLowerCase()];\n};\n\n/**\n * Set header related properties:\n *\n *   - `.type` the content type without params\n *\n * A response of \"Content-Type: text/plain; charset=utf-8\"\n * will provide you with a `.type` of \"text/plain\".\n *\n * @param {Object} header\n * @api private\n */\n\nResponse.prototype.setHeaderProperties = function(header){\n  // content-type\n  var ct = this.header['content-type'] || '';\n  this.type = type(ct);\n\n  // params\n  var obj = params(ct);\n  for (var key in obj) this[key] = obj[key];\n};\n\n/**\n * Parse the given body `str`.\n *\n * Used for auto-parsing of bodies. Parsers\n * are defined on the `superagent.parse` object.\n *\n * @param {String} str\n * @return {Mixed}\n * @api private\n */\n\nResponse.prototype.parseBody = function(str){\n  var parse = request.parse[this.type];\n  return parse && str && str.length\n    ? parse(str)\n    : null;\n};\n\n/**\n * Set flags such as `.ok` based on `status`.\n *\n * For example a 2xx response will give you a `.ok` of __true__\n * whereas 5xx will be __false__ and `.error` will be __true__. The\n * `.clientError` and `.serverError` are also available to be more\n * specific, and `.statusType` is the class of error ranging from 1..5\n * sometimes useful for mapping respond colors etc.\n *\n * \"sugar\" properties are also defined for common cases. Currently providing:\n *\n *   - .noContent\n *   - .badRequest\n *   - .unauthorized\n *   - .notAcceptable\n *   - .notFound\n *\n * @param {Number} status\n * @api private\n */\n\nResponse.prototype.setStatusProperties = function(status){\n  var type = status / 100 | 0;\n\n  // status / class\n  this.status = status;\n  this.statusType = type;\n\n  // basics\n  this.info = 1 == type;\n  this.ok = 2 == type;\n  this.clientError = 4 == type;\n  this.serverError = 5 == type;\n  this.error = (4 == type || 5 == type)\n    ? this.toError()\n    : false;\n\n  // sugar\n  this.accepted = 202 == status;\n  this.noContent = 204 == status || 1223 == status;\n  this.badRequest = 400 == status;\n  this.unauthorized = 401 == status;\n  this.notAcceptable = 406 == status;\n  this.notFound = 404 == status;\n  this.forbidden = 403 == status;\n};\n\n/**\n * Return an `Error` representative of this response.\n *\n * @return {Error}\n * @api public\n */\n\nResponse.prototype.toError = function(){\n  var req = this.req;\n  var method = req.method;\n  var url = req.url;\n\n  var msg = 'cannot ' + method + ' ' + url + ' (' + this.status + ')';\n  var err = new Error(msg);\n  err.status = this.status;\n  err.method = method;\n  err.url = url;\n\n  return err;\n};\n\n/**\n * Expose `Response`.\n */\n\nrequest.Response = Response;\n\n/**\n * Initialize a new `Request` with the given `method` and `url`.\n *\n * @param {String} method\n * @param {String} url\n * @api public\n */\n\nfunction Request(method, url) {\n  var self = this;\n  Emitter.call(this);\n  this._query = this._query || [];\n  this.method = method;\n  this.url = url;\n  this.header = {};\n  this._header = {};\n  this.on('end', function(){\n    var err = null;\n    var res = null;\n\n    try {\n      res = new Response(self); \n    } catch(e) {\n      err = new Error('Parser is unable to parse the response');\n      err.parse = true;\n      err.original = e;\n    }\n\n    self.callback(err, res);\n  });\n}\n\n/**\n * Mixin `Emitter`.\n */\n\nEmitter(Request.prototype);\n\n/**\n * Allow for extension\n */\n\nRequest.prototype.use = function(fn) {\n  fn(this);\n  return this;\n}\n\n/**\n * Set timeout to `ms`.\n *\n * @param {Number} ms\n * @return {Request} for chaining\n * @api public\n */\n\nRequest.prototype.timeout = function(ms){\n  this._timeout = ms;\n  return this;\n};\n\n/**\n * Clear previous timeout.\n *\n * @return {Request} for chaining\n * @api public\n */\n\nRequest.prototype.clearTimeout = function(){\n  this._timeout = 0;\n  clearTimeout(this._timer);\n  return this;\n};\n\n/**\n * Abort the request, and clear potential timeout.\n *\n * @return {Request}\n * @api public\n */\n\nRequest.prototype.abort = function(){\n  if (this.aborted) return;\n  this.aborted = true;\n  this.xhr.abort();\n  this.clearTimeout();\n  this.emit('abort');\n  return this;\n};\n\n/**\n * Set header `field` to `val`, or multiple fields with one object.\n *\n * Examples:\n *\n *      req.get('/')\n *        .set('Accept', 'application/json')\n *        .set('X-API-Key', 'foobar')\n *        .end(callback);\n *\n *      req.get('/')\n *        .set({ Accept: 'application/json', 'X-API-Key': 'foobar' })\n *        .end(callback);\n *\n * @param {String|Object} field\n * @param {String} val\n * @return {Request} for chaining\n * @api public\n */\n\nRequest.prototype.set = function(field, val){\n  if (isObject(field)) {\n    for (var key in field) {\n      this.set(key, field[key]);\n    }\n    return this;\n  }\n  this._header[field.toLowerCase()] = val;\n  this.header[field] = val;\n  return this;\n};\n\n/**\n * Remove header `field`.\n *\n * Example:\n *\n *      req.get('/')\n *        .unset('User-Agent')\n *        .end(callback);\n *\n * @param {String} field\n * @return {Request} for chaining\n * @api public\n */\n\nRequest.prototype.unset = function(field){\n  delete this._header[field.toLowerCase()];\n  delete this.header[field];\n  return this;\n};\n\n/**\n * Get case-insensitive header `field` value.\n *\n * @param {String} field\n * @return {String}\n * @api private\n */\n\nRequest.prototype.getHeader = function(field){\n  return this._header[field.toLowerCase()];\n};\n\n/**\n * Set Content-Type to `type`, mapping values from `request.types`.\n *\n * Examples:\n *\n *      superagent.types.xml = 'application/xml';\n *\n *      request.post('/')\n *        .type('xml')\n *        .send(xmlstring)\n *        .end(callback);\n *\n *      request.post('/')\n *        .type('application/xml')\n *        .send(xmlstring)\n *        .end(callback);\n *\n * @param {String} type\n * @return {Request} for chaining\n * @api public\n */\n\nRequest.prototype.type = function(type){\n  this.set('Content-Type', request.types[type] || type);\n  return this;\n};\n\n/**\n * Set Accept to `type`, mapping values from `request.types`.\n *\n * Examples:\n *\n *      superagent.types.json = 'application/json';\n *\n *      request.get('/agent')\n *        .accept('json')\n *        .end(callback);\n *\n *      request.get('/agent')\n *        .accept('application/json')\n *        .end(callback);\n *\n * @param {String} accept\n * @return {Request} for chaining\n * @api public\n */\n\nRequest.prototype.accept = function(type){\n  this.set('Accept', request.types[type] || type);\n  return this;\n};\n\n/**\n * Set Authorization field value with `user` and `pass`.\n *\n * @param {String} user\n * @param {String} pass\n * @return {Request} for chaining\n * @api public\n */\n\nRequest.prototype.auth = function(user, pass){\n  var str = btoa(user + ':' + pass);\n  this.set('Authorization', 'Basic ' + str);\n  return this;\n};\n\n/**\n* Add query-string `val`.\n*\n* Examples:\n*\n*   request.get('/shoes')\n*     .query('size=10')\n*     .query({ color: 'blue' })\n*\n* @param {Object|String} val\n* @return {Request} for chaining\n* @api public\n*/\n\nRequest.prototype.query = function(val){\n  if ('string' != typeof val) val = serialize(val);\n  if (val) this._query.push(val);\n  return this;\n};\n\n/**\n * Write the field `name` and `val` for \"multipart/form-data\"\n * request bodies.\n *\n * ``` js\n * request.post('/upload')\n *   .field('foo', 'bar')\n *   .end(callback);\n * ```\n *\n * @param {String} name\n * @param {String|Blob|File} val\n * @return {Request} for chaining\n * @api public\n */\n\nRequest.prototype.field = function(name, val){\n  if (!this._formData) this._formData = new FormData();\n  this._formData.append(name, val);\n  return this;\n};\n\n/**\n * Queue the given `file` as an attachment to the specified `field`,\n * with optional `filename`.\n *\n * ``` js\n * request.post('/upload')\n *   .attach(new Blob(['<a id=\"a\"><b id=\"b\">hey!</b></a>'], { type: \"text/html\"}))\n *   .end(callback);\n * ```\n *\n * @param {String} field\n * @param {Blob|File} file\n * @param {String} filename\n * @return {Request} for chaining\n * @api public\n */\n\nRequest.prototype.attach = function(field, file, filename){\n  if (!this._formData) this._formData = new FormData();\n  this._formData.append(field, file, filename);\n  return this;\n};\n\n/**\n * Send `data`, defaulting the `.type()` to \"json\" when\n * an object is given.\n *\n * Examples:\n *\n *       // querystring\n *       request.get('/search')\n *         .end(callback)\n *\n *       // multiple data \"writes\"\n *       request.get('/search')\n *         .send({ search: 'query' })\n *         .send({ range: '1..5' })\n *         .send({ order: 'desc' })\n *         .end(callback)\n *\n *       // manual json\n *       request.post('/user')\n *         .type('json')\n *         .send('{\"name\":\"tj\"})\n *         .end(callback)\n *\n *       // auto json\n *       request.post('/user')\n *         .send({ name: 'tj' })\n *         .end(callback)\n *\n *       // manual x-www-form-urlencoded\n *       request.post('/user')\n *         .type('form')\n *         .send('name=tj')\n *         .end(callback)\n *\n *       // auto x-www-form-urlencoded\n *       request.post('/user')\n *         .type('form')\n *         .send({ name: 'tj' })\n *         .end(callback)\n *\n *       // defaults to x-www-form-urlencoded\n  *      request.post('/user')\n  *        .send('name=tobi')\n  *        .send('species=ferret')\n  *        .end(callback)\n *\n * @param {String|Object} data\n * @return {Request} for chaining\n * @api public\n */\n\nRequest.prototype.send = function(data){\n  var obj = isObject(data);\n  var type = this.getHeader('Content-Type');\n\n  // merge\n  if (obj && isObject(this._data)) {\n    for (var key in data) {\n      this._data[key] = data[key];\n    }\n  } else if ('string' == typeof data) {\n    if (!type) this.type('form');\n    type = this.getHeader('Content-Type');\n    if ('application/x-www-form-urlencoded' == type) {\n      this._data = this._data\n        ? this._data + '&' + data\n        : data;\n    } else {\n      this._data = (this._data || '') + data;\n    }\n  } else {\n    this._data = data;\n  }\n\n  if (!obj) return this;\n  if (!type) this.type('json');\n  return this;\n};\n\n/**\n * Invoke the callback with `err` and `res`\n * and handle arity check.\n *\n * @param {Error} err\n * @param {Response} res\n * @api private\n */\n\nRequest.prototype.callback = function(err, res){\n  var fn = this._callback;\n  this.clearTimeout();\n  if (2 == fn.length) return fn(err, res);\n  if (err) return this.emit('error', err);\n  fn(res);\n};\n\n/**\n * Invoke callback with x-domain error.\n *\n * @api private\n */\n\nRequest.prototype.crossDomainError = function(){\n  var err = new Error('Origin is not allowed by Access-Control-Allow-Origin');\n  err.crossDomain = true;\n  this.callback(err);\n};\n\n/**\n * Invoke callback with timeout error.\n *\n * @api private\n */\n\nRequest.prototype.timeoutError = function(){\n  var timeout = this._timeout;\n  var err = new Error('timeout of ' + timeout + 'ms exceeded');\n  err.timeout = timeout;\n  this.callback(err);\n};\n\n/**\n * Enable transmission of cookies with x-domain requests.\n *\n * Note that for this to work the origin must not be\n * using \"Access-Control-Allow-Origin\" with a wildcard,\n * and also must set \"Access-Control-Allow-Credentials\"\n * to \"true\".\n *\n * @api public\n */\n\nRequest.prototype.withCredentials = function(){\n  this._withCredentials = true;\n  return this;\n};\n\n/**\n * Initiate request, invoking callback `fn(res)`\n * with an instanceof `Response`.\n *\n * @param {Function} fn\n * @return {Request} for chaining\n * @api public\n */\n\nRequest.prototype.end = function(fn){\n  var self = this;\n  var xhr = this.xhr = getXHR();\n  var query = this._query.join('&');\n  var timeout = this._timeout;\n  var data = this._formData || this._data;\n\n  // store callback\n  this._callback = fn || noop;\n\n  // state change\n  xhr.onreadystatechange = function(){\n    if (4 != xhr.readyState) return;\n    if (0 == xhr.status) {\n      if (self.aborted) return self.timeoutError();\n      return self.crossDomainError();\n    }\n    self.emit('end');\n  };\n\n  // progress\n  if (xhr.upload) {\n    xhr.upload.onprogress = function(e){\n      e.percent = e.loaded / e.total * 100;\n      self.emit('progress', e);\n    };\n  }\n\n  // timeout\n  if (timeout && !this._timer) {\n    this._timer = setTimeout(function(){\n      self.abort();\n    }, timeout);\n  }\n\n  // querystring\n  if (query) {\n    query = request.serializeObject(query);\n    this.url += ~this.url.indexOf('?')\n      ? '&' + query\n      : '?' + query;\n  }\n\n  // initiate request\n  xhr.open(this.method, this.url, true);\n\n  // CORS\n  if (this._withCredentials) xhr.withCredentials = true;\n\n  // body\n  if ('GET' != this.method && 'HEAD' != this.method && 'string' != typeof data && !isHost(data)) {\n    // serialize stuff\n    var serialize = request.serialize[this.getHeader('Content-Type')];\n    if (serialize) data = serialize(data);\n  }\n\n  // set header fields\n  for (var field in this.header) {\n    if (null == this.header[field]) continue;\n    xhr.setRequestHeader(field, this.header[field]);\n  }\n\n  // send stuff\n  this.emit('request', this);\n  xhr.send(data);\n  return this;\n};\n\n/**\n * Expose `Request`.\n */\n\nrequest.Request = Request;\n\n/**\n * Issue a request:\n *\n * Examples:\n *\n *    request('GET', '/users').end(callback)\n *    request('/users').end(callback)\n *    request('/users', callback)\n *\n * @param {String} method\n * @param {String|Function} url or callback\n * @return {Request}\n * @api public\n */\n\nfunction request(method, url) {\n  // callback\n  if ('function' == typeof url) {\n    return new Request('GET', method).end(url);\n  }\n\n  // url first\n  if (1 == arguments.length) {\n    return new Request('GET', method);\n  }\n\n  return new Request(method, url);\n}\n\n/**\n * GET `url` with optional callback `fn(res)`.\n *\n * @param {String} url\n * @param {Mixed|Function} data or fn\n * @param {Function} fn\n * @return {Request}\n * @api public\n */\n\nrequest.get = function(url, data, fn){\n  var req = request('GET', url);\n  if ('function' == typeof data) fn = data, data = null;\n  if (data) req.query(data);\n  if (fn) req.end(fn);\n  return req;\n};\n\n/**\n * HEAD `url` with optional callback `fn(res)`.\n *\n * @param {String} url\n * @param {Mixed|Function} data or fn\n * @param {Function} fn\n * @return {Request}\n * @api public\n */\n\nrequest.head = function(url, data, fn){\n  var req = request('HEAD', url);\n  if ('function' == typeof data) fn = data, data = null;\n  if (data) req.send(data);\n  if (fn) req.end(fn);\n  return req;\n};\n\n/**\n * DELETE `url` with optional callback `fn(res)`.\n *\n * @param {String} url\n * @param {Function} fn\n * @return {Request}\n * @api public\n */\n\nrequest.del = function(url, fn){\n  var req = request('DELETE', url);\n  if (fn) req.end(fn);\n  return req;\n};\n\n/**\n * PATCH `url` with optional `data` and callback `fn(res)`.\n *\n * @param {String} url\n * @param {Mixed} data\n * @param {Function} fn\n * @return {Request}\n * @api public\n */\n\nrequest.patch = function(url, data, fn){\n  var req = request('PATCH', url);\n  if ('function' == typeof data) fn = data, data = null;\n  if (data) req.send(data);\n  if (fn) req.end(fn);\n  return req;\n};\n\n/**\n * POST `url` with optional `data` and callback `fn(res)`.\n *\n * @param {String} url\n * @param {Mixed} data\n * @param {Function} fn\n * @return {Request}\n * @api public\n */\n\nrequest.post = function(url, data, fn){\n  var req = request('POST', url);\n  if ('function' == typeof data) fn = data, data = null;\n  if (data) req.send(data);\n  if (fn) req.end(fn);\n  return req;\n};\n\n/**\n * PUT `url` with optional `data` and callback `fn(res)`.\n *\n * @param {String} url\n * @param {Mixed|Function} data or fn\n * @param {Function} fn\n * @return {Request}\n * @api public\n */\n\nrequest.put = function(url, data, fn){\n  var req = request('PUT', url);\n  if ('function' == typeof data) fn = data, data = null;\n  if (data) req.send(data);\n  if (fn) req.end(fn);\n  return req;\n};\n\n/**\n * Expose `request`.\n */\n\nmodule.exports = request;\n\n},{\"emitter\":5,\"reduce\":8}]},{},[1])(1)\n});"
  },
  {
    "path": "lib/soda-js.js",
    "content": "// Generated by CoffeeScript 1.6.3\nvar Connection, Consumer, Dataset, EventEmitter, Operation, Producer, Query, addExpr, base64Lookup, eelib, expr, extend, handleLiteral, handleOrder, httpClient, isArray, isNumber, isString, rawToBase64, toBase64, toQuerystring,\n  __slice = [].slice,\n  __hasProp = {}.hasOwnProperty;\n\neelib = require('eventemitter2');\n\nEventEmitter = eelib.EventEmitter2 || eelib;\n\nhttpClient = require('superagent');\n\nisString = function(obj) {\n  return typeof obj === 'string';\n};\n\nisArray = function(obj) {\n  return Array.isArray(obj);\n};\n\nisNumber = function(obj) {\n  return !isNaN(parseFloat(obj));\n};\n\nextend = function() {\n  var k, source, sources, target, v, _i, _len;\n  target = arguments[0], sources = 2 <= arguments.length ? __slice.call(arguments, 1) : [];\n  for (_i = 0, _len = sources.length; _i < _len; _i++) {\n    source = sources[_i];\n    for (k in source) {\n      v = source[k];\n      target[k] = v;\n    }\n  }\n  return null;\n};\n\ntoBase64 = typeof Buffer !== \"undefined\" && Buffer !== null ? function(str) {\n  return new Buffer(str).toString('base64');\n} : (base64Lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='.split(''), rawToBase64 = typeof btoa !== \"undefined\" && btoa !== null ? btoa : function(str) {\n  var chr1, chr2, chr3, enc1, enc2, enc3, enc4, i, result;\n  result = [];\n  i = 0;\n  while (i < str.length) {\n    chr1 = str.charCodeAt(i++);\n    chr2 = str.charCodeAt(i++);\n    chr3 = str.charCodeAt(i++);\n    if (Math.max(chr1, chr2, chr3) > 0xFF) {\n      throw new Error('Invalid character!');\n    }\n    enc1 = chr1 >> 2;\n    enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);\n    enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);\n    enc4 = chr3 & 63;\n    if (isNaN(chr2)) {\n      enc3 = enc4 = 64;\n    } else if (isNaN(chr3)) {\n      enc4 = 64;\n    }\n    result.push(base64Lookup[enc1]);\n    result.push(base64Lookup[enc2]);\n    result.push(base64Lookup[enc3]);\n    result.push(base64Lookup[enc4]);\n  }\n  return result.join('');\n}, function(str) {\n  return rawToBase64(unescape(encodeURIComponent(str)));\n});\n\nhandleLiteral = function(literal) {\n  if (isString(literal)) {\n    return \"'\" + literal + \"'\";\n  } else if (isNumber(literal)) {\n    return literal;\n  } else {\n    return literal;\n  }\n};\n\nhandleOrder = function(order) {\n  if (/( asc$| desc$)/i.test(order)) {\n    return order;\n  } else {\n    return order + ' asc';\n  }\n};\n\naddExpr = function(target, args) {\n  var arg, k, v, _i, _len, _results;\n  _results = [];\n  for (_i = 0, _len = args.length; _i < _len; _i++) {\n    arg = args[_i];\n    if (isString(arg)) {\n      _results.push(target.push(arg));\n    } else {\n      _results.push((function() {\n        var _results1;\n        _results1 = [];\n        for (k in arg) {\n          v = arg[k];\n          _results1.push(target.push(\"\" + k + \" = \" + (handleLiteral(v))));\n        }\n        return _results1;\n      })());\n    }\n  }\n  return _results;\n};\n\nexpr = {\n  and: function() {\n    var clause, clauses;\n    clauses = 1 <= arguments.length ? __slice.call(arguments, 0) : [];\n    return ((function() {\n      var _i, _len, _results;\n      _results = [];\n      for (_i = 0, _len = clauses.length; _i < _len; _i++) {\n        clause = clauses[_i];\n        _results.push(\"(\" + clause + \")\");\n      }\n      return _results;\n    })()).join(' and ');\n  },\n  or: function() {\n    var clause, clauses;\n    clauses = 1 <= arguments.length ? __slice.call(arguments, 0) : [];\n    return ((function() {\n      var _i, _len, _results;\n      _results = [];\n      for (_i = 0, _len = clauses.length; _i < _len; _i++) {\n        clause = clauses[_i];\n        _results.push(\"(\" + clause + \")\");\n      }\n      return _results;\n    })()).join(' or ');\n  },\n  gt: function(column, literal) {\n    return \"\" + column + \" > \" + (handleLiteral(literal));\n  },\n  gte: function(column, literal) {\n    return \"\" + column + \" >= \" + (handleLiteral(literal));\n  },\n  lt: function(column, literal) {\n    return \"\" + column + \" < \" + (handleLiteral(literal));\n  },\n  lte: function(column, literal) {\n    return \"\" + column + \" <= \" + (handleLiteral(literal));\n  },\n  eq: function(column, literal) {\n    return \"\" + column + \" = \" + (handleLiteral(literal));\n  }\n};\n\ntoQuerystring = function(obj) {\n  var key, str, val;\n  str = [];\n  for (key in obj) {\n    if (!__hasProp.call(obj, key)) continue;\n    val = obj[key];\n    str.push(encodeURIComponent(key) + '=' + encodeURIComponent(val));\n  }\n  return str.join('&');\n};\n\nConnection = (function() {\n  function Connection(dataSite, sodaOpts) {\n    var _ref;\n    this.dataSite = dataSite;\n    this.sodaOpts = sodaOpts != null ? sodaOpts : {};\n    if (!/^[a-z0-9-_.]+(:[0-9]+)?$/i.test(this.dataSite)) {\n      throw new Error('dataSite does not appear to be valid! Please supply a domain name, eg data.seattle.gov');\n    }\n    this.emitterOpts = (_ref = this.sodaOpts.emitterOpts) != null ? _ref : {\n      wildcard: true,\n      delimiter: '.',\n      maxListeners: 15\n    };\n    this.networker = function(opts, data) {\n      var client, url,\n        _this = this;\n      url = \"https://\" + this.dataSite + opts.path;\n      client = httpClient(opts.method, url);\n      if (data != null) {\n        client.set('Accept', \"application/json\");\n      }\n      if (data != null) {\n        client.set('Content-type', \"application/json\");\n      }\n      if (this.sodaOpts.apiToken != null) {\n        client.set('X-App-Token', this.sodaOpts.apiToken);\n      }\n      if ((this.sodaOpts.username != null) && (this.sodaOpts.password != null)) {\n        client.set('Authorization', \"Basic \" + toBase64(\"\" + this.sodaOpts.username + \":\" + this.sodaOpts.password));\n      }\n      if (this.sodaOpts.accessToken != null) {\n        client.set('Authorization', \"OAuth \" + accessToken);\n      }\n      if (opts.query != null) {\n        client.query(opts.query);\n      }\n      if (data != null) {\n        client.send(data);\n      }\n      return function(responseHandler) {\n        return client.end(responseHandler || _this.getDefaultHandler());\n      };\n    };\n  }\n\n  Connection.prototype.getDefaultHandler = function() {\n    var emitter, handler;\n    this.emitter = emitter = new EventEmitter(this.emitterOpts);\n    return handler = function(error, response) {\n      var _ref;\n      if (response.ok) {\n        if (response.accepted) {\n          emitter.emit('progress', response.body);\n          setTimeout((function() {\n            return this.consumer.networker(opts)(handler);\n          }), 5000);\n        } else {\n          emitter.emit('success', response.body);\n        }\n      } else {\n        emitter.emit('error', (_ref = response.body) != null ? _ref : response.text);\n      }\n      return emitter.emit('complete', response);\n    };\n  };\n\n  return Connection;\n\n})();\n\nConsumer = (function() {\n  function Consumer(dataSite, sodaOpts) {\n    this.dataSite = dataSite;\n    this.sodaOpts = sodaOpts != null ? sodaOpts : {};\n    this.connection = new Connection(this.dataSite, this.sodaOpts);\n  }\n\n  Consumer.prototype.query = function() {\n    return new Query(this);\n  };\n\n  Consumer.prototype.getDataset = function(id) {\n    var emitter;\n    return emitter = new EventEmitter(this.emitterOpts);\n  };\n\n  return Consumer;\n\n})();\n\nProducer = (function() {\n  function Producer(dataSite, sodaOpts) {\n    this.dataSite = dataSite;\n    this.sodaOpts = sodaOpts != null ? sodaOpts : {};\n    this.connection = new Connection(this.dataSite, this.sodaOpts);\n  }\n\n  Producer.prototype.operation = function() {\n    return new Operation(this);\n  };\n\n  return Producer;\n\n})();\n\nOperation = (function() {\n  function Operation(producer) {\n    this.producer = producer;\n  }\n\n  Operation.prototype.withDataset = function(datasetId) {\n    this._datasetId = datasetId;\n    return this;\n  };\n\n  Operation.prototype.truncate = function() {\n    var opts;\n    opts = {\n      method: 'delete'\n    };\n    opts.path = \"/resource/\" + this._datasetId;\n    return this._exec(opts);\n  };\n\n  Operation.prototype.add = function(data) {\n    var obj, opts, _data, _i, _len;\n    opts = {\n      method: 'post'\n    };\n    opts.path = \"/resource/\" + this._datasetId;\n    _data = JSON.parse(JSON.stringify(data));\n    delete _data[':id'];\n    delete _data[':delete'];\n    for (_i = 0, _len = _data.length; _i < _len; _i++) {\n      obj = _data[_i];\n      delete obj[':id'];\n      delete obj[':delete'];\n    }\n    return this._exec(opts, _data);\n  };\n\n  Operation.prototype[\"delete\"] = function(id) {\n    var opts;\n    opts = {\n      method: 'delete'\n    };\n    opts.path = \"/resource/\" + this._datasetId + \"/\" + id;\n    return this._exec(opts);\n  };\n\n  Operation.prototype.update = function(id, data) {\n    var opts;\n    opts = {\n      method: 'post'\n    };\n    opts.path = \"/resource/\" + this._datasetId + \"/\" + id;\n    return this._exec(opts, data);\n  };\n\n  Operation.prototype.replace = function(id, data) {\n    var opts;\n    opts = {\n      method: 'put'\n    };\n    opts.path = \"/resource/\" + this._datasetId + \"/\" + id;\n    return this._exec(opts, data);\n  };\n\n  Operation.prototype.upsert = function(data) {\n    var opts;\n    opts = {\n      method: 'post'\n    };\n    opts.path = \"/resource/\" + this._datasetId;\n    return this._exec(opts, data);\n  };\n\n  Operation.prototype._exec = function(opts, data) {\n    if (this._datasetId == null) {\n      throw new Error('no dataset given to work against!');\n    }\n    this.producer.connection.networker(opts, data)();\n    return this.producer.connection.emitter;\n  };\n\n  return Operation;\n\n})();\n\nQuery = (function() {\n  function Query(consumer) {\n    this.consumer = consumer;\n    this._select = [];\n    this._where = [];\n    this._group = [];\n    this._having = [];\n    this._order = [];\n    this._offset = this._limit = this._q = null;\n  }\n\n  Query.prototype.withDataset = function(datasetId) {\n    this._datasetId = datasetId;\n    return this;\n  };\n\n  Query.prototype.soql = function(query) {\n    this._soql = query;\n    return this;\n  };\n\n  Query.prototype.select = function() {\n    var select, selects, _i, _len;\n    selects = 1 <= arguments.length ? __slice.call(arguments, 0) : [];\n    for (_i = 0, _len = selects.length; _i < _len; _i++) {\n      select = selects[_i];\n      this._select.push(select);\n    }\n    return this;\n  };\n\n  Query.prototype.where = function() {\n    var args;\n    args = 1 <= arguments.length ? __slice.call(arguments, 0) : [];\n    addExpr(this._where, args);\n    return this;\n  };\n\n  Query.prototype.having = function() {\n    var args;\n    args = 1 <= arguments.length ? __slice.call(arguments, 0) : [];\n    addExpr(this._having, args);\n    return this;\n  };\n\n  Query.prototype.group = function() {\n    var group, groups, _i, _len;\n    groups = 1 <= arguments.length ? __slice.call(arguments, 0) : [];\n    for (_i = 0, _len = groups.length; _i < _len; _i++) {\n      group = groups[_i];\n      this._group.push(group);\n    }\n    return this;\n  };\n\n  Query.prototype.order = function() {\n    var order, orders, _i, _len;\n    orders = 1 <= arguments.length ? __slice.call(arguments, 0) : [];\n    for (_i = 0, _len = orders.length; _i < _len; _i++) {\n      order = orders[_i];\n      this._order.push(handleOrder(order));\n    }\n    return this;\n  };\n\n  Query.prototype.offset = function(offset) {\n    this._offset = offset;\n    return this;\n  };\n\n  Query.prototype.limit = function(limit) {\n    this._limit = limit;\n    return this;\n  };\n\n  Query.prototype.q = function(q) {\n    this._q = q;\n    return this;\n  };\n\n  Query.prototype.getOpts = function() {\n    var k, opts, queryComponents, v;\n    opts = {\n      method: 'get'\n    };\n    if (this._datasetId == null) {\n      throw new Error('no dataset given to work against!');\n    }\n    opts.path = \"/resource/\" + this._datasetId + \".json\";\n    queryComponents = this._buildQueryComponents();\n    opts.query = {};\n    for (k in queryComponents) {\n      v = queryComponents[k];\n      opts.query['$' + k] = v;\n    }\n    return opts;\n  };\n\n  Query.prototype.getURL = function() {\n    var opts, query;\n    opts = this.getOpts();\n    query = toQuerystring(opts.query);\n    return (\"https://\" + this.consumer.dataSite + opts.path) + (query ? \"?\" + query : \"\");\n  };\n\n  Query.prototype.getRows = function() {\n    var opts;\n    opts = this.getOpts();\n    this.consumer.connection.networker(opts)();\n    return this.consumer.connection.emitter;\n  };\n\n  Query.prototype._buildQueryComponents = function() {\n    var query;\n    query = {};\n    if (this._soql != null) {\n      query.query = this._soql;\n    } else {\n      if (this._select.length > 0) {\n        query.select = this._select.join(', ');\n      }\n      if (this._where.length > 0) {\n        query.where = expr.and.apply(this, this._where);\n      }\n      if (this._group.length > 0) {\n        query.group = this._group.join(', ');\n      }\n      if (this._having.length > 0) {\n        if (!(this._group.length > 0)) {\n          throw new Error('Having provided without group by!');\n        }\n        query.having = expr.and.apply(this, this._having);\n      }\n      if (this._order.length > 0) {\n        query.order = this._order.join(', ');\n      }\n      if (isNumber(this._offset)) {\n        query.offset = this._offset;\n      }\n      if (isNumber(this._limit)) {\n        query.limit = this._limit;\n      }\n      if (this._q) {\n        query.q = this._q;\n      }\n    }\n    return query;\n  };\n\n  return Query;\n\n})();\n\nDataset = (function() {\n  function Dataset(data, client) {\n    this.data = data;\n    this.client = client;\n  }\n\n  return Dataset;\n\n})();\n\nextend(typeof exports !== \"undefined\" && exports !== null ? exports : this.soda, {\n  Consumer: Consumer,\n  Producer: Producer,\n  expr: expr,\n  _internal: {\n    Connection: Connection,\n    Query: Query,\n    Operation: Operation,\n    util: {\n      toBase64: toBase64,\n      handleLiteral: handleLiteral,\n      handleOrder: handleOrder\n    }\n  }\n});\n"
  },
  {
    "path": "package.json",
    "content": "{\n  \"name\": \"soda-js\",\n  \"description\": \"js library for accessing a soda2 api\",\n  \"homepage\": \"https://github.com/socrata/soda-js\",\n  \"keywords\": [\n    \"socrata\",\n    \"soda\",\n    \"api\",\n    \"opendata\",\n    \"open data\"\n  ],\n  \"contributors\": [\n    {\n      \"name\": \"Clint Tseng\",\n      \"email\": \"clint.tseng@socrata.com\"\n    }\n  ],\n  \"dependencies\": {\n    \"eventemitter2\": \"~0.4.14\",\n    \"superagent\": \"^3.7.0\"\n  },\n  \"devDependencies\": {\n    \"coffee-script\": \"~1.6.3\",\n    \"expresso\": \"~0.9.2\",\n    \"browserify\": \"^12.0.1\"\n  },\n  \"licenses\": [\n    {\n      \"type\": \"MIT\"\n    }\n  ],\n  \"scripts\": {\n    \"test\": \"node_modules/expresso/bin/expresso test/*\",\n    \"coffee\": \"node_modules/coffee-script/bin/cake build\",\n    \"bundle\": \"browserify lib/soda-js.js --standalone soda > lib/soda-js.bundle.js\",\n    \"build\": \"npm run coffee && npm run bundle\"\n  },\n  \"main\": \"./lib/soda-js.js\",\n  \"version\": \"0.2.4\"\n}\n"
  },
  {
    "path": "sample/basic_producer.js",
    "content": "var soda = require('../lib/soda-js');\n\nvar sodaOpts = {\n        \"username\": \"testuser@gmail.com\",\n        \"password\" : \"OpenData\",\n        \"apiToken\" : \"D8Atrg62F2j017ZTdkMpuZ9vY\"\n}\nvar producer = new soda.Producer('sandbox.demo.socrata.com', sodaOpts);\n\n\nvar addSample = function() {\n  var data = {\n    mynum : 42,\n    mytext: \"hello world\",\n    mymoney: 999.99\n  }\n\n  console.log(\"Adding Sample\")\n  producer.operation()\n    .withDataset('rphc-ayt9')\n    .add(data)\n      .on('success', function(row) { console.log(row); updateSample(row[':id']); })\n      .on('error', function(error) { console.error(error); })\n}\n\nvar updateSample = function(id) {\n  var data = { mytext: \"goodbye world\" }\n\n  console.log(\"\\nUpdating Sample\")\n  producer.operation()\n    .withDataset('rphc-ayt9')\n    .update(id, data)\n      .on('success', function(row) { console.log(row); deleteSample(row[':id']); })\n      .on('error', function(error) { console.error(error); })\n}\n\n\nvar deleteSample = function(id) {\n  console.log(\"\\nDeleting Sample\")\n  producer.operation()\n    .withDataset('rphc-ayt9')\n    .delete(id)\n      .on('success', function(row) { console.log(row); })\n      .on('error', function(error) { console.error(error); })\n}\n\n\n\naddSample();"
  },
  {
    "path": "sample/basic_query.js",
    "content": "var soda = require('../lib/soda-js');\n\nvar consumer = new soda.Consumer('open.whitehouse.gov');\n\nconsumer.query()\n  .withDataset('p86s-ychb')\n  .limit(5)\n  .where({ namelast: 'SMITH' })\n  .order('namelast')\n  .getRows()\n    .on('success', function(rows) { console.log(rows); })\n    .on('error', function(error) { console.error(error); });\n\n"
  },
  {
    "path": "sample/browser.html",
    "content": "<!DOCTYPE html>\n<html>\n\t<head>\n\t\t<meta charset=\"utf-8\">\n\t\t<title>soda-js sample</title>\n\t</head>\n\t<body>\n\t\t<script src=\"../lib/soda-js.bundle.js\"></script>\n\t\t<script>\n\t\t\tvar consumer = new soda.Consumer('data.phila.gov');\n\n\t\t\tconsumer.query()\n\t\t\t\t.withDataset('2pfz-fnns')\n\t\t\t\t.limit(5)\n\t\t\t\t.where({ issuing_agency: 'POLICE' })\n\t\t\t\t.order('fine')\n\t\t\t\t.getRows()\n\t\t\t\t\t.on('success', function(rows) { console.log(rows); })\n\t\t\t\t\t.on('error', function(error) { console.error(error); });\n\t\t</script>\n\t</body>\n</html>"
  },
  {
    "path": "src/soda-js.coffee",
    "content": "# soda.coffee -- chained, evented, buzzworded library for accessing SODA via JS.\n\n# sodaOpts options:\n#   username: https basic auth username\n#   password: https basic auth password\n#   apiToken: socrata api token\n#\n#   emitterOpts: options to override EventEmitter2 declaration options\n\n#  TODO:\n#    * we're inconsistent about validating query correctness. do we continue with catch-what-we-can,\n#      or do we just back off and leave all failures to the api to return?\n\neelib = require('eventemitter2')\nEventEmitter = eelib.EventEmitter2 || eelib\nhttpClient = require('superagent')\n\n# internal util funcs\nisString = (obj) -> typeof obj == 'string'\nisArray = (obj) -> Array.isArray(obj)\nisNumber = (obj) -> !isNaN(parseFloat(obj))\nextend = (target, sources...) -> (target[k] = v for k, v of source) for source in sources; null\n\n# it's really, really, really stupid that i have to solve this problem here\ntoBase64 =\n  if Buffer?\n    (str) -> new Buffer(str).toString('base64')\n  else\n    # adapted/modified from https://github.com/rwz/base64.coffee\n    base64Lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='.split('')\n    rawToBase64 = btoa ? (str) ->\n      result = []\n      i = 0\n      while i < str.length\n        chr1 = str.charCodeAt(i++)\n        chr2 = str.charCodeAt(i++)\n        chr3 = str.charCodeAt(i++)\n        throw new Error('Invalid character!') if Math.max(chr1, chr2, chr3) > 0xFF\n\n        enc1 = chr1 >> 2\n        enc2 = ((chr1 & 3) << 4) | (chr2 >> 4)\n        enc3 = ((chr2 & 15) << 2) | (chr3 >> 6)\n        enc4 = chr3 & 63\n\n        if isNaN(chr2)\n          enc3 = enc4 = 64\n        else if isNaN(chr3)\n          enc4 = 64\n\n        result.push(base64Lookup[enc1])\n        result.push(base64Lookup[enc2])\n        result.push(base64Lookup[enc3])\n        result.push(base64Lookup[enc4])\n      result.join('')\n    (str) -> rawToBase64(unescape(encodeURIComponent(str)))\n\nhandleLiteral = (literal) ->\n  if isString(literal)\n    \"'#{literal}'\"\n  else if isNumber(literal)\n    # TODO: possibly ensure number cleanliness for sending to the api? sci not?\n    literal\n  else\n    literal\n\nhandleOrder = (order) ->\n  if /( asc$| desc$)/i.test(order)\n    order\n  else\n    order + ' asc'\n\naddExpr = (target, args) ->\n  for arg in args\n    if isString(arg)\n      target.push(arg)\n    else\n      target.push(\"#{k} = #{handleLiteral(v)}\") for k, v of arg\n\n# extern util funcs\n\n# convenience functions for building where clauses, if so desired\nexpr =\n  and: (clauses...) -> (\"(#{clause})\" for clause in clauses).join(' and ')\n  or:  (clauses...) -> (\"(#{clause})\" for clause in clauses).join(' or ')\n\n  gt:  (column, literal) -> \"#{column} > #{handleLiteral(literal)}\"\n  gte: (column, literal) -> \"#{column} >= #{handleLiteral(literal)}\"\n  lt:  (column, literal) -> \"#{column} < #{handleLiteral(literal)}\"\n  lte: (column, literal) -> \"#{column} <= #{handleLiteral(literal)}\"\n  eq:  (column, literal) -> \"#{column} = #{handleLiteral(literal)}\"\n  \n# serialize object to querystring\ntoQuerystring = (obj) ->\n  str = []\n  for own key, val of obj\n    str.push encodeURIComponent(key) + '=' + encodeURIComponent(val)\n  str.join '&'\n\nclass Connection\n  constructor: (@dataSite, @sodaOpts = {}) ->\n    throw new Error('dataSite does not appear to be valid! Please supply a domain name, eg data.seattle.gov') unless /^[a-z0-9-_.]+(:[0-9]+)?$/i.test(@dataSite)\n\n    # options passed directly into EventEmitter2 construction\n    @emitterOpts = @sodaOpts.emitterOpts ?\n      wildcard: true,\n      delimiter: '.',\n      maxListeners: 15\n\n    @networker = (opts, data) ->\n      url = \"https://#{@dataSite}#{opts.path}\"\n\n      client = httpClient(opts.method, url)\n\n      client.set('Accept', \"application/json\") if data?\n      client.set('Content-type', \"application/json\") if data?\n      client.set('X-App-Token', @sodaOpts.apiToken) if @sodaOpts.apiToken?\n      client.set('Authorization', \"Basic \" + toBase64(\"#{@sodaOpts.username}:#{@sodaOpts.password}\")) if @sodaOpts.username? and @sodaOpts.password?\n      client.set('Authorization', \"OAuth \" + accessToken) if @sodaOpts.accessToken?\n\n      client.query(opts.query) if opts.query?\n      client.send(data) if data?\n\n      (responseHandler) => client.end(responseHandler || @getDefaultHandler())\n\n  getDefaultHandler: ->\n    # instance variable for easy chaining\n    @emitter = emitter = new EventEmitter(@emitterOpts)\n\n    # return the handler\n    handler = (error, response) ->\n      # TODO: possibly more granular handling?\n      if response.ok\n        if response.accepted\n          # handle 202 by remaking request. inform of possible progress.\n          emitter.emit('progress', response.body)\n          setTimeout((-> @consumer.networker(opts)(handler)), 5000)\n        else\n          emitter.emit('success', response.body)\n      else\n        emitter.emit('error', response.body ? response.text)\n\n      # just emit the raw superagent obj if they just want complete event\n      emitter.emit('complete', response)\n\n\n\n\n# main class\nclass Consumer\n  constructor: (@dataSite, @sodaOpts = {}) ->\n    @connection = new Connection(@dataSite, @sodaOpts)\n\n  query: ->\n    new Query(this)\n\n  getDataset: (id) ->\n    emitter = new EventEmitter(@emitterOpts)\n    # TODO: implement me\n\n# Producer class\nclass Producer\n  constructor: (@dataSite, @sodaOpts = {}) ->\n    @connection = new Connection(@dataSite, @sodaOpts)\n\n  operation: ->\n    new Operation(this)\n\nclass Operation\n  constructor: (@producer) ->\n\n  withDataset: (datasetId) -> @_datasetId = datasetId; this\n\n  # truncate the entire dataset\n  truncate: ->\n    opts = method: 'delete'\n    opts.path = \"/resource/#{@_datasetId}\"\n    this._exec(opts)\n\n  # add a new row - explicitly avoids upserting (updating/deleting existing rows)\n  add: (data) ->\n    opts = method: 'post'\n    opts.path = \"/resource/#{@_datasetId}\"\n\n    _data = JSON.parse(JSON.stringify(data))\n    delete _data[':id']\n    delete _data[':delete']\n    for obj in _data\n      delete obj[':id']\n      delete obj[':delete']\n\n    this._exec(opts, _data)\n\n  # modify existing rows\n  delete: (id) ->\n    opts = method: 'delete'\n    opts.path = \"/resource/#{@_datasetId}/#{id}\"\n    this._exec(opts)\n  update: (id, data) ->\n    opts = method: 'post'\n    opts.path = \"/resource/#{@_datasetId}/#{id}\"\n    this._exec(opts, data)\n  replace: (id, data) ->\n    opts = method: 'put'\n    opts.path = \"/resource/#{@_datasetId}/#{id}\"\n    this._exec(opts, data)\n  \n  # add objects, update if existing, delete if :delete=true\n  upsert: (data) ->\n    opts = method: 'post'\n    opts.path = \"/resource/#{@_datasetId}\"\n    this._exec(opts, data)\n\n  _exec: (opts, data) ->\n    throw new Error('no dataset given to work against!') unless @_datasetId?\n    @producer.connection.networker(opts, data)()\n    @producer.connection.emitter\n\n\n# querybuilder class\nclass Query\n  constructor: (@consumer) ->\n    @_select = []\n    @_where = []\n    @_group = []\n    @_having = []\n    @_order = []\n    @_offset = @_limit = @_q = null\n\n  withDataset: (datasetId) -> @_datasetId = datasetId; this\n\n  # for passing in a fully formed soql query. all other params will be ignored\n  soql: (query) -> @_soql = query; this\n\n  select: (selects...) -> @_select.push(select) for select in selects; this\n\n  # args: ('clause', [...])\n  #       ({ column: value1, columnb: value2 }, [...]])\n  # multiple calls are assumed to be and-chained\n  where: (args...) -> addExpr(@_where, args); this\n  having: (args...) -> addExpr(@_having, args); this\n\n  group: (groups...) -> @_group.push(group) for group in groups; this\n\n  # args: (\"column direction\", [\"column direction\", [...]])\n  order: (orders...) -> @_order.push(handleOrder(order)) for order in orders; this\n\n  offset: (offset) -> @_offset = offset; this\n\n  limit: (limit) -> @_limit = limit; this\n  \n  q: (q) -> @_q = q; this\n\n  getOpts: ->\n    opts = method: 'get'\n    \n    throw new Error('no dataset given to work against!') unless @_datasetId?\n    opts.path = \"/resource/#{@_datasetId}.json\"\n\n    queryComponents = this._buildQueryComponents()\n    opts.query = {}\n    opts.query['$' + k] = v for k, v of queryComponents\n    \n    opts\n    \n  getURL: ->\n    opts = this.getOpts()\n    query = toQuerystring(opts.query)\n    \n    \"https://#{@consumer.dataSite}#{opts.path}\" + (if query then \"?#{query}\" else \"\")\n\n  getRows: ->\n    opts = this.getOpts()\n\n    @consumer.connection.networker(opts)()\n    @consumer.connection.emitter\n\n  _buildQueryComponents: ->\n    query = {}\n\n    if @_soql?\n      query.query = @_soql\n    else\n      query.select = @_select.join(', ') if @_select.length > 0\n\n      query.where = expr.and.apply(this, @_where) if @_where.length > 0\n\n      query.group = @_group.join(', ') if @_group.length > 0\n\n      if @_having.length > 0\n        throw new Error('Having provided without group by!') unless @_group.length > 0\n        query.having = expr.and.apply(this, @_having)\n\n      query.order = @_order.join(', ') if @_order.length > 0\n\n      query.offset = @_offset if isNumber(@_offset)\n      query.limit = @_limit if isNumber(@_limit)\n      \n      query.q = @_q if @_q\n\n    query\n\nclass Dataset\n  constructor: (@data, @client) ->\n    # TODO: implement me\n\nextend(exports ? this.soda,\n  Consumer: Consumer,\n  Producer: Producer,\n  expr: expr,\n\n  # exported for testing reasons\n  _internal:\n    Connection: Connection,\n    Query: Query,\n    Operation: Operation,\n    util:\n      toBase64: toBase64,\n      handleLiteral: handleLiteral,\n      handleOrder: handleOrder\n)\n\n"
  },
  {
    "path": "test/connection_tests.coffee",
    "content": "\nsoda = require('../lib/soda-js')\n\nmodule.exports =\n  \n  'basic construction': (beforeExit, assert) ->\n    connection = new soda._internal.Connection('opendata.socrata.com')\n    assert.eql(connection.dataSite, 'opendata.socrata.com')\n\n  'failed construction': (beforeExit, assert) ->\n    caught = false\n    try\n      connection = new soda._internal.Connection('http://data.cityofchicago.org')\n    catch ex\n      caught = true\n    assert.ok(caught)"
  },
  {
    "path": "test/consumer_tests.coffee",
    "content": "\nsoda = require('../lib/soda-js')\n\nmodule.exports =\n  'create consumer connection': (beforeExit, assert) ->\n    consumer = new soda.Producer('data.seattle.gov')\n    assert.ok(consumer.connection instanceof soda._internal.Connection)\n    assert.eql(consumer.connection.dataSite, 'data.seattle.gov')\n\n  'create query': (beforeExit, assert) ->\n    consumer = new soda.Consumer('data.seattle.gov')\n    query = consumer.query()\n    assert.ok(query instanceof soda._internal.Query)\n    assert.eql(query.consumer, consumer)\n\n"
  },
  {
    "path": "test/operation_tests.coffee",
    "content": "\nsoda = require('../lib/soda-js')\n\n# fixture generator to allow injecting verifiers as networkers\nproducer = (verifier) ->\n  connection:\n    networker: ((opts, data) -> verifier(opts, data); -> null),\n    emitterOpts:\n      wildcard: true,\n      delimiter: '.',\n      maxListeners: 15\n\n\n# convenience func for using the above fixture with an operation\noperateWith = (networker) -> new soda._internal.Operation(producer(networker))\n\nmodule.exports =\n  'basic add': (beforeExit, assert) ->\n    verifier = (opts, data) -> \n        assert.eql(opts.method, \"post\")\n        assert.eql(opts.path, \"/resource/abcd-1234\")\n        assert.eql(data, { hello: \"world\" })\n\n    operateWith(verifier)\n      .withDataset('abcd-1234')\n      .add( {hello: \"world\" })\n\n  'multiple add': (beforeExit, assert) ->\n    verifier = (opts, data) -> \n        assert.eql(opts.method, \"post\")\n        assert.eql(opts.path, \"/resource/abcd-1234\")\n        assert.eql(data.length, 3)\n\n    operateWith(verifier)\n      .withDataset('abcd-1234')\n      .add( [{col:\"a\"}, {col:\"b\"}, {col:\"c\"}] )\n\n  'add prevents upsert of object': (beforeExit, assert) ->\n    verifier = (opts, data) -> \n        assert.eql(opts.method, \"post\")\n        assert.eql(opts.path, \"/resource/abcd-1234\")\n        assert.eql(data, { col: \"c\" })\n\n    operateWith(verifier)\n      .withDataset('abcd-1234')\n      .add( { \":id\": 3, \":delete\": true, col:\"c\"} )\n\n  'add prevents upsert of array': (beforeExit, assert) ->\n    verifier = (opts, data) -> \n        assert.eql(opts.method, \"post\")\n        assert.eql(opts.path, \"/resource/abcd-1234\")\n        assert.eql(data, [\n          {col:\"a\"}, \n          {col:\"b\"}, \n          {col:\"c\"}, \n          {col:\"d\"}\n        ])\n\n    operateWith(verifier)\n      .withDataset('abcd-1234')\n      .add([\n        { \":id\": 1, col: \"a\"},\n        { col: \"b\", \":delete\": true },\n        { \":id\": 3, \":delete\": true, col:\"c\"},\n        { col: \"d\" }\n      ])\n\n\n  'upsert array': (beforeExit, assert) ->\n    verifier = (opts, data) -> \n        assert.eql(opts.method, \"post\")\n        assert.eql(opts.path, \"/resource/abcd-1234\")\n        assert.eql(data, [\n          { col: \"a\", \":id\": 1},\n          { col: \"b\", \":delete\": true },\n          { col: \"c\", \":id\": 3, \":delete\": true },\n          { col: \"d\" }\n        ])\n\n    operateWith(verifier)\n      .withDataset('abcd-1234')\n      .upsert([\n        { \":id\": 1, col: \"a\"},\n        { col: \"b\", \":delete\": true },\n        { \":id\": 3, \":delete\": true, col:\"c\"},\n        { col: \"d\" }\n      ])      \n\n  'basic truncate': (beforeExit, assert) ->\n    verifier = (opts, data) ->\n      assert.eql(opts.method, \"delete\")\n      assert.eql(opts.path, \"/resource/lmno-9876\")\n      assert.isUndefined(data)\n\n    operateWith(verifier)\n      .withDataset('lmno-9876')\n      .truncate()\n\n  'basic delete': (beforeExit, assert) ->\n    verifier = (opts, data) ->\n      assert.eql(opts.method, \"delete\")\n      assert.eql(opts.path, \"/resource/lmno-9876/123\")\n      assert.isUndefined(data)\n\n    operateWith(verifier)\n      .withDataset('lmno-9876')\n      .delete(123)\n\n  'basic update': (beforeExit, assert) ->\n    verifier = (opts, data) ->\n      assert.eql(opts.method, \"post\") # seriously, why isn't this patch?\n      assert.eql(opts.path, \"/resource/lmno-9876/123\")\n      assert.eql(data, { num : 987 })\n\n    operateWith(verifier)\n      .withDataset(\"lmno-9876\")\n      .update(123, { num : 987 })\n\n  'basic replace': (beforeExit, assert) ->\n    verifier = (opts, data) ->\n      assert.eql(opts.method, \"put\")\n      assert.eql(opts.path, \"/resource/lmno-1234/987\")\n      assert.eql(data, { num : 456 })\n\n    operateWith(verifier)\n      .withDataset(\"lmno-1234\")\n      .replace(987, { num : 456 })\n\n  "
  },
  {
    "path": "test/producer_tests.coffee",
    "content": "\nsoda = require('../lib/soda-js')\n\nmodule.exports =\n  'create producer connection': (beforeExit, assert) ->\n    producer = new soda.Producer('data.seattle.gov')\n    assert.ok(producer.connection instanceof soda._internal.Connection)\n    assert.eql(producer.connection.dataSite, 'data.seattle.gov')\n\n  'create producer operation': (beforeExit, assert) ->\n    producer = new soda.Producer('data.seattle.gov')\n    operation = producer.operation()\n    assert.ok(operation instanceof soda._internal.Operation)\n    assert.eql(operation.producer, producer)"
  },
  {
    "path": "test/query_tests.coffee",
    "content": "\nsoda = require('../lib/soda-js')\n\n# fixture generator to allow injecting verifiers as networkers\nconsumer = (verifier) ->\n  connection:\n    networker: ((opts) -> verifier(opts); -> null),\n    emitterOpts:\n      wildcard: true,\n      delimiter: '.',\n      maxListeners: 15\n\n# convenience func for using the above fixture with a query\nqueryWith = (networker) -> new soda._internal.Query(consumer(networker))\n\nmodule.exports =\n\n  'basic query': (beforeExit, assert) ->\n    verifier = (opts) ->\n      assert.eql(opts.path, '/resource/hospitals.json')\n\n    queryWith(verifier)\n      .withDataset('hospitals')\n      .getRows()\n\n  'col select': (beforeExit, assert) ->\n    verifier = (opts) ->\n      assert.eql(opts.query, { $select: 'street, city, state, zip' })\n\n    queryWith(verifier)\n      .withDataset('hospitals')\n      .select('street', 'city', 'state', 'zip')\n      .getRows()\n\n  'string expr': (beforeExit, assert) ->\n    expr = soda.expr.eq('name', 'bob')\n    assert.eql(expr, \"name = 'bob'\")\n\n  'number expr': (beforeExit, assert) ->\n    expr = soda.expr.eq('age', 15)\n    assert.eql(expr, \"age = 15\")\n\n  'compound expr': (beforeExit, assert) ->\n    expr = soda.expr.and(soda.expr.eq('columnone', 1), soda.expr.eq('columntwo', 2))\n    assert.eql(expr, '(columnone = 1) and (columntwo = 2)')\n\n  'string where': (beforeExit, assert) ->\n    verifier = (opts) ->\n      assert.eql(opts.query, { $where: '(salary > 35000) and (yearsWorked >= 5)' })\n\n    queryWith(verifier)\n      .withDataset('salaries')\n      .where('salary > 35000', 'yearsWorked >= 5')\n      .getRows()\n\n  'obj where': (beforeExit, assert) ->\n    verifier = (opts) ->\n      assert.eql(opts.query, { $where: \"(firstname = 'abed') and (lastname = 'nadir')\" })\n\n    queryWith(verifier)\n      .withDataset('people')\n      .where({ firstname: 'abed', lastname: 'nadir' })\n      .getRows()\n\n  'groupby': (beforeExit, assert) ->\n    verifier = (opts) ->\n      assert.eql(opts.query, { $group: 'department, type' })\n\n    queryWith(verifier)\n      .withDataset('payments')\n      .group('department', 'type')\n      .getRows()\n\n  'having': (beforeExit, assert) ->\n    # having is the same implementation as where, so just test a maxiquery\n    verifier = (opts) ->\n      assert.eql(opts.query,\n        $group: 'firstname, lastname, total_salary',\n        $having: \"((firstname = 'jeff') or (lastname = 'winger')) and (total_salary > 100000)\")\n\n    queryWith(verifier)\n      .withDataset('salaries')\n      .group('firstname', 'lastname', 'total_salary') # of course in reality total_salary would be an aggr func..\n      .having(soda.expr.or(soda.expr.eq('firstname', 'jeff'), soda.expr.eq('lastname', 'winger')), 'total_salary > 100000')\n      .getRows()\n\n  'orderby': (beforeExit, assert) ->\n    verifier = (opts) ->\n      assert.eql(opts.query, { $order: 'lastname asc, firstname desc' })\n\n    queryWith(verifier)\n      .withDataset('salaries')\n      .order('lastname', 'firstname desc')\n      .getRows()\n\n  'offset and limit': (beforeExit, assert) ->\n    verifier = (opts) ->\n      assert.eql(opts.query, { $offset: 5, $limit: 10 })\n\n    queryWith(verifier)\n      .withDataset('hospitals')\n      .offset(5)\n      .limit(10)\n      .getRows()\n\n"
  }
]