Full Code of nolanlawson/socket-pouch for AI

master 6911f9a47b41 cached
86 files
3.7 MB
982.7k tokens
1174 symbols
1 requests
Download .txt
Showing preview only (3,930K chars total). Download the full file or copy to clipboard to get everything.
Repository: nolanlawson/socket-pouch
Branch: master
Commit: 6911f9a47b41
Files: 86
Total size: 3.7 MB

Directory structure:
gitextract_5blrnppl/

├── .gitignore
├── .jshintrc
├── .npmignore
├── .travis.yml
├── LICENSE
├── README.md
├── bin/
│   ├── dev-server.js
│   ├── es3ify.js
│   ├── run-test.sh
│   ├── test-browser.js
│   └── test-node.sh
├── client/
│   └── index.js
├── dist/
│   └── socket-pouch.client.js
├── lib/
│   ├── client/
│   │   ├── arrayBufferToBinaryString.js
│   │   ├── base64.js
│   │   ├── base64StringToBlobOrBuffer-browser.js
│   │   ├── base64StringToBlobOrBuffer.js
│   │   ├── binaryStringToArrayBuffer.js
│   │   ├── binaryStringToBlobOrBuffer-browser.js
│   │   ├── binaryStringToBlobOrBuffer.js
│   │   ├── blob.js
│   │   ├── index.js
│   │   ├── readAsArrayBuffer.js
│   │   ├── readAsBinaryString-browser.js
│   │   ├── readAsBinaryString.js
│   │   ├── typedBuffer.js
│   │   └── utils.js
│   ├── server/
│   │   ├── index.js
│   │   ├── make-pouch-creator.js
│   │   ├── safe-eval.js
│   │   └── utils.js
│   └── shared/
│       ├── buffer-browser.js
│       ├── buffer.js
│       ├── cloneBinaryObject-browser.js
│       ├── cloneBinaryObject.js
│       ├── errors.js
│       ├── isBinaryObject-browser.js
│       ├── isBinaryObject.js
│       ├── parse-message.js
│       ├── pouchdb-clone.js
│       ├── utils.js
│       └── uuid.js
├── package.json
├── server/
│   └── index.js
└── test/
    ├── bind-polyfill.js
    ├── deps/
    │   └── bigimage.js
    ├── index.html
    ├── node.setup.js
    ├── pouchdb/
    │   ├── integration/
    │   │   ├── deps/
    │   │   │   └── bigimage.js
    │   │   ├── pouchdb-for-coverage.js
    │   │   ├── test.aa.setup.js
    │   │   ├── test.all_docs.js
    │   │   ├── test.attachments.js
    │   │   ├── test.basics.js
    │   │   ├── test.bulk_docs.js
    │   │   ├── test.bulk_get.js
    │   │   ├── test.changes.js
    │   │   ├── test.compaction.js
    │   │   ├── test.conflicts.js
    │   │   ├── test.constructor.js
    │   │   ├── test.design_docs.js
    │   │   ├── test.events.js
    │   │   ├── test.get.js
    │   │   ├── test.http.js
    │   │   ├── test.issue1175.js
    │   │   ├── test.issue221.js
    │   │   ├── test.issue3179.js
    │   │   ├── test.issue3646.js
    │   │   ├── test.local_docs.js
    │   │   ├── test.replication.js
    │   │   ├── test.replication_events.js
    │   │   ├── test.reserved.js
    │   │   ├── test.retry.js
    │   │   ├── test.revs_diff.js
    │   │   ├── test.slash_id.js
    │   │   ├── test.sync.js
    │   │   ├── test.sync_events.js
    │   │   ├── test.taskqueue.js
    │   │   ├── test.uuids.js
    │   │   ├── utils-bundle.js
    │   │   └── utils.js
    │   └── mapreduce/
    │       ├── test.mapreduce.js
    │       ├── test.persisted.js
    │       └── test.views.js
    ├── test.js
    └── webrunner.js

================================================
FILE CONTENTS
================================================

================================================
FILE: .gitignore
================================================
node_modules
.DS_Store
*~
coverage
test/test-bundle.js
npm-debug.log
testdb*


================================================
FILE: .jshintrc
================================================
{
  "curly": true,
  "eqeqeq": true,
  "immed": true,
  "newcap": true,
  "noarg": true,
  "sub": true,
  "undef": true,
  "unused": true,
  "eqnull": true,
  "browser": true,
  "node": true,
  "strict": true,
  "globalstrict": true,
  "globals": { "eio": true},
  "white": true,
  "indent": 2,
  "maxlen": 100,
  "predef": [
    "chrome",
    "eio",
    "process",
    "global",
    "require",
    "console",
    "describe",
    "beforeEach",
    "afterEach",
    "it",
    "emit"
  ]
}

================================================
FILE: .npmignore
================================================
.git*
node_modules
.DS_Store
*~
coverage
npm-debug.log
vendor/


================================================
FILE: .travis.yml
================================================
language: node_js

services:
  - couchdb

node_js:
  - "5"
sudo: false
addons:
  firefox: "41.0.1"
script: npm run $COMMAND
before_script:
  - "export DISPLAY=:99.0"
  - "sh -e /etc/init.d/xvfb start"

  - "export DEBUG=pouchdb:socket"
  - "npm install add-cors-to-couchdb"
  - "./node_modules/.bin/add-cors-to-couchdb"

env:
  matrix:
  - COMMAND=test
  - CLIENT=selenium:firefox:41.0.1 COMMAND=test

branches:
  only:
  - master


================================================
FILE: LICENSE
================================================

                                Apache License
                          Version 2.0, January 2004
                       http://www.apache.org/licenses/

  TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

  1. Definitions.

     "License" shall mean the terms and conditions for use, reproduction,
     and distribution as defined by Sections 1 through 9 of this document.

     "Licensor" shall mean the copyright owner or entity authorized by
     the copyright owner that is granting the License.

     "Legal Entity" shall mean the union of the acting entity and all
     other entities that control, are controlled by, or are under common
     control with that entity. For the purposes of this definition,
     "control" means (i) the power, direct or indirect, to cause the
     direction or management of such entity, whether by contract or
     otherwise, or (ii) ownership of fifty percent (50%) or more of the
     outstanding shares, or (iii) beneficial ownership of such entity.

     "You" (or "Your") shall mean an individual or Legal Entity
     exercising permissions granted by this License.

     "Source" form shall mean the preferred form for making modifications,
     including but not limited to software source code, documentation
     source, and configuration files.

     "Object" form shall mean any form resulting from mechanical
     transformation or translation of a Source form, including but
     not limited to compiled object code, generated documentation,
     and conversions to other media types.

     "Work" shall mean the work of authorship, whether in Source or
     Object form, made available under the License, as indicated by a
     copyright notice that is included in or attached to the work
     (an example is provided in the Appendix below).

     "Derivative Works" shall mean any work, whether in Source or Object
     form, that is based on (or derived from) the Work and for which the
     editorial revisions, annotations, elaborations, or other modifications
     represent, as a whole, an original work of authorship. For the purposes
     of this License, Derivative Works shall not include works that remain
     separable from, or merely link (or bind by name) to the interfaces of,
     the Work and Derivative Works thereof.

     "Contribution" shall mean any work of authorship, including
     the original version of the Work and any modifications or additions
     to that Work or Derivative Works thereof, that is intentionally
     submitted to Licensor for inclusion in the Work by the copyright owner
     or by an individual or Legal Entity authorized to submit on behalf of
     the copyright owner. For the purposes of this definition, "submitted"
     means any form of electronic, verbal, or written communication sent
     to the Licensor or its representatives, including but not limited to
     communication on electronic mailing lists, source code control systems,
     and issue tracking systems that are managed by, or on behalf of, the
     Licensor for the purpose of discussing and improving the Work, but
     excluding communication that is conspicuously marked or otherwise
     designated in writing by the copyright owner as "Not a Contribution."

     "Contributor" shall mean Licensor and any individual or Legal Entity
     on behalf of whom a Contribution has been received by Licensor and
     subsequently incorporated within the Work.

  2. Grant of Copyright License. Subject to the terms and conditions of
     this License, each Contributor hereby grants to You a perpetual,
     worldwide, non-exclusive, no-charge, royalty-free, irrevocable
     copyright license to reproduce, prepare Derivative Works of,
     publicly display, publicly perform, sublicense, and distribute the
     Work and such Derivative Works in Source or Object form.

  3. Grant of Patent License. Subject to the terms and conditions of
     this License, each Contributor hereby grants to You a perpetual,
     worldwide, non-exclusive, no-charge, royalty-free, irrevocable
     (except as stated in this section) patent license to make, have made,
     use, offer to sell, sell, import, and otherwise transfer the Work,
     where such license applies only to those patent claims licensable
     by such Contributor that are necessarily infringed by their
     Contribution(s) alone or by combination of their Contribution(s)
     with the Work to which such Contribution(s) was submitted. If You
     institute patent litigation against any entity (including a
     cross-claim or counterclaim in a lawsuit) alleging that the Work
     or a Contribution incorporated within the Work constitutes direct
     or contributory patent infringement, then any patent licenses
     granted to You under this License for that Work shall terminate
     as of the date such litigation is filed.

  4. Redistribution. You may reproduce and distribute copies of the
     Work or Derivative Works thereof in any medium, with or without
     modifications, and in Source or Object form, provided that You
     meet the following conditions:

     (a) You must give any other recipients of the Work or
         Derivative Works a copy of this License; and

     (b) You must cause any modified files to carry prominent notices
         stating that You changed the files; and

     (c) You must retain, in the Source form of any Derivative Works
         that You distribute, all copyright, patent, trademark, and
         attribution notices from the Source form of the Work,
         excluding those notices that do not pertain to any part of
         the Derivative Works; and

     (d) If the Work includes a "NOTICE" text file as part of its
         distribution, then any Derivative Works that You distribute must
         include a readable copy of the attribution notices contained
         within such NOTICE file, excluding those notices that do not
         pertain to any part of the Derivative Works, in at least one
         of the following places: within a NOTICE text file distributed
         as part of the Derivative Works; within the Source form or
         documentation, if provided along with the Derivative Works; or,
         within a display generated by the Derivative Works, if and
         wherever such third-party notices normally appear. The contents
         of the NOTICE file are for informational purposes only and
         do not modify the License. You may add Your own attribution
         notices within Derivative Works that You distribute, alongside
         or as an addendum to the NOTICE text from the Work, provided
         that such additional attribution notices cannot be construed
         as modifying the License.

     You may add Your own copyright statement to Your modifications and
     may provide additional or different license terms and conditions
     for use, reproduction, or distribution of Your modifications, or
     for any such Derivative Works as a whole, provided Your use,
     reproduction, and distribution of the Work otherwise complies with
     the conditions stated in this License.

  5. Submission of Contributions. Unless You explicitly state otherwise,
     any Contribution intentionally submitted for inclusion in the Work
     by You to the Licensor shall be under the terms and conditions of
     this License, without any additional terms or conditions.
     Notwithstanding the above, nothing herein shall supersede or modify
     the terms of any separate license agreement you may have executed
     with Licensor regarding such Contributions.

  6. Trademarks. This License does not grant permission to use the trade
     names, trademarks, service marks, or product names of the Licensor,
     except as required for reasonable and customary use in describing the
     origin of the Work and reproducing the content of the NOTICE file.

  7. Disclaimer of Warranty. Unless required by applicable law or
     agreed to in writing, Licensor provides the Work (and each
     Contributor provides its Contributions) on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
     implied, including, without limitation, any warranties or conditions
     of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
     PARTICULAR PURPOSE. You are solely responsible for determining the
     appropriateness of using or redistributing the Work and assume any
     risks associated with Your exercise of permissions under this License.

  8. Limitation of Liability. In no event and under no legal theory,
     whether in tort (including negligence), contract, or otherwise,
     unless required by applicable law (such as deliberate and grossly
     negligent acts) or agreed to in writing, shall any Contributor be
     liable to You for damages, including any direct, indirect, special,
     incidental, or consequential damages of any character arising as a
     result of this License or out of the use or inability to use the
     Work (including but not limited to damages for loss of goodwill,
     work stoppage, computer failure or malfunction, or any and all
     other commercial damages or losses), even if such Contributor
     has been advised of the possibility of such damages.

  9. Accepting Warranty or Additional Liability. While redistributing
     the Work or Derivative Works thereof, You may choose to offer,
     and charge a fee for, acceptance of support, warranty, indemnity,
     or other liability obligations and/or rights consistent with this
     License. However, in accepting such obligations, You may act only
     on Your own behalf and on Your sole responsibility, not on behalf
     of any other Contributor, and only if You agree to indemnify,
     defend, and hold each Contributor harmless for any liability
     incurred by, or claims asserted against, such Contributor by reason
     of your accepting any such warranty or additional liability.

  END OF TERMS AND CONDITIONS

  APPENDIX: How to apply the Apache License to your work.

     To apply the Apache License to your work, attach the following
     boilerplate notice, with the fields enclosed by brackets "[]"
     replaced with your own identifying information. (Don't include
     the brackets!)  The text should be enclosed in the appropriate
     comment syntax for the file format. We also recommend that a
     file or class name and description of purpose be included on the
     same "printed page" as the copyright notice for easier
     identification within third-party archives.

  Copyright [yyyy] [name of copyright owner]

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.


================================================
FILE: README.md
================================================
socket-pouch [![Build Status](https://travis-ci.org/nolanlawson/socket-pouch.svg)](https://travis-ci.org/nolanlawson/socket-pouch)
=====

```js
// This pouch is powered by web sockets!
var db = new PouchDB('mydb', {adapter: 'socket', url: 'ws://localhost:80'});
```

Adapter plugin that proxies all PouchDB API calls to another PouchDB running on the server in Node.js. The communication mechanism is [Engine.io](https://github.com/Automattic/engine.io), the famous core of [Socket.io](http://socket.io/).

This means that instead of syncing over HTTP, socket-pouch syncs over WebSockets. Thanks to Engine.io, it falls back to XHR polling in browsers that don't support WebSockets.

The socket-pouch library has two parts:

* **A Node.js server**, which can create local PouchDBs or proxy to a remote CouchDB.
* **A JavaScript client**, which can run in Node.js or the browser.

This adapter passes [the full PouchDB test suite](https://travis-ci.org/nolanlawson/socket-pouch). It requires PouchDB 5.0.0+.

Usage
---

    $ npm install socket-pouch

#### Server

```js
var socketPouchServer = require('socket-pouch/server');

socketPouchServer.listen(80);
```

#### Client

##### In the browser
    
When you `npm install socket-pouch`, the client JS file is available at `node_modules/socket-pouch/dist/socket-pouch.client.js`. Or you can just download it from Github above.

Then include it in your HTML, after PouchDB:

```html
<script src="pouchdb.js"></script>
<script src="socket-pouch.client.js"></script>
```

Then you can create a socket-powered PouchDB using:

```js
var db = new PouchDB('mydb', {
  adapter: 'socket',
  url: 'ws://localhost:80'
});
```

##### In Node.js/Browserify

The same rules apply, but you have to notify PouchDB of the new adapter:

```js
var PouchDB = require('pouchdb');
PouchDB.adapter('socket', require('socket-pouch/client'));
```

API
----

### Server

```js
var socketPouchServer = require('socket-pouch/server');

socketPouchServer.listen(80, {}, function () {
  // server started
});
```

#### socketPouchServer.listen(port [, options] [, callback])

##### Arguments

* **port**: the port to listen on. You should probably use 80 or 443 if you plan on running this in production; most browsers are finicky about other ports. 8080 may work in Chrome during debugging.
* **options**: (optional) options object
  * **remoteUrl**: tells socket-pouch to act as a proxy for a remote CouchDB at the given URL (rather than creating local PouchDB databases)
  * **pouchCreator**: alternatively, you can supply a custom function that takes a string and returns any PouchDB object however you like. (See examples below.) 
  * **socketOptions**: (optional) options passed verbatim to Engine.io. See [their documentation](https://github.com/Automattic/engine.io/#methods) for details.
* **callback**: (optional) called when the server has started

Create a server which creates local PouchDBs, named by the user and placed in the current directory:

```js
socketPouchServer.listen(80, {}, function () {
  console.log('server started!');
});
```

Create a server which acts as a proxy to a remote CouchDB (or CouchDB-compliant database):

```js
socketPouchServer.listen(80, {
  remoteUrl: 'http://localhost:5984'
});
```

So e.g. when the user requests a database called 'foo', it will use a remote database at `'http://localhost:5984/foo'`. Note that authentication is not handled, so you may want the `pouchCreator` option instead.

Create a MemDOWN-backed PouchDB server:

```js
socketPouchServer.listen(80, {
  pouchCreator: function (dbName) {
    return new PouchDB(dbName, {
      db: require('memdown')
    });
  }
});
```

Note that this `dbName` is supplied by the client ver batim, meaning **it could be dangerous**. In the example above, everything is fine because MemDOWN databases can have any string as a name.

Alternatively, your `pouchCreator` can return a `Promise` if you want to do something asynchronously, such as authenticating the user. In that case you must wrap the object in `{pouch: yourPouchDB}`:

```js
socketPouchServer.listen(80, {
  pouchCreator: function (dbName) {
    return doSomethingAsynchronously().then(function () {
      return {
        pouch: new PouchDB('dbname')
      };
    });
  }
});
```

### Client

```js
var db = new PouchDB({
  adapter: 'socket',
  name: 'mydb',
  url: 'ws://localhost:80',
  socketOptions: {}
});
```

The `name` and `url` are required and must point to a valid `socketPouchServer`. The `socketOptions`, if provided, are passed ver batim to Engine.io, so refer to [their documentation](https://github.com/Automattic/engine.io-client/#nodejs-with-certificates) for details.

### Replication

The `db` object acts like a PouchDB that communicates remotely with the `socketPouchServer` In other words, it's analogous to a PouchDB created like `new PouchDB('http://localhost:5984/mydb')`.

So you can replicate using the normal methods:

```js
var localDB = new PouchDB('local');
var remoteDB = new PouchDB({adapter: 'socket', name: 'remote', url: 'ws://localhost:80'});

// replicate from local to remote
localDB.replicate.to(remoteDB);

// replicate from remote to local
localDB.replicate.from(remoteDB);

// replicate bidirectionally
localDB.sync(remoteDB);
```

For details, see the official [`replicate()`](http://pouchdb.com/api.html#replication) or [`sync()`](http://pouchdb.com/api.html#sync) docs.

### Remote API

```js
var remoteDB = new PouchDB({adapter: 'socket', name: 'remote', url: 'ws://localhost:80'});
```

You can also talk to this `remoteDB` as if it were a normal PouchDB. All the standard methods like `info()`, `get()`, `put()`, and `putAttachment()` will work. The [Travis tests](https://travis-ci.org/nolanlawson/socket-pouch) run the full PouchDB test suite.

### Debugging

SocketPouch uses [debug](https://github.com/visionmedia/debug) for logging. So in Node.js, you can enable debugging by setting a flag:

```
DEBUG=pouchdb:socket:*
```

In the browser, you can enable debugging by using PouchDB's logger:

```js
PouchDB.debug.enable('pouchdb:socket:*');
```

Q & A
---

#### How does it communicate?

SocketPouch communicates using the normal Engine.io APIs like `send()` and `on('message')`.

Normally it sends JSON text data, but in the case of attachments, binary data is sent. This means that SocketPouch is actually more efficient than regular PouchDB replication, which (as of this writing) uses base64-string encoding to send attachments between the client and server.

#### Does it work in a web worker or service worker?

Unfortuantely, not at the moment.

#### How is it implemented?

This is a custom PouchDB adapter. Other examples of PouchDB adapters include the built-in IndexedDB, WebSQL, LevelDB, and HTTP (Couch) adapters, as well as a partial adapter written for [pouchdb-replication-stream](https://github.com/nolanlawson/pouchdb-replication-stream) and [worker-pouch](https://github.com/nolanlawson/worker-pouch), which is a fork of this repo.

Changelog
---

- 2.0.0
  - Support for PouchDB 6.0.0, drop support for PouchDB <=5
- 1.0.0
  - Initial release

Building
----

    npm install
    npm run build

Testing
----

### In Node

This will run the tests in Node using LevelDB:

    npm test
    
You can also check for 100% code coverage using:

    npm run coverage

Run certain tests:
```
GREP=foo npm test
```

### In the browser

Run `npm run dev` and then point your favorite browser to [http://127.0.0.1:8000/test/index.html](http://127.0.0.1:8000/test/index.html).

The query param `?grep=mysearch` will search for tests matching `mysearch`.

### Automated browser tests

You can run e.g.

    CLIENT=selenium:firefox npm test
    CLIENT=selenium:phantomjs npm test

This will run the tests automatically and the process will exit with a 0 or a 1 when it's done. Firefox uses IndexedDB, and PhantomJS uses WebSQL.




================================================
FILE: bin/dev-server.js
================================================
#!/usr/bin/env node

'use strict';

var COUCH_HOST = process.env.COUCH_HOST || 'http://127.0.0.1:5984';
var HTTP_PORT = 8000;
var CORS_PORT = 2020;
var SOCKET_PORT = 8080;

var cors_proxy = require('corsproxy');
var Promise = require('bluebird');
var http_proxy = require('pouchdb-http-proxy');
var http_server = require("http-server");
var fs = require('fs');
var indexfile = "./test/test.js";
var dotfile = "./test/.test-bundle.js";
var outfile = "./test/test-bundle.js";
var watchify = require("watchify");
var browserify = require('browserify');
var socketPouch = require('../lib/server');
var w = watchify(browserify(indexfile, {
  cache: {},
  packageCache: {},
  fullPaths: true,
  debug: true
}));

w.on('update', bundle);
bundle();

var filesWritten = false;
var serverStarted = false;
var socketServerStarted = false;
var readyCallback;

function bundle() {
  var wb = w.bundle();
  wb.on('error', function (err) {
    console.error(String(err));
  });
  wb.on("end", end);
  wb.pipe(fs.createWriteStream(dotfile));

  function end() {
    fs.rename(dotfile, outfile, function (err) {
      if (err) { return console.error(err); }
      console.log('Updated:', outfile);
      filesWritten = true;
      checkReady();
    });
  }
}

function startSocketServer() {
  socketPouch.listen(SOCKET_PORT, {}, function () {
    console.log('Socket server started');
    socketServerStarted = true;
    checkReady();
  });
}

function startServers(callback) {
  readyCallback = callback;

  startSocketServer();

  return new Promise(function (resolve, reject) {
    http_server.createServer().listen(HTTP_PORT, function (err) {
      if (err) {
        return reject(err);
      }
      cors_proxy.options = {target: COUCH_HOST};
      http_proxy.createServer(cors_proxy).listen(CORS_PORT, function (err) {
        if (err) {
          return reject(err);
        }
        resolve();
      });
    });
  }).then(function () {
    console.log('Tests: http://127.0.0.1:' + HTTP_PORT + '/test/index.html');
    serverStarted = true;
    checkReady();
  }).catch(function (err) {
    if (err) {
      console.log(err);
      process.exit(1);
    }
  });
}

function checkReady() {
  if (filesWritten && serverStarted && socketServerStarted && readyCallback) {
    readyCallback();
  }
}

if (require.main === module) {
  startServers();
} else {
  module.exports.start = startServers;
}


================================================
FILE: bin/es3ify.js
================================================
#!/usr/bin/env node
'use strict';
var es3ify = require('es3ify');
return process.stdin.pipe(es3ify()).pipe(process.stdout);


================================================
FILE: bin/run-test.sh
================================================
#!/bin/bash

: ${CLIENT:="node"}

if [ "$CLIENT" == "node" ]; then
    npm run test-node
else
    npm run test-browser
fi


================================================
FILE: bin/test-browser.js
================================================
#!/usr/bin/env node
'use strict';

var wd = require('wd');
var sauceConnectLauncher = require('sauce-connect-launcher');
var selenium = require('selenium-standalone');
var querystring = require("querystring");

var devserver = require('./dev-server.js');

var testTimeout = 30 * 60 * 1000;

var username = process.env.SAUCE_USERNAME;
var accessKey = process.env.SAUCE_ACCESS_KEY;

// process.env.CLIENT is a colon seperated list of
// (saucelabs|selenium):browserName:browserVerion:platform
var tmp = (process.env.CLIENT || 'selenium:firefox').split(':');
var client = {
  runner: tmp[0] || 'selenium',
  browser: tmp[1] || 'firefox',
  version: tmp[2] || null, // Latest
  platform: tmp[3] || null
};

var testUrl = 'http://127.0.0.1:8000/test/index.html';
var qs = {};

var sauceClient;
var sauceConnectProcess;
var tunnelId = process.env.TRAVIS_JOB_NUMBER || 'tunnel-' + Date.now();

if (client.runner === 'saucelabs') {
  qs.saucelabs = true;
}
if (process.env.GREP) {
  qs.grep = process.env.GREP;
}
testUrl += '?';
testUrl += querystring.stringify(qs);

if (process.env.TRAVIS &&
    client.browser !== 'firefox' &&
    client.browser !== 'phantomjs' &&
    process.env.TRAVIS_SECURE_ENV_VARS === 'false') {
  console.error('Not running test, cannot connect to saucelabs');
  process.exit(1);
  return;
}

function testError(e) {
  console.error(e);
  console.error('Doh, tests failed');
  sauceClient.quit();
  process.exit(3);
}

function postResult(result) {
  process.exit(!process.env.PERF && result.failed ? 1 : 0);
}

function testComplete(result) {
  console.log(result);

  sauceClient.quit().then(function () {
    if (sauceConnectProcess) {
      sauceConnectProcess.close(function () {
        postResult(result);
      });
    } else {
      postResult(result);
    }
  });
}

function startSelenium(callback) {
  // Start selenium
  var opts = {version: '2.45.0'};
  selenium.install(opts, function(err) {
    if (err) {
      console.error('Failed to install selenium');
      process.exit(1);
    }
    selenium.start(opts, function(err, server) {
      sauceClient = wd.promiseChainRemote();
      callback();
    });
  });
}

function startSauceConnect(callback) {

  var options = {
    username: username,
    accessKey: accessKey,
    tunnelIdentifier: tunnelId
  };

  sauceConnectLauncher(options, function (err, process) {
    if (err) {
      console.error('Failed to connect to saucelabs');
      console.error(err);
      return process.exit(1);
    }
    sauceConnectProcess = process;
    sauceClient = wd.promiseChainRemote("localhost", 4445, username, accessKey);
    callback();
  });
}

function startTest() {

  console.log('Starting', client);

  var opts = {
    browserName: client.browser,
    version: client.version,
    platform: client.platform,
    tunnelTimeout: testTimeout,
    name: client.browser + ' - ' + tunnelId,
    'max-duration': 60 * 30,
    'command-timeout': 599,
    'idle-timeout': 599,
    'tunnel-identifier': tunnelId
  };

  sauceClient.init(opts).get(testUrl, function () {

    /* jshint evil: true */
    var interval = setInterval(function () {
      sauceClient.eval('window.results', function (err, results) {
        if (err) {
          clearInterval(interval);
          testError(err);
        } else if (results.completed || results.failures.length) {
          clearInterval(interval);
          testComplete(results);
        } else {
          console.log('=> ', results);
        }
      });
    }, 10 * 1000);
  });
}

devserver.start(function () {
  if (client.runner === 'saucelabs') {
    startSauceConnect(startTest);
  } else {
    startSelenium(startTest);
  }
});


================================================
FILE: bin/test-node.sh
================================================
#!/usr/bin/env bash

: ${TIMEOUT:=50000}
: ${REPORTER:="spec"}

node ./bin/dev-server.js &
export DEV_SERVER_PID=$!

sleep 10

# TODO: this fixes a weird test in test.views.js
./node_modules/.bin/rimraf tmp
./node_modules/.bin/mkdirp tmp

# skip migration and defaults tests
if [[ $INVERT == '1' ]]; then
  INVERT_ARG='--invert'
else
  INVERT_ARG=''
fi

mocha \
  --reporter=$REPORTER \
  --timeout $TIMEOUT --bail \
  --require=./test/node.setup.js \
  --grep=$GREP \
  $INVERT_ARG \
  test/pouchdb/{integration,mapreduce}/test.*.js

EXIT_STATUS=$?
if [[ ! -z $DEV_SERVER_PID ]]; then
  kill $DEV_SERVER_PID
fi
exit $EXIT_STATUS


================================================
FILE: client/index.js
================================================
'use strict';

module.exports = require('../lib/client');

================================================
FILE: dist/socket-pouch.client.js
================================================
(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.socketPouch = 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(_dereq_,module,exports){
'use strict';

module.exports = _dereq_('../lib/client');
},{"../lib/client":8}],2:[function(_dereq_,module,exports){
'use strict';

//Can't find original post, but this is close
//http://stackoverflow.com/questions/6965107/ (continues on next line)
//converting-between-strings-and-arraybuffers
module.exports = function (buffer) {
  var binary = '';
  var bytes = new Uint8Array(buffer);
  var length = bytes.byteLength;
  for (var i = 0; i < length; i++) {
    binary += String.fromCharCode(bytes[i]);
  }
  return binary;
};
},{}],3:[function(_dereq_,module,exports){
'use strict';

var buffer = _dereq_('../shared/buffer');

/* istanbul ignore if */
if (typeof atob === 'function') {
  exports.atob = function (str) {
    /* global atob */
    return atob(str);
  };
} else {
  exports.atob = function (str) {
    var base64 = new buffer(str, 'base64');
    // Node.js will just skip the characters it can't encode instead of
    // throwing and exception
    if (base64.toString('base64') !== str) {
      throw ("Cannot base64 encode full string");
    }
    return base64.toString('binary');
  };
}

/* istanbul ignore if */
if (typeof btoa === 'function') {
  exports.btoa = function (str) {
    /* global btoa */
    return btoa(str);
  };
} else {
  exports.btoa = function (str) {
    return new buffer(str, 'binary').toString('base64');
  };
}
},{"../shared/buffer":11}],4:[function(_dereq_,module,exports){
'use strict';

var binaryStringToBlobOrBuffer = _dereq_('./binaryStringToBlobOrBuffer');

module.exports = function (b64, type) {
  return binaryStringToBlobOrBuffer(atob(b64), type);
};
},{"./binaryStringToBlobOrBuffer":6}],5:[function(_dereq_,module,exports){
'use strict';

// From http://stackoverflow.com/questions/14967647/ (continues on next line)
// encode-decode-image-with-base64-breaks-image (2013-04-21)
module.exports = function (bin) {
  var length = bin.length;
  var buf = new ArrayBuffer(length);
  var arr = new Uint8Array(buf);
  for (var i = 0; i < length; i++) {
    arr[i] = bin.charCodeAt(i);
  }
  return buf;
};
},{}],6:[function(_dereq_,module,exports){
'use strict';

var createBlob = _dereq_('./blob');
var binaryStringToArrayBuffer = _dereq_('./binaryStringToArrayBuffer');

module.exports = function (binString, type) {
  return createBlob([binaryStringToArrayBuffer(binString)], {type: type});
};
},{"./binaryStringToArrayBuffer":5,"./blob":7}],7:[function(_dereq_,module,exports){
"use strict";

// Abstracts constructing a Blob object, so it also works in older
// browsers that don't support the native Blob constructor (e.g.
// old QtWebKit versions, Android < 4.4).
function createBlob(parts, properties) {
  /* global BlobBuilder,MSBlobBuilder,MozBlobBuilder,WebKitBlobBuilder */
  parts = parts || [];
  properties = properties || {};
  try {
    return new Blob(parts, properties);
  } catch (e) {
    if (e.name !== "TypeError") {
      throw e;
    }
    var Builder = typeof BlobBuilder !== 'undefined' ? BlobBuilder :
                  typeof MSBlobBuilder !== 'undefined' ? MSBlobBuilder :
                  typeof MozBlobBuilder !== 'undefined' ? MozBlobBuilder :
                  WebKitBlobBuilder;
    var builder = new Builder();
    for (var i = 0; i < parts.length; i += 1) {
      builder.append(parts[i]);
    }
    return builder.getBlob(properties.type);
  }
}

module.exports = createBlob;


},{}],8:[function(_dereq_,module,exports){
(function (process){
'use strict';

var utils = _dereq_('../shared/utils');
var clientUtils = _dereq_('./utils');
var uuid = _dereq_('./../shared/uuid');
var errors = _dereq_('../shared/errors');
var log = _dereq_('debug')('pouchdb:socket:client');
var Socket = _dereq_('engine.io-client');
var blobUtil = _dereq_('blob-util');
var isBrowser = typeof process === 'undefined' || process.browser;
var buffer = _dereq_('../shared/buffer');
var preprocessAttachments = clientUtils.preprocessAttachments;
var stringifyArgs = clientUtils.stringifyArgs;
var padInt = clientUtils.padInt;
var readAttachmentsAsBlobOrBuffer = clientUtils.readAttachmentsAsBlobOrBuffer;
var adapterFun = clientUtils.adapterFun;
var readAsBinaryString = _dereq_('./readAsBinaryString');
var isBinaryObject = _dereq_('../shared/isBinaryObject');
var Promise = _dereq_('pouchdb-promise');
var base64 = _dereq_('./base64');

var instances = {};

function close(api, callback) {
  // api.name was added in pouchdb 6.0.0
  log('closing socket', api._socketId, api.name || api._name);

  function closeSocket() {
    api._socket.closed = true;
    api._socket.once('close', function (msg) {
      log('socket closed', api._socketId, msg);
      api._socket.removeAllListeners();
      callback();
    });
    api._socket.close();
  }

  if (api._socket.closed) {
    return callback();
  }
  closeSocket();
}

// Implements the PouchDB API for dealing with CouchDB instances over WS
function SocketPouch(opts, callback) {
  var api = this;

  if (typeof opts === 'string') {
    var slashIdx = utils.lastIndexOf(opts, '/');
    opts = {
      url: opts.substring(0, slashIdx),
      name: opts.substring(slashIdx + 1)
    };
  } else {
    opts = utils.clone(opts);
  }

  log('constructor called', opts);

  if (!opts.url || !opts.name) {
    var optsErrMessage = 'Error: you must provide a web socket ' +
      'url and database name.';
    console.error(optsErrMessage);
    return callback(new Error(optsErrMessage));
  }

  // api.name was added in pouchdb 6.0.0
  api._socketName = api.name || opts.originalName;

  var cacheKey = '$' + api._socketName;

  function useExistingSocket() {
    // Re-use the cached one instead of creating multiple sockets.
    // This is important, because if a user creates many PouchDBs
    // without closing/destroying each one, then we could end up
    // with too many open sockets, which causes problems like
    // https://github.com/Automattic/engine.io/issues/320
    var instance = instances[cacheKey];
    api._socket = instance._socket;
    api._callbacks = instance._callbacks;
    api._changesListeners = instance._changesListeners;
    api._blobs = instance._blobs;
    api._binaryMessages = instance._binaryMessages;
    api._name = instance._name;

    if (instance._socketId) {
      api._socketId = instance._socketId;
      process.nextTick(function () {
        callback(null, api);
      });
    } else {
      api._socket.once('open', function () {
        api._socketId = api._socket.id;
        process.nextTick(function () {
          callback(null, api);
        });
      });
    }
  }

  function createNewSocket() {
    // to force XHR during debugging
    // opts.socketOptions = {transports: ['polling']};
    var socket = api._socket = new Socket(opts.url, opts.socketOptions || {});
    socket.binaryType = 'blob';
    api._callbacks = {};
    api._changesListeners = {};
    api._blobs = {};
    api._binaryMessages = {};
    api._name = api._socketName;
    instances[cacheKey] = api;

    socket.once('open', function () {
      api._socketId = socket.id;
      log('socket opened', api._socketId, api._name);
      var serverOpts = {
        name: api._name,
        auto_compaction: !!opts.auto_compaction
      };
      if ('revs_limit' in opts) {
        serverOpts.revs_limit = opts.revs_limit;
      }
      sendMessage('createDatabase', [serverOpts], function (err) {
        if (err) {
          return callback(err);
        }
        callback(null, api);
      });
    });

    api._socket.once('error', function (err) {
      callback(err);
    });

    function handleUncaughtError(content) {
      try {
        api.emit('error', content);
      } catch (err) {
        // TODO: it's weird that adapters should have to handle this themselves
        console.error(
          'The user\'s map/reduce function threw an uncaught error.\n' +
          'You can debug this error by doing:\n' +
          'myDatabase.on(\'error\', function (err) { debugger; });\n' +
          'Please double-check your map/reduce function.');
        console.error(content);
      }
    }

    function receiveMessage(res) {
      var split = utils.parseMessage(res, 3);
      var messageId = split[0];
      var messageType = split[1];
      var content = JSON.parse(split[2]);

      if (messageType === '4') { // unhandled error
        handleUncaughtError(content);
        return;
      }

      var cb = api._callbacks[messageId];

      if (!cb) {
        log('duplicate message (ignoring)', messageId, messageType, content);
        return;
      }

      log('receive message', api._socketId, messageId, messageType, content);

      if (messageType === '0') { // error
        delete api._callbacks[messageId];
        cb(content);
      } else if (messageType === '1') { // success
        delete api._callbacks[messageId];
        cb(null, content);
      } else if (messageType === '2') { // update, i.e. changes
        if (api._changesListeners[messageId].asBinary) {
          readAttachmentsAsBlobOrBuffer(content);
        }
        api._changesListeners[messageId].listener(content);
      } else { // binary success
        delete api._callbacks[messageId];
        receiveBinaryMessage(content, cb);
      }
    }

    function receiveBinaryMessage(content, cb) {
      log('receiveBinaryMessage', content.uuid);
      api._binaryMessages[content.uuid] = {
        contentType: content.type,
        cb: cb
      };
      checkBinaryReady(uuid);
    }

    function receiveBlob(blob) {
      if (isBrowser) {
        blobUtil.blobToBinaryString(blob.slice(0, 36)).then(function (uuid) {
          api._blobs[uuid] = blob.slice(36);
          log('receiveBlob', uuid);
          checkBinaryReady(uuid);
        })["catch"](console.log.bind(console));
      } else {
        var uuid = blob.slice(0, 36).toString('utf8');
        log('receiveBlob', uuid);
        api._blobs[uuid] = blob.slice(36);
        checkBinaryReady(uuid);
      }
    }

    // binary messages come in two parts; wait until we've received both
    function checkBinaryReady(uuid) {
      if (!(uuid in api._blobs && uuid in api._binaryMessages)) {
        return;
      }
      log('receive full binary message', uuid);
      var blob = api._blobs[uuid];
      var msg = api._binaryMessages[uuid];

      delete api._blobs[uuid];
      delete api._binaryMessages[uuid];

      var blobToDeliver;
      if (isBrowser) {
        blobToDeliver = blobUtil.createBlob([blob], {type: msg.contentType});
      } else {
        blobToDeliver = blob;
        blob.type = msg.contentType; // non-standard, but we do it for the tests
      }

      msg.cb(null, blobToDeliver);
    }

    api._socket.on('message', function (res) {
      if (typeof res !== 'string') {
        return receiveBlob(res);
      }
      receiveMessage(res);
    });
  }

  if (instances[cacheKey]) {
    useExistingSocket();
  } else { // new DB
    createNewSocket();
  }

  function sendMessage(type, args, callback) {
    if (api._destroyed) {
      return callback(new Error('this db was destroyed'));
    } else if (api._closed) {
      return callback(new Error('this db was closed'));
    }
    var messageId = uuid();
    log('send message', api._socketId, messageId, type, args);
    api._callbacks[messageId] = callback;
    var stringArgs = stringifyArgs(args);
    api._socket.send(type + ':' + messageId + ':' + stringArgs, function () {
      log('message sent', api._socketId, messageId);
    });
  }

  function sendBinaryMessage(type, args, blobIndex, blob, callback) {
    var messageId = uuid();
    api._callbacks[messageId] = callback;
    var header = {
      args: args,
      blobIndex: blobIndex,
      messageId: messageId,
      messageType: type
    };

    log('send binary message', api._socketId, messageId, header);
    var headerString = JSON.stringify(header);
    var headerLen = padInt(headerString.length, 16);
    var blobToSend;
    if (isBrowser) {
      blobToSend = blobUtil.createBlob([
        headerLen,
        headerString,
        blob
      ]);
    } else { // node.js
      blobToSend = buffer.concat([
        new buffer(headerLen, 'utf8'),
        new buffer(headerString, 'utf8'),
        new buffer(blob, 'binary')
      ]);
    }
    api._socket.send(blobToSend, function () {
      log('binary message sent', api._socketId, messageId);
    });
  }

  api.type = function () {
    return 'socket';
  };

  api._id = adapterFun('id', function (callback) {
    sendMessage('id', [], callback);
  });

  api.compact = adapterFun('compact', function (opts, callback) {
    if (typeof opts === 'function') {
      callback = opts;
      opts = {};
    }
    sendMessage('compact', [opts], callback);
  });

  api._info = function (callback) {
    sendMessage('info', [], callback);
  };

  api.get = adapterFun('get', function (id, opts, callback) {
    if (typeof opts === 'function') {
      callback = opts;
      opts = {};
    }
    sendMessage('get', [id, opts], function (err, res) {
      if (err) {
        return callback(err);
      }
      if (opts.attachments && opts.binary) {
        if (Array.isArray(res)) {
          res.forEach(readAttachmentsAsBlobOrBuffer);
        } else {
          readAttachmentsAsBlobOrBuffer({doc: res});
        }
      }
      callback(null, res);
    });
  });

  // hacky code necessary due to implicit breaking change in
  // https://github.com/pouchdb/pouchdb/commits/0ddeae6b
  api._get = function (id, opts, callback) {
    api.get(id, opts, function (err, doc) {
      if (err) {
        return callback(err);
      }
      callback(null, {doc: doc});
    });
  };

  api.remove =
    adapterFun('remove', function (docOrId, optsOrRev, opts, callback) {
      var doc;
      if (typeof optsOrRev === 'string') {
        // id, rev, opts, callback style
        doc = {
          _id: docOrId,
          _rev: optsOrRev
        };
        if (typeof opts === 'function') {
          callback = opts;
          opts = {};
        }
      } else {
        // doc, opts, callback style
        doc = docOrId;
        if (typeof optsOrRev === 'function') {
          callback = optsOrRev;
          opts = {};
        } else {
          callback = opts;
          opts = optsOrRev;
        }
      }
      var rev = (doc._rev || opts.rev);

      sendMessage('remove', [doc._id, rev], callback);
  });

  api.getAttachment =
    adapterFun('getAttachment', function (docId, attachmentId, opts,
                                                callback) {
      if (typeof opts === 'function') {
        callback = opts;
        opts = {};
      }
      sendMessage('getAttachment', [docId, attachmentId, opts], callback);
  });

  api.removeAttachment =
    adapterFun('removeAttachment', function (docId, attachmentId, rev,
                                                   callback) {

      sendMessage('removeAttachment', [docId, attachmentId, rev], callback);
    });

  // Add the attachment given by blob and its contentType property
  // to the document with the given id, the revision given by rev, and
  // add it to the database given by host.
  api.putAttachment =
    adapterFun('putAttachment', function (docId, attachmentId, rev, blob,
                                                type, callback) {
      if (typeof type === 'function') {
        callback = type;
        type = blob;
        blob = rev;
        rev = null;
      }
      if (typeof type === 'undefined') {
        type = blob;
        blob = rev;
        rev = null;
      }

      if (typeof blob === 'string') {
        var binary;
        try {
          binary = utils.atob(blob);
        } catch (err) {
          // it's not base64-encoded, so throw error
          return callback(errors.error(errors.BAD_ARG,
            'Attachments need to be base64 encoded'));
        }
        if (isBrowser) {
          blob = utils.createBlob([utils.binaryStringToArrayBuffer(binary)], {type: type});
        } else {
          blob = binary ? new buffer(binary, 'binary') : '';
        }
      }

      var args = [docId, attachmentId, rev, null, type];
      sendBinaryMessage('putAttachment', args, 3, blob, callback);
    });

  api.put = adapterFun('put', utils.getArguments(function (args) {
    var temp, temptype, opts;
    var doc = args.shift();
    var id = '_id' in doc;
    var callback = args.pop();
    if (typeof doc !== 'object' || Array.isArray(doc)) {
      return callback(errors.error(errors.NOT_AN_OBJECT));
    }

    doc = utils.clone(doc);

    preprocessAttachments(doc).then(function () {
      while (true) {
        temp = args.shift();
        temptype = typeof temp;
        if (temptype === "string" && !id) {
          doc._id = temp;
          id = true;
        } else if (temptype === "string" && id && !('_rev' in doc)) {
          doc._rev = temp;
        } else if (temptype === "object") {
          opts = utils.clone(temp);
        }
        if (!args.length) {
          break;
        }
      }
      opts = opts || {};

      sendMessage('put', [doc, opts], callback);
    })["catch"](callback);

  }));

  api.post = adapterFun('post', function (doc, opts, callback) {
    if (typeof opts === 'function') {
      callback = opts;
      opts = {};
    }
    opts = utils.clone(opts);

    sendMessage('post', [doc, opts], callback);
  });

  api._bulkDocs = function (req, opts, callback) {
    var docs = req.docs || req;

    Promise.all(docs.map(function (doc) {
      var atts = doc._attachments;
      if (!atts) {
        return;
      }
      return Promise.all(Object.keys(atts).map(function (key) {
        var att = doc._attachments[key];
        if (!isBinaryObject(att.data)) {
          return;
        }
        return new Promise(function (resolve) {
          readAsBinaryString(att.data, resolve);
        }).then(function (binString) {
          att.data = base64.btoa(binString);
        });
      }));
    })).then(function () {
      sendMessage('bulkDocs', [req, opts], callback);
    })["catch"](callback);
  };

  api._allDocs = function (opts, callback) {
    if (typeof opts === 'function') {
      callback = opts;
      opts = {};
    }
    sendMessage('allDocs', [opts], function (err, res) {
      if (err) {
        return callback(err);
      }
      if (opts.attachments && opts.binary) {
        res.rows.forEach(readAttachmentsAsBlobOrBuffer);
      }
      callback(null, res);
    });
  };

  api._changes = function (opts) {
    opts = utils.clone(opts);

    if (opts.continuous) {
      var messageId = uuid();
      api._changesListeners[messageId] = {
        listener: opts.onChange,
        asBinary: opts.attachments && opts.binary
      };
      api._callbacks[messageId] = opts.complete;
      api._socket.send('liveChanges' + ':' + messageId + ':' + JSON.stringify([opts]));
      return {
        cancel: function () {
          api._socket.send('cancelChanges' + ':' + messageId + ':' + JSON.stringify([]));
        }
      };
    }

    sendMessage('changes', [opts], function (err, res) {
      if (err) {
        opts.complete(err);
        return callback(err);
      }
      res.results.forEach(function (change) {
        if (opts.attachments && opts.binary) {
          readAttachmentsAsBlobOrBuffer(change);
        }
        opts.onChange(change);
      });
      if (opts.returnDocs === false || opts.return_docs === false) {
        res.results = [];
      }
      opts.complete(null, res);
    });
  };

  // Given a set of document/revision IDs (given by req), tets the subset of
  // those that do NOT correspond to revisions stored in the database.
  // See http://wiki.apache.org/couchdb/HttpPostRevsDiff
  api.revsDiff = adapterFun('revsDiff', function (req, opts, callback) {
    // If no options were given, set the callback to be the second parameter
    if (typeof opts === 'function') {
      callback = opts;
      opts = {};
    }

    sendMessage('revsDiff', [req, opts], callback);
  });

  api._query = adapterFun('query', function (fun, opts, callback) {
    if (typeof opts === 'function') {
      callback = opts;
      opts = {};
    }
    var funEncoded = fun;
    if (typeof fun === 'function') {
      funEncoded = {map: fun};
    }
    sendMessage('query', [funEncoded, opts], function (err, res) {
      if (err) {
        return callback(err);
      }
      if (opts.attachments && opts.binary) {
        res.rows.forEach(readAttachmentsAsBlobOrBuffer);
      }
      callback(null, res);
    });
  });

  api._viewCleanup = adapterFun('viewCleanup', function (callback) {
    sendMessage('viewCleanup', [], callback);
  });

  api._close = function (callback) {
    api._closed = true;
    var cacheKey = '$' + api._socketName;
    if (!instances[cacheKey]) { // already closed/destroyed
      return callback();
    }
    delete instances[cacheKey];
    close(api, callback);
  };

  api.destroy = adapterFun('destroy', function (opts, callback) {
    if (typeof opts === 'function') {
      callback = opts;
      opts = {};
    }
    var cacheKey = '$' + api._socketName;

    if (!instances[cacheKey]) { // already closed/destroyed
      return callback(null, {ok: true});
    }
    delete instances[cacheKey];
    sendMessage('destroy', [], function (err, res) {
      if (err) {
        api.emit('error', err);
        return callback(err);
      }
      api._destroyed = true;
      close(api, function (err) {
        if (err) {
          api.emit('error', err);
          return callback(err);
        }
        api.emit('destroyed');
        callback(null, res);
      });
    });
  });
}

// SocketPouch is a valid adapter.
SocketPouch.valid = function () {
  return true;
};

module.exports = SocketPouch;

/* istanbul ignore next */
if (typeof window !== 'undefined' && window.PouchDB) {
  window.PouchDB.adapter('socket', module.exports);
}

}).call(this,_dereq_('_process'))
},{"../shared/buffer":11,"../shared/errors":13,"../shared/isBinaryObject":14,"../shared/utils":17,"./../shared/uuid":18,"./base64":3,"./readAsBinaryString":9,"./utils":10,"_process":71,"blob-util":22,"debug":27,"engine.io-client":29,"pouchdb-promise":69}],9:[function(_dereq_,module,exports){
'use strict';

var arrayBufferToBinaryString = _dereq_('./arrayBufferToBinaryString');

// shim for browsers that don't support it
module.exports = function (blob, callback) {
  var reader = new FileReader();
  var hasBinaryString = typeof reader.readAsBinaryString === 'function';
  reader.onloadend = function (e) {
    var result = e.target.result || '';
    if (hasBinaryString) {
      return callback(result);
    }
    callback(arrayBufferToBinaryString(result));
  };
  if (hasBinaryString) {
    reader.readAsBinaryString(blob);
  } else {
    reader.readAsArrayBuffer(blob);
  }
};
},{"./arrayBufferToBinaryString":2}],10:[function(_dereq_,module,exports){
(function (process){
'use strict';

var utils = _dereq_('../shared/utils');
var log = _dereq_('debug')('pouchdb:socket:client');
var isBrowser = typeof process === 'undefined' || process.browser;

exports.preprocessAttachments = function preprocessAttachments(doc) {
  if (!doc._attachments || !Object.keys(doc._attachments)) {
    return utils.Promise.resolve();
  }

  var atts = doc._attachments;
  return utils.Promise.all(Object.keys(atts).map(function (key) {
    var att = atts[key];
    if (att.data && typeof att.data !== 'string') {
      if (isBrowser) {
        return new utils.Promise(function (resolve) {
          utils.readAsBinaryString(att.data, function (binary) {
            att.data = utils.btoa(binary);
            resolve();
          });
        });
      } else {
        att.data = att.data.toString('base64');
      }
    }
  }));
};

var b64StringToBluffer =
  _dereq_('./base64StringToBlobOrBuffer');

exports.readAttachmentsAsBlobOrBuffer = function (row) {
  var atts = (row.doc && row.doc._attachments) ||
    (row.ok && row.ok._attachments);
  if (!atts) {
    return;
  }
  Object.keys(atts).forEach(function (filename) {
    var att = atts[filename];
    att.data = b64StringToBluffer(att.data, att.content_type);
  });
};

exports.stringifyArgs = function stringifyArgs(args) {
  var funcArgs = ['filter', 'map', 'reduce'];
  args.forEach(function (arg) {
    if (typeof arg === 'object' && arg !== null && !Array.isArray(arg)) {
      funcArgs.forEach(function (funcArg) {
        if (funcArg in arg && typeof arg[funcArg] === 'function') {
          arg[funcArg] = {
            type: 'func',
            func: arg[funcArg].toString()
          };
        }
      });
    }
  });
  return JSON.stringify(args);
};

exports.padInt = function padInt(i, len) {
  var res = i.toString();
  while (res.length < len) {
    res = '0' + res;
  }
  return res;
};


exports.adapterFun = function adapterFun(name, callback) {

  function logApiCall(self, name, args) {
    if (!log.enabled) {
      return;
    }
    // db.name was added in pouch 6.0.0
    var dbName = self.name || self._db_name;
    var logArgs = [dbName, name];
    for (var i = 0; i < args.length - 1; i++) {
      logArgs.push(args[i]);
    }
    log.apply(null, logArgs);

    // override the callback itself to log the response
    var origCallback = args[args.length - 1];
    args[args.length - 1] = function (err, res) {
      var responseArgs = [dbName, name];
      responseArgs = responseArgs.concat(
        err ? ['error', err] : ['success', res]
      );
      log.apply(null, responseArgs);
      origCallback(err, res);
    };
  }


  return utils.toPromise(utils.getArguments(function (args) {
    if (this._closed) {
      return utils.Promise.reject(new Error('database is closed'));
    }
    var self = this;
    logApiCall(self, name, args);
    if (!this.taskqueue.isReady) {
      return new utils.Promise(function (fulfill, reject) {
        self.taskqueue.addTask(function (failed) {
          if (failed) {
            reject(failed);
          } else {
            fulfill(self[name].apply(self, args));
          }
        });
      });
    }
    return callback.apply(this, args);
  }));
};
}).call(this,_dereq_('_process'))
},{"../shared/utils":17,"./base64StringToBlobOrBuffer":4,"_process":71,"debug":27}],11:[function(_dereq_,module,exports){
// hey guess what, we don't need this in the browser
module.exports = {};
},{}],12:[function(_dereq_,module,exports){
'use strict';

function cloneArrayBuffer(buff) {
  if (typeof buff.slice === 'function') {
    return buff.slice(0);
  }
  // IE10-11 slice() polyfill
  var target = new ArrayBuffer(buff.byteLength);
  var targetArray = new Uint8Array(target);
  var sourceArray = new Uint8Array(buff);
  targetArray.set(sourceArray);
  return target;
}

module.exports = function cloneBinaryObject(object) {
  if (object instanceof ArrayBuffer) {
    return cloneArrayBuffer(object);
  }
  var size = object.size;
  var type = object.type;
  // Blob
  if (typeof object.slice === 'function') {
    return object.slice(0, size, type);
  }
  // PhantomJS slice() replacement
  return object.webkitSlice(0, size, type);
};

},{}],13:[function(_dereq_,module,exports){
"use strict";

var inherits = _dereq_('inherits');
inherits(PouchError, Error);

function PouchError(opts) {
  Error.call(opts.reason);
  this.status = opts.status;
  this.name = opts.error;
  this.message = opts.reason;
  this.error = true;
}

PouchError.prototype.toString = function () {
  return JSON.stringify({
    status: this.status,
    name: this.name,
    message: this.message
  });
};

exports.UNAUTHORIZED = new PouchError({
  status: 401,
  error: 'unauthorized',
  reason: "Name or password is incorrect."
});

exports.MISSING_BULK_DOCS = new PouchError({
  status: 400,
  error: 'bad_request',
  reason: "Missing JSON list of 'docs'"
});

exports.MISSING_DOC = new PouchError({
  status: 404,
  error: 'not_found',
  reason: 'missing'
});

exports.REV_CONFLICT = new PouchError({
  status: 409,
  error: 'conflict',
  reason: 'Document update conflict'
});

exports.INVALID_ID = new PouchError({
  status: 400,
  error: 'invalid_id',
  reason: '_id field must contain a string'
});

exports.MISSING_ID = new PouchError({
  status: 412,
  error: 'missing_id',
  reason: '_id is required for puts'
});

exports.RESERVED_ID = new PouchError({
  status: 400,
  error: 'bad_request',
  reason: 'Only reserved document ids may start with underscore.'
});

exports.NOT_OPEN = new PouchError({
  status: 412,
  error: 'precondition_failed',
  reason: 'Database not open'
});

exports.UNKNOWN_ERROR = new PouchError({
  status: 500,
  error: 'unknown_error',
  reason: 'Database encountered an unknown error'
});

exports.BAD_ARG = new PouchError({
  status: 500,
  error: 'badarg',
  reason: 'Some query argument is invalid'
});

exports.INVALID_REQUEST = new PouchError({
  status: 400,
  error: 'invalid_request',
  reason: 'Request was invalid'
});

exports.QUERY_PARSE_ERROR = new PouchError({
  status: 400,
  error: 'query_parse_error',
  reason: 'Some query parameter is invalid'
});

exports.DOC_VALIDATION = new PouchError({
  status: 500,
  error: 'doc_validation',
  reason: 'Bad special document member'
});

exports.BAD_REQUEST = new PouchError({
  status: 400,
  error: 'bad_request',
  reason: 'Something wrong with the request'
});

exports.NOT_AN_OBJECT = new PouchError({
  status: 400,
  error: 'bad_request',
  reason: 'Document must be a JSON object'
});

exports.DB_MISSING = new PouchError({
  status: 404,
  error: 'not_found',
  reason: 'Database not found'
});

exports.IDB_ERROR = new PouchError({
  status: 500,
  error: 'indexed_db_went_bad',
  reason: 'unknown'
});

exports.WSQ_ERROR = new PouchError({
  status: 500,
  error: 'web_sql_went_bad',
  reason: 'unknown'
});

exports.LDB_ERROR = new PouchError({
  status: 500,
  error: 'levelDB_went_went_bad',
  reason: 'unknown'
});

exports.FORBIDDEN = new PouchError({
  status: 403,
  error: 'forbidden',
  reason: 'Forbidden by design doc validate_doc_update function'
});

exports.INVALID_REV = new PouchError({
  status: 400,
  error: 'bad_request',
  reason: 'Invalid rev format'
});

exports.FILE_EXISTS = new PouchError({
  status: 412,
  error: 'file_exists',
  reason: 'The database could not be created, the file already exists.'
});

exports.MISSING_STUB = new PouchError({
  status: 412,
  error: 'missing_stub'
});

exports.error = function (error, reason, name) {
  function CustomPouchError(reason) {
    // inherit error properties from our parent error manually
    // so as to allow proper JSON parsing.
    /* jshint ignore:start */
    for (var p in error) {
      if (typeof error[p] !== 'function') {
        this[p] = error[p];
      }
    }
    /* jshint ignore:end */
    if (name !== undefined) {
      this.name = name;
    }
    if (reason !== undefined) {
      this.reason = reason;
    }
  }
  CustomPouchError.prototype = PouchError.prototype;
  return new CustomPouchError(reason);
};

// Find one of the errors defined above based on the value
// of the specified property.
// If reason is provided prefer the error matching that reason.
// This is for differentiating between errors with the same name and status,
// eg, bad_request.
exports.getErrorTypeByProp = function (prop, value, reason) {
  var errors = exports;
  var keys = Object.keys(errors).filter(function (key) {
    var error = errors[key];
    return typeof error !== 'function' && error[prop] === value;
  });
  var key = reason && keys.filter(function (key) {
      var error = errors[key];
      return error.message === reason;
    })[0] || keys[0];
  return (key) ? errors[key] : null;
};

exports.generateErrorFromResponse = function (res) {
  var error, errName, errType, errMsg, errReason;
  var errors = exports;

  errName = (res.error === true && typeof res.name === 'string') ?
    res.name :
    res.error;
  errReason = res.reason;
  errType = errors.getErrorTypeByProp('name', errName, errReason);

  if (res.missing ||
    errReason === 'missing' ||
    errReason === 'deleted' ||
    errName === 'not_found') {
    errType = errors.MISSING_DOC;
  } else if (errName === 'doc_validation') {
    // doc validation needs special treatment since
    // res.reason depends on the validation error.
    // see utils.js
    errType = errors.DOC_VALIDATION;
    errMsg = errReason;
  } else if (errName === 'bad_request' && errType.message !== errReason) {
    // if bad_request error already found based on reason don't override.

    // attachment errors.
    if (errReason.indexOf('unknown stub attachment') === 0) {
      errType = errors.MISSING_STUB;
      errMsg = errReason;
    } else {
      errType = errors.BAD_REQUEST;
    }
  }

  // fallback to error by statys or unknown error.
  if (!errType) {
    errType = errors.getErrorTypeByProp('status', res.status, errReason) ||
    errors.UNKNOWN_ERROR;
  }

  error = errors.error(errType, errReason, errName);

  // Keep custom message.
  if (errMsg) {
    error.message = errMsg;
  }

  // Keep helpful response data in our error messages.
  if (res.id) {
    error.id = res.id;
  }
  if (res.status) {
    error.status = res.status;
  }
  if (res.statusText) {
    error.name = res.statusText;
  }
  if (res.missing) {
    error.missing = res.missing;
  }

  return error;
};

},{"inherits":48}],14:[function(_dereq_,module,exports){
'use strict';

module.exports = function isBinaryObject(object) {
  return object instanceof ArrayBuffer ||
    (typeof Blob !== 'undefined' && object instanceof Blob);
};
},{}],15:[function(_dereq_,module,exports){
'use strict';

function parseMessage(msg, numArgs) {
  var res = [];
  for (var i = 0; i < numArgs - 1; i++) {
    var idx = msg.indexOf(':');
    res.push(msg.substring(0, idx));
    msg = msg.substring(idx + 1);
  }
  res.push(msg);
  return res;
}

module.exports = parseMessage;
},{}],16:[function(_dereq_,module,exports){
'use strict';

var isBinaryObject = _dereq_('./isBinaryObject');
var cloneBinaryObject = _dereq_('./cloneBinaryObject');

module.exports = function clone(object) {
  var newObject;
  var i;
  var len;

  if (!object || typeof object !== 'object') {
    return object;
  }

  if (Array.isArray(object)) {
    newObject = [];
    for (i = 0, len = object.length; i < len; i++) {
      newObject[i] = clone(object[i]);
    }
    return newObject;
  }

  // special case: to avoid inconsistencies between IndexedDB
  // and other backends, we automatically stringify Dates
  if (object instanceof Date) {
    return object.toISOString();
  }

  if (isBinaryObject(object)) {
    return cloneBinaryObject(object);
  }

  newObject = {};
  for (i in object) {
    if (Object.prototype.hasOwnProperty.call(object, i)) {
      var value = clone(object[i]);
      if (typeof value !== 'undefined') {
        newObject[i] = value;
      }
    }
  }
  return newObject;
};

},{"./cloneBinaryObject":12,"./isBinaryObject":14}],17:[function(_dereq_,module,exports){
(function (process){
'use strict';

var Promise = _dereq_('pouchdb-promise');
var buffer = _dereq_('./buffer');

exports.lastIndexOf = function lastIndexOf(str, char) {
  for (var i = str.length - 1; i >= 0; i--) {
    if (str.charAt(i) === char) {
      return i;
    }
  }
  return -1;
};

exports.clone = _dereq_('./pouchdb-clone');

exports.parseMessage = _dereq_('./parse-message');

/* istanbul ignore next */
exports.once = function once(fun) {
  var called = false;
  return exports.getArguments(function (args) {
    if (called) {
      console.trace();
      throw new Error('once called  more than once');
    } else {
      called = true;
      fun.apply(this, args);
    }
  });
};
/* istanbul ignore next */
exports.getArguments = function getArguments(fun) {
  return function () {
    var len = arguments.length;
    var args = new Array(len);
    var i = -1;
    while (++i < len) {
      args[i] = arguments[i];
    }
    return fun.call(this, args);
  };
};
/* istanbul ignore next */
exports.toPromise = function toPromise(func) {
  //create the function we will be returning
  return exports.getArguments(function (args) {
    var self = this;
    var tempCB = (typeof args[args.length - 1] === 'function') ? args.pop() : false;
    // if the last argument is a function, assume its a callback
    var usedCB;
    if (tempCB) {
      // if it was a callback, create a new callback which calls it,
      // but do so async so we don't trap any errors
      usedCB = function (err, resp) {
        process.nextTick(function () {
          tempCB(err, resp);
        });
      };
    }
    var promise = new Promise(function (fulfill, reject) {
      try {
        var callback = exports.once(function (err, mesg) {
          if (err) {
            reject(err);
          } else {
            fulfill(mesg);
          }
        });
        // create a callback for this invocation
        // apply the function in the orig context
        args.push(callback);
        func.apply(self, args);
      } catch (e) {
        reject(e);
      }
    });
    // if there is a callback, call it back
    if (usedCB) {
      promise.then(function (result) {
        usedCB(null, result);
      }, usedCB);
    }
    promise.cancel = function () {
      return this;
    };
    return promise;
  });
};

if (typeof atob === 'function') {
  exports.atob = function atobShim(str) {
    return atob(str);
  };
} else {
  exports.atob = function atobShim(str) {
    var base64 = new buffer(str, 'base64');
    // Node.js will just skip the characters it can't encode instead of
    // throwing and exception
    if (base64.toString('base64') !== str) {
      throw ("Cannot base64 encode full string");
    }
    return base64.toString('binary');
  };
}

if (typeof btoa === 'function') {
  exports.btoa = function btoaShim(str) {
    return btoa(str);
  };
} else {
  exports.btoa = function btoaShim(str) {
    return new buffer(str, 'binary').toString('base64');
  };
}

exports.inherits = _dereq_('inherits');
exports.Promise = Promise;

var binUtil = _dereq_('pouchdb-binary-util');

exports.createBlob = binUtil.createBlob;
exports.readAsArrayBuffer = binUtil.readAsArrayBuffer;
exports.readAsBinaryString = binUtil.readAsBinaryString;
exports.binaryStringToArrayBuffer = binUtil.binaryStringToArrayBuffer;
exports.arrayBufferToBinaryString = binUtil.arrayBufferToBinaryString;
}).call(this,_dereq_('_process'))
},{"./buffer":11,"./parse-message":15,"./pouchdb-clone":16,"_process":71,"inherits":48,"pouchdb-binary-util":68,"pouchdb-promise":69}],18:[function(_dereq_,module,exports){
"use strict";

// BEGIN Math.uuid.js

/*!
 Math.uuid.js (v1.4)
 http://www.broofa.com
 mailto:robert@broofa.com

 Copyright (c) 2010 Robert Kieffer
 Dual licensed under the MIT and GPL licenses.
 */

/*
 * Generate a random uuid.
 *
 * USAGE: Math.uuid(length, radix)
 *   length - the desired number of characters
 *   radix  - the number of allowable values for each character.
 *
 * EXAMPLES:
 *   // No arguments  - returns RFC4122, version 4 ID
 *   >>> Math.uuid()
 *   "92329D39-6F5C-4520-ABFC-AAB64544E172"
 *
 *   // One argument - returns ID of the specified length
 *   >>> Math.uuid(15)     // 15 character ID (default base=62)
 *   "VcydxgltxrVZSTV"
 *
 *   // Two arguments - returns ID of the specified length, and radix. 
 *   // (Radix must be <= 62)
 *   >>> Math.uuid(8, 2)  // 8 character ID (base=2)
 *   "01001010"
 *   >>> Math.uuid(8, 10) // 8 character ID (base=10)
 *   "47473046"
 *   >>> Math.uuid(8, 16) // 8 character ID (base=16)
 *   "098F4D35"
 */
var chars = (
'0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ' +
'abcdefghijklmnopqrstuvwxyz'
).split('');
function getValue(radix) {
  return 0 | Math.random() * radix;
}
function uuid(len, radix) {
  radix = radix || chars.length;
  var out = '';
  var i = -1;

  if (len) {
    // Compact form
    while (++i < len) {
      out += chars[getValue(radix)];
    }
    return out;
  }
  // rfc4122, version 4 form
  // Fill in random data.  At i==19 set the high bits of clock sequence as
  // per rfc4122, sec. 4.1.5
  while (++i < 36) {
    switch (i) {
      case 8:
      case 13:
      case 18:
      case 23:
        out += '-';
        break;
      case 19:
        out += chars[(getValue(16) & 0x3) | 0x8];
        break;
      default:
        out += chars[getValue(16)];
    }
  }

  return out;
}



module.exports = uuid;


},{}],19:[function(_dereq_,module,exports){
module.exports = after

function after(count, callback, err_cb) {
    var bail = false
    err_cb = err_cb || noop
    proxy.count = count

    return (count === 0) ? callback() : proxy

    function proxy(err, result) {
        if (proxy.count <= 0) {
            throw new Error('after called too many times')
        }
        --proxy.count

        // after first error, rest are passed to err_cb
        if (err) {
            bail = true
            callback(err)
            // future error callbacks will go to error handler
            callback = err_cb
        } else if (proxy.count === 0 && !bail) {
            callback(null, result)
        }
    }
}

function noop() {}

},{}],20:[function(_dereq_,module,exports){
/**
 * An abstraction for slicing an arraybuffer even when
 * ArrayBuffer.prototype.slice is not supported
 *
 * @api public
 */

module.exports = function(arraybuffer, start, end) {
  var bytes = arraybuffer.byteLength;
  start = start || 0;
  end = end || bytes;

  if (arraybuffer.slice) { return arraybuffer.slice(start, end); }

  if (start < 0) { start += bytes; }
  if (end < 0) { end += bytes; }
  if (end > bytes) { end = bytes; }

  if (start >= bytes || start >= end || bytes === 0) {
    return new ArrayBuffer(0);
  }

  var abv = new Uint8Array(arraybuffer);
  var result = new Uint8Array(end - start);
  for (var i = start, ii = 0; i < end; i++, ii++) {
    result[ii] = abv[i];
  }
  return result.buffer;
};

},{}],21:[function(_dereq_,module,exports){
/*
 * base64-arraybuffer
 * https://github.com/niklasvh/base64-arraybuffer
 *
 * Copyright (c) 2012 Niklas von Hertzen
 * Licensed under the MIT license.
 */
(function(){
  "use strict";

  var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

  // Use a lookup table to find the index.
  var lookup = new Uint8Array(256);
  for (var i = 0; i < chars.length; i++) {
    lookup[chars.charCodeAt(i)] = i;
  }

  exports.encode = function(arraybuffer) {
    var bytes = new Uint8Array(arraybuffer),
    i, len = bytes.length, base64 = "";

    for (i = 0; i < len; i+=3) {
      base64 += chars[bytes[i] >> 2];
      base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];
      base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];
      base64 += chars[bytes[i + 2] & 63];
    }

    if ((len % 3) === 2) {
      base64 = base64.substring(0, base64.length - 1) + "=";
    } else if (len % 3 === 1) {
      base64 = base64.substring(0, base64.length - 2) + "==";
    }

    return base64;
  };

  exports.decode =  function(base64) {
    var bufferLength = base64.length * 0.75,
    len = base64.length, i, p = 0,
    encoded1, encoded2, encoded3, encoded4;

    if (base64[base64.length - 1] === "=") {
      bufferLength--;
      if (base64[base64.length - 2] === "=") {
        bufferLength--;
      }
    }

    var arraybuffer = new ArrayBuffer(bufferLength),
    bytes = new Uint8Array(arraybuffer);

    for (i = 0; i < len; i+=4) {
      encoded1 = lookup[base64.charCodeAt(i)];
      encoded2 = lookup[base64.charCodeAt(i+1)];
      encoded3 = lookup[base64.charCodeAt(i+2)];
      encoded4 = lookup[base64.charCodeAt(i+3)];

      bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);
      bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);
      bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);
    }

    return arraybuffer;
  };
})();

},{}],22:[function(_dereq_,module,exports){
'use strict';

/* jshint -W079 */
var Blob = _dereq_('blob');
var Promise = _dereq_('native-or-lie');

//
// PRIVATE
//

// From http://stackoverflow.com/questions/14967647/ (continues on next line)
// encode-decode-image-with-base64-breaks-image (2013-04-21)
function binaryStringToArrayBuffer(binary) {
  var length = binary.length;
  var buf = new ArrayBuffer(length);
  var arr = new Uint8Array(buf);
  var i = -1;
  while (++i < length) {
    arr[i] = binary.charCodeAt(i);
  }
  return buf;
}

// Can't find original post, but this is close
// http://stackoverflow.com/questions/6965107/ (continues on next line)
// converting-between-strings-and-arraybuffers
function arrayBufferToBinaryString(buffer) {
  var binary = '';
  var bytes = new Uint8Array(buffer);
  var length = bytes.byteLength;
  var i = -1;
  while (++i < length) {
    binary += String.fromCharCode(bytes[i]);
  }
  return binary;
}

// doesn't download the image more than once, because
// browsers aren't dumb. uses the cache
function loadImage(src, crossOrigin) {
  return new Promise(function (resolve, reject) {
    var img = new Image();
    if (crossOrigin) {
      img.crossOrigin = crossOrigin;
    }
    img.onload = function () {
      resolve(img);
    };
    img.onerror = reject;
    img.src = src;
  });
}

function imgToCanvas(img) {
  var canvas = document.createElement('canvas');

  canvas.width = img.width;
  canvas.height = img.height;

  // copy the image contents to the canvas
  var context = canvas.getContext('2d');
  context.drawImage(
    img,
    0, 0,
    img.width, img.height,
    0, 0,
    img.width, img.height);

  return canvas;
}

//
// PUBLIC
//

/**
 * Shim for
 * [new Blob()]{@link https://developer.mozilla.org/en-US/docs/Web/API/Blob.Blob}
 * to support
 * [older browsers that use the deprecated <code>BlobBuilder</code> API]{@link http://caniuse.com/blob}.
 *
 * @param {Array} parts - content of the <code>Blob</code>
 * @param {Object} options - usually just <code>{type: myContentType}</code>
 * @returns {Blob}
 */
function createBlob(parts, options) {
  options = options || {};
  if (typeof options === 'string') {
    options = {type: options}; // do you a solid here
  }
  return new Blob(parts, options);
}

/**
 * Shim for
 * [URL.createObjectURL()]{@link https://developer.mozilla.org/en-US/docs/Web/API/URL.createObjectURL}
 * to support browsers that only have the prefixed
 * <code>webkitURL</code> (e.g. Android <4.4).
 * @param {Blob} blob
 * @returns {string} url
 */
function createObjectURL(blob) {
  return (window.URL || window.webkitURL).createObjectURL(blob);
}

/**
 * Shim for
 * [URL.revokeObjectURL()]{@link https://developer.mozilla.org/en-US/docs/Web/API/URL.revokeObjectURL}
 * to support browsers that only have the prefixed
 * <code>webkitURL</code> (e.g. Android <4.4).
 * @param {string} url
 */
function revokeObjectURL(url) {
  return (window.URL || window.webkitURL).revokeObjectURL(url);
}

/**
 * Convert a <code>Blob</code> to a binary string. Returns a Promise.
 *
 * @param {Blob} blob
 * @returns {Promise} Promise that resolves with the binary string
 */
function blobToBinaryString(blob) {
  return new Promise(function (resolve, reject) {
    var reader = new FileReader();
    var hasBinaryString = typeof reader.readAsBinaryString === 'function';
    reader.onloadend = function (e) {
      var result = e.target.result || '';
      if (hasBinaryString) {
        return resolve(result);
      }
      resolve(arrayBufferToBinaryString(result));
    };
    reader.onerror = reject;
    if (hasBinaryString) {
      reader.readAsBinaryString(blob);
    } else {
      reader.readAsArrayBuffer(blob);
    }
  });
}

/**
 * Convert a base64-encoded string to a <code>Blob</code>. Returns a Promise.
 * @param {string} base64
 * @param {string|undefined} type - the content type (optional)
 * @returns {Promise} Promise that resolves with the <code>Blob</code>
 */
function base64StringToBlob(base64, type) {
  return Promise.resolve().then(function () {
    var parts = [binaryStringToArrayBuffer(atob(base64))];
    return type ? createBlob(parts, {type: type}) : createBlob(parts);
  });
}

/**
 * Convert a binary string to a <code>Blob</code>. Returns a Promise.
 * @param {string} binary
 * @param {string|undefined} type - the content type (optional)
 * @returns {Promise} Promise that resolves with the <code>Blob</code>
 */
function binaryStringToBlob(binary, type) {
  return Promise.resolve().then(function () {
    return base64StringToBlob(btoa(binary), type);
  });
}

/**
 * Convert a <code>Blob</code> to a binary string. Returns a Promise.
 * @param {Blob} blob
 * @returns {Promise} Promise that resolves with the binary string
 */
function blobToBase64String(blob) {
  return blobToBinaryString(blob).then(function (binary) {
    return btoa(binary);
  });
}

/**
 * Convert a data URL string
 * (e.g. <code>'data:image/png;base64,iVBORw0KG...'</code>)
 * to a <code>Blob</code>. Returns a Promise.
 * @param {string} dataURL
 * @returns {Promise} Promise that resolves with the <code>Blob</code>
 */
function dataURLToBlob(dataURL) {
  return Promise.resolve().then(function () {
    var type = dataURL.match(/data:([^;]+)/)[1];
    var base64 = dataURL.replace(/^[^,]+,/, '');

    var buff = binaryStringToArrayBuffer(atob(base64));
    return createBlob([buff], {type: type});
  });
}

/**
 * Convert an image's <code>src</code> URL to a data URL by loading the image and painting
 * it to a <code>canvas</code>. Returns a Promise.
 *
 * <p/>Note: this will coerce the image to the desired content type, and it
 * will only paint the first frame of an animated GIF.
 *
 * @param {string} src
 * @param {string|undefined} type - the content type (optional, defaults to 'image/png')
 * @param {string|undefined} crossOrigin - for CORS-enabled images, set this to
 *                                         'Anonymous' to avoid "tainted canvas" errors
 * @param {number|undefined} quality - a number between 0 and 1 indicating image quality
 *                                     if the requested type is 'image/jpeg' or 'image/webp'
 * @returns {Promise} Promise that resolves with the data URL string
 */
function imgSrcToDataURL(src, type, crossOrigin, quality) {
  type = type || 'image/png';

  return loadImage(src, crossOrigin).then(function (img) {
    return imgToCanvas(img);
  }).then(function (canvas) {
    return canvas.toDataURL(type, quality);
  });
}

/**
 * Convert a <code>canvas</code> to a <code>Blob</code>. Returns a Promise.
 * @param {string} canvas
 * @param {string|undefined} type - the content type (optional, defaults to 'image/png')
 * @param {number|undefined} quality - a number between 0 and 1 indicating image quality
 *                                     if the requested type is 'image/jpeg' or 'image/webp'
 * @returns {Promise} Promise that resolves with the <code>Blob</code>
 */
function canvasToBlob(canvas, type, quality) {
  return Promise.resolve().then(function () {
    if (typeof canvas.toBlob === 'function') {
      return new Promise(function (resolve) {
        canvas.toBlob(resolve, type, quality);
      });
    }
    return dataURLToBlob(canvas.toDataURL(type, quality));
  });
}

/**
 * Convert an image's <code>src</code> URL to a <code>Blob</code> by loading the image and painting
 * it to a <code>canvas</code>. Returns a Promise.
 *
 * <p/>Note: this will coerce the image to the desired content type, and it
 * will only paint the first frame of an animated GIF.
 *
 * @param {string} src
 * @param {string|undefined} type - the content type (optional, defaults to 'image/png')
 * @param {string|undefined} crossOrigin - for CORS-enabled images, set this to
 *                                         'Anonymous' to avoid "tainted canvas" errors
 * @param {number|undefined} quality - a number between 0 and 1 indicating image quality
 *                                     if the requested type is 'image/jpeg' or 'image/webp'
 * @returns {Promise} Promise that resolves with the <code>Blob</code>
 */
function imgSrcToBlob(src, type, crossOrigin, quality) {
  type = type || 'image/png';

  return loadImage(src, crossOrigin).then(function (img) {
    return imgToCanvas(img);
  }).then(function (canvas) {
    return canvasToBlob(canvas, type, quality);
  });
}

/**
 * Convert an <code>ArrayBuffer</code> to a <code>Blob</code>. Returns a Promise.
 *
 * @param {ArrayBuffer} buffer
 * @param {string|undefined} type - the content type (optional)
 * @returns {Promise} Promise that resolves with the <code>Blob</code>
 */
function arrayBufferToBlob(buffer, type) {
  return Promise.resolve().then(function () {
    return createBlob([buffer], type);
  });
}

/**
 * Convert a <code>Blob</code> to an <code>ArrayBuffer</code>. Returns a Promise.
 * @param {Blob} blob
 * @returns {Promise} Promise that resolves with the <code>ArrayBuffer</code>
 */
function blobToArrayBuffer(blob) {
  return new Promise(function (resolve, reject) {
    var reader = new FileReader();
    reader.onloadend = function (e) {
      var result = e.target.result || new ArrayBuffer(0);
      resolve(result);
    };
    reader.onerror = reject;
    reader.readAsArrayBuffer(blob);
  });
}

module.exports = {
  createBlob         : createBlob,
  createObjectURL    : createObjectURL,
  revokeObjectURL    : revokeObjectURL,
  imgSrcToBlob       : imgSrcToBlob,
  imgSrcToDataURL    : imgSrcToDataURL,
  canvasToBlob       : canvasToBlob,
  dataURLToBlob      : dataURLToBlob,
  blobToBase64String : blobToBase64String,
  base64StringToBlob : base64StringToBlob,
  binaryStringToBlob : binaryStringToBlob,
  blobToBinaryString : blobToBinaryString,
  arrayBufferToBlob  : arrayBufferToBlob,
  blobToArrayBuffer  : blobToArrayBuffer
};

},{"blob":23,"native-or-lie":64}],23:[function(_dereq_,module,exports){
(function (global){
/**
 * Create a blob builder even when vendor prefixes exist
 */

var BlobBuilder = global.BlobBuilder
  || global.WebKitBlobBuilder
  || global.MSBlobBuilder
  || global.MozBlobBuilder;

/**
 * Check if Blob constructor is supported
 */

var blobSupported = (function() {
  try {
    var a = new Blob(['hi']);
    return a.size === 2;
  } catch(e) {
    return false;
  }
})();

/**
 * Check if Blob constructor supports ArrayBufferViews
 * Fails in Safari 6, so we need to map to ArrayBuffers there.
 */

var blobSupportsArrayBufferView = blobSupported && (function() {
  try {
    var b = new Blob([new Uint8Array([1,2])]);
    return b.size === 2;
  } catch(e) {
    return false;
  }
})();

/**
 * Check if BlobBuilder is supported
 */

var blobBuilderSupported = BlobBuilder
  && BlobBuilder.prototype.append
  && BlobBuilder.prototype.getBlob;

/**
 * Helper function that maps ArrayBufferViews to ArrayBuffers
 * Used by BlobBuilder constructor and old browsers that didn't
 * support it in the Blob constructor.
 */

function mapArrayBufferViews(ary) {
  for (var i = 0; i < ary.length; i++) {
    var chunk = ary[i];
    if (chunk.buffer instanceof ArrayBuffer) {
      var buf = chunk.buffer;

      // if this is a subarray, make a copy so we only
      // include the subarray region from the underlying buffer
      if (chunk.byteLength !== buf.byteLength) {
        var copy = new Uint8Array(chunk.byteLength);
        copy.set(new Uint8Array(buf, chunk.byteOffset, chunk.byteLength));
        buf = copy.buffer;
      }

      ary[i] = buf;
    }
  }
}

function BlobBuilderConstructor(ary, options) {
  options = options || {};

  var bb = new BlobBuilder();
  mapArrayBufferViews(ary);

  for (var i = 0; i < ary.length; i++) {
    bb.append(ary[i]);
  }

  return (options.type) ? bb.getBlob(options.type) : bb.getBlob();
};

function BlobConstructor(ary, options) {
  mapArrayBufferViews(ary);
  return new Blob(ary, options || {});
};

module.exports = (function() {
  if (blobSupported) {
    return blobSupportsArrayBufferView ? global.Blob : BlobConstructor;
  } else if (blobBuilderSupported) {
    return BlobBuilderConstructor;
  } else {
    return undefined;
  }
})();

}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],24:[function(_dereq_,module,exports){

},{}],25:[function(_dereq_,module,exports){

/**
 * Expose `Emitter`.
 */

module.exports = Emitter;

/**
 * Initialize a new `Emitter`.
 *
 * @api public
 */

function Emitter(obj) {
  if (obj) return mixin(obj);
};

/**
 * Mixin the emitter properties.
 *
 * @param {Object} obj
 * @return {Object}
 * @api private
 */

function mixin(obj) {
  for (var key in Emitter.prototype) {
    obj[key] = Emitter.prototype[key];
  }
  return obj;
}

/**
 * Listen on the given `event` with `fn`.
 *
 * @param {String} event
 * @param {Function} fn
 * @return {Emitter}
 * @api public
 */

Emitter.prototype.on =
Emitter.prototype.addEventListener = function(event, fn){
  this._callbacks = this._callbacks || {};
  (this._callbacks[event] = this._callbacks[event] || [])
    .push(fn);
  return this;
};

/**
 * Adds an `event` listener that will be invoked a single
 * time then automatically removed.
 *
 * @param {String} event
 * @param {Function} fn
 * @return {Emitter}
 * @api public
 */

Emitter.prototype.once = function(event, fn){
  var self = this;
  this._callbacks = this._callbacks || {};

  function on() {
    self.off(event, on);
    fn.apply(this, arguments);
  }

  on.fn = fn;
  this.on(event, on);
  return this;
};

/**
 * Remove the given callback for `event` or all
 * registered callbacks.
 *
 * @param {String} event
 * @param {Function} fn
 * @return {Emitter}
 * @api public
 */

Emitter.prototype.off =
Emitter.prototype.removeListener =
Emitter.prototype.removeAllListeners =
Emitter.prototype.removeEventListener = function(event, fn){
  this._callbacks = this._callbacks || {};

  // all
  if (0 == arguments.length) {
    this._callbacks = {};
    return this;
  }

  // specific event
  var callbacks = this._callbacks[event];
  if (!callbacks) return this;

  // remove all handlers
  if (1 == arguments.length) {
    delete this._callbacks[event];
    return this;
  }

  // remove specific handler
  var cb;
  for (var i = 0; i < callbacks.length; i++) {
    cb = callbacks[i];
    if (cb === fn || cb.fn === fn) {
      callbacks.splice(i, 1);
      break;
    }
  }
  return this;
};

/**
 * Emit `event` with the given args.
 *
 * @param {String} event
 * @param {Mixed} ...
 * @return {Emitter}
 */

Emitter.prototype.emit = function(event){
  this._callbacks = this._callbacks || {};
  var args = [].slice.call(arguments, 1)
    , callbacks = this._callbacks[event];

  if (callbacks) {
    callbacks = callbacks.slice(0);
    for (var i = 0, len = callbacks.length; i < len; ++i) {
      callbacks[i].apply(this, args);
    }
  }

  return this;
};

/**
 * Return array of callbacks for `event`.
 *
 * @param {String} event
 * @return {Array}
 * @api public
 */

Emitter.prototype.listeners = function(event){
  this._callbacks = this._callbacks || {};
  return this._callbacks[event] || [];
};

/**
 * Check if this emitter has `event` handlers.
 *
 * @param {String} event
 * @return {Boolean}
 * @api public
 */

Emitter.prototype.hasListeners = function(event){
  return !! this.listeners(event).length;
};

},{}],26:[function(_dereq_,module,exports){

module.exports = function(a, b){
  var fn = function(){};
  fn.prototype = b.prototype;
  a.prototype = new fn;
  a.prototype.constructor = a;
};
},{}],27:[function(_dereq_,module,exports){
(function (process){

/**
 * This is the web browser implementation of `debug()`.
 *
 * Expose `debug()` as the module.
 */

exports = module.exports = _dereq_('./debug');
exports.log = log;
exports.formatArgs = formatArgs;
exports.save = save;
exports.load = load;
exports.useColors = useColors;
exports.storage = 'undefined' != typeof chrome
               && 'undefined' != typeof chrome.storage
                  ? chrome.storage.local
                  : localstorage();

/**
 * Colors.
 */

exports.colors = [
  'lightseagreen',
  'forestgreen',
  'goldenrod',
  'dodgerblue',
  'darkorchid',
  'crimson'
];

/**
 * Currently only WebKit-based Web Inspectors, Firefox >= v31,
 * and the Firebug extension (any Firefox version) are known
 * to support "%c" CSS customizations.
 *
 * TODO: add a `localStorage` variable to explicitly enable/disable colors
 */

function useColors() {
  // is webkit? http://stackoverflow.com/a/16459606/376773
  // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
  return (typeof document !== 'undefined' && 'WebkitAppearance' in document.documentElement.style) ||
    // is firebug? http://stackoverflow.com/a/398120/376773
    (window.console && (console.firebug || (console.exception && console.table))) ||
    // is firefox >= v31?
    // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
    (navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31);
}

/**
 * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
 */

exports.formatters.j = function(v) {
  return JSON.stringify(v);
};


/**
 * Colorize log arguments if enabled.
 *
 * @api public
 */

function formatArgs() {
  var args = arguments;
  var useColors = this.useColors;

  args[0] = (useColors ? '%c' : '')
    + this.namespace
    + (useColors ? ' %c' : ' ')
    + args[0]
    + (useColors ? '%c ' : ' ')
    + '+' + exports.humanize(this.diff);

  if (!useColors) return args;

  var c = 'color: ' + this.color;
  args = [args[0], c, 'color: inherit'].concat(Array.prototype.slice.call(args, 1));

  // the final "%c" is somewhat tricky, because there could be other
  // arguments passed either before or after the %c, so we need to
  // figure out the correct index to insert the CSS into
  var index = 0;
  var lastC = 0;
  args[0].replace(/%[a-z%]/g, function(match) {
    if ('%%' === match) return;
    index++;
    if ('%c' === match) {
      // we only are interested in the *last* %c
      // (the user may have provided their own)
      lastC = index;
    }
  });

  args.splice(lastC, 0, c);
  return args;
}

/**
 * Invokes `console.log()` when available.
 * No-op when `console.log` is not a "function".
 *
 * @api public
 */

function log() {
  // this hackery is required for IE8/9, where
  // the `console.log` function doesn't have 'apply'
  return 'object' === typeof console
    && console.log
    && Function.prototype.apply.call(console.log, console, arguments);
}

/**
 * Save `namespaces`.
 *
 * @param {String} namespaces
 * @api private
 */

function save(namespaces) {
  try {
    if (null == namespaces) {
      exports.storage.removeItem('debug');
    } else {
      exports.storage.debug = namespaces;
    }
  } catch(e) {}
}

/**
 * Load `namespaces`.
 *
 * @return {String} returns the previously persisted debug modes
 * @api private
 */

function load() {
  var r;
  try {
    r = exports.storage.debug;
  } catch(e) {}

  // If debug isn't set in LS, and we're in Electron, try to load $DEBUG
  if ('env' in (typeof process === 'undefined' ? {} : process)) {
    r = process.env.DEBUG;
  }
  
  return r;
}

/**
 * Enable namespaces listed in `localStorage.debug` initially.
 */

exports.enable(load());

/**
 * Localstorage attempts to return the localstorage.
 *
 * This is necessary because safari throws
 * when a user disables cookies/localstorage
 * and you attempt to access it.
 *
 * @return {LocalStorage}
 * @api private
 */

function localstorage(){
  try {
    return window.localStorage;
  } catch (e) {}
}

}).call(this,_dereq_('_process'))
},{"./debug":28,"_process":71}],28:[function(_dereq_,module,exports){

/**
 * This is the common logic for both the Node.js and web browser
 * implementations of `debug()`.
 *
 * Expose `debug()` as the module.
 */

exports = module.exports = debug.debug = debug;
exports.coerce = coerce;
exports.disable = disable;
exports.enable = enable;
exports.enabled = enabled;
exports.humanize = _dereq_('ms');

/**
 * The currently active debug mode names, and names to skip.
 */

exports.names = [];
exports.skips = [];

/**
 * Map of special "%n" handling functions, for the debug "format" argument.
 *
 * Valid key names are a single, lowercased letter, i.e. "n".
 */

exports.formatters = {};

/**
 * Previously assigned color.
 */

var prevColor = 0;

/**
 * Previous log timestamp.
 */

var prevTime;

/**
 * Select a color.
 *
 * @return {Number}
 * @api private
 */

function selectColor() {
  return exports.colors[prevColor++ % exports.colors.length];
}

/**
 * Create a debugger with the given `namespace`.
 *
 * @param {String} namespace
 * @return {Function}
 * @api public
 */

function debug(namespace) {

  // define the `disabled` version
  function disabled() {
  }
  disabled.enabled = false;

  // define the `enabled` version
  function enabled() {

    var self = enabled;

    // set `diff` timestamp
    var curr = +new Date();
    var ms = curr - (prevTime || curr);
    self.diff = ms;
    self.prev = prevTime;
    self.curr = curr;
    prevTime = curr;

    // add the `color` if not set
    if (null == self.useColors) self.useColors = exports.useColors();
    if (null == self.color && self.useColors) self.color = selectColor();

    var args = new Array(arguments.length);
    for (var i = 0; i < args.length; i++) {
      args[i] = arguments[i];
    }

    args[0] = exports.coerce(args[0]);

    if ('string' !== typeof args[0]) {
      // anything else let's inspect with %o
      args = ['%o'].concat(args);
    }

    // apply any `formatters` transformations
    var index = 0;
    args[0] = args[0].replace(/%([a-z%])/g, function(match, format) {
      // if we encounter an escaped % then don't increase the array index
      if (match === '%%') return match;
      index++;
      var formatter = exports.formatters[format];
      if ('function' === typeof formatter) {
        var val = args[index];
        match = formatter.call(self, val);

        // now we need to remove `args[index]` since it's inlined in the `format`
        args.splice(index, 1);
        index--;
      }
      return match;
    });

    // apply env-specific formatting
    args = exports.formatArgs.apply(self, args);

    var logFn = enabled.log || exports.log || console.log.bind(console);
    logFn.apply(self, args);
  }
  enabled.enabled = true;

  var fn = exports.enabled(namespace) ? enabled : disabled;

  fn.namespace = namespace;

  return fn;
}

/**
 * Enables a debug mode by namespaces. This can include modes
 * separated by a colon and wildcards.
 *
 * @param {String} namespaces
 * @api public
 */

function enable(namespaces) {
  exports.save(namespaces);

  var split = (namespaces || '').split(/[\s,]+/);
  var len = split.length;

  for (var i = 0; i < len; i++) {
    if (!split[i]) continue; // ignore empty strings
    namespaces = split[i].replace(/[\\^$+?.()|[\]{}]/g, '\\$&').replace(/\*/g, '.*?');
    if (namespaces[0] === '-') {
      exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
    } else {
      exports.names.push(new RegExp('^' + namespaces + '$'));
    }
  }
}

/**
 * Disable debug output.
 *
 * @api public
 */

function disable() {
  exports.enable('');
}

/**
 * Returns true if the given mode name is enabled, false otherwise.
 *
 * @param {String} name
 * @return {Boolean}
 * @api public
 */

function enabled(name) {
  var i, len;
  for (i = 0, len = exports.skips.length; i < len; i++) {
    if (exports.skips[i].test(name)) {
      return false;
    }
  }
  for (i = 0, len = exports.names.length; i < len; i++) {
    if (exports.names[i].test(name)) {
      return true;
    }
  }
  return false;
}

/**
 * Coerce `val`.
 *
 * @param {Mixed} val
 * @return {Mixed}
 * @api private
 */

function coerce(val) {
  if (val instanceof Error) return val.stack || val.message;
  return val;
}

},{"ms":63}],29:[function(_dereq_,module,exports){

module.exports = _dereq_('./lib/index');

},{"./lib/index":30}],30:[function(_dereq_,module,exports){

module.exports = _dereq_('./socket');

/**
 * Exports parser
 *
 * @api public
 *
 */
module.exports.parser = _dereq_('engine.io-parser');

},{"./socket":31,"engine.io-parser":42}],31:[function(_dereq_,module,exports){
(function (global){
/**
 * Module dependencies.
 */

var transports = _dereq_('./transports/index');
var Emitter = _dereq_('component-emitter');
var debug = _dereq_('debug')('engine.io-client:socket');
var index = _dereq_('indexof');
var parser = _dereq_('engine.io-parser');
var parseuri = _dereq_('parseuri');
var parsejson = _dereq_('parsejson');
var parseqs = _dereq_('parseqs');

/**
 * Module exports.
 */

module.exports = Socket;

/**
 * Socket constructor.
 *
 * @param {String|Object} uri or options
 * @param {Object} options
 * @api public
 */

function Socket (uri, opts) {
  if (!(this instanceof Socket)) return new Socket(uri, opts);

  opts = opts || {};

  if (uri && 'object' === typeof uri) {
    opts = uri;
    uri = null;
  }

  if (uri) {
    uri = parseuri(uri);
    opts.hostname = uri.host;
    opts.secure = uri.protocol === 'https' || uri.protocol === 'wss';
    opts.port = uri.port;
    if (uri.query) opts.query = uri.query;
  } else if (opts.host) {
    opts.hostname = parseuri(opts.host).host;
  }

  this.secure = null != opts.secure ? opts.secure
    : (global.location && 'https:' === location.protocol);

  if (opts.hostname && !opts.port) {
    // if no port is specified manually, use the protocol default
    opts.port = this.secure ? '443' : '80';
  }

  this.agent = opts.agent || false;
  this.hostname = opts.hostname ||
    (global.location ? location.hostname : 'localhost');
  this.port = opts.port || (global.location && location.port
      ? location.port
      : (this.secure ? 443 : 80));
  this.query = opts.query || {};
  if ('string' === typeof this.query) this.query = parseqs.decode(this.query);
  this.upgrade = false !== opts.upgrade;
  this.path = (opts.path || '/engine.io').replace(/\/$/, '') + '/';
  this.forceJSONP = !!opts.forceJSONP;
  this.jsonp = false !== opts.jsonp;
  this.forceBase64 = !!opts.forceBase64;
  this.enablesXDR = !!opts.enablesXDR;
  this.timestampParam = opts.timestampParam || 't';
  this.timestampRequests = opts.timestampRequests;
  this.transports = opts.transports || ['polling', 'websocket'];
  this.readyState = '';
  this.writeBuffer = [];
  this.prevBufferLen = 0;
  this.policyPort = opts.policyPort || 843;
  this.rememberUpgrade = opts.rememberUpgrade || false;
  this.binaryType = null;
  this.onlyBinaryUpgrades = opts.onlyBinaryUpgrades;
  this.perMessageDeflate = false !== opts.perMessageDeflate ? (opts.perMessageDeflate || {}) : false;

  if (true === this.perMessageDeflate) this.perMessageDeflate = {};
  if (this.perMessageDeflate && null == this.perMessageDeflate.threshold) {
    this.perMessageDeflate.threshold = 1024;
  }

  // SSL options for Node.js client
  this.pfx = opts.pfx || null;
  this.key = opts.key || null;
  this.passphrase = opts.passphrase || null;
  this.cert = opts.cert || null;
  this.ca = opts.ca || null;
  this.ciphers = opts.ciphers || null;
  this.rejectUnauthorized = opts.rejectUnauthorized === undefined ? null : opts.rejectUnauthorized;

  // other options for Node.js client
  var freeGlobal = typeof global === 'object' && global;
  if (freeGlobal.global === freeGlobal) {
    if (opts.extraHeaders && Object.keys(opts.extraHeaders).length > 0) {
      this.extraHeaders = opts.extraHeaders;
    }
  }

  // set on handshake
  this.id = null;
  this.upgrades = null;
  this.pingInterval = null;
  this.pingTimeout = null;

  // set on heartbeat
  this.pingIntervalTimer = null;
  this.pingTimeoutTimer = null;

  this.open();
}

Socket.priorWebsocketSuccess = false;

/**
 * Mix in `Emitter`.
 */

Emitter(Socket.prototype);

/**
 * Protocol version.
 *
 * @api public
 */

Socket.protocol = parser.protocol; // this is an int

/**
 * Expose deps for legacy compatibility
 * and standalone browser access.
 */

Socket.Socket = Socket;
Socket.Transport = _dereq_('./transport');
Socket.transports = _dereq_('./transports/index');
Socket.parser = _dereq_('engine.io-parser');

/**
 * Creates transport of the given type.
 *
 * @param {String} transport name
 * @return {Transport}
 * @api private
 */

Socket.prototype.createTransport = function (name) {
  debug('creating transport "%s"', name);
  var query = clone(this.query);

  // append engine.io protocol identifier
  query.EIO = parser.protocol;

  // transport name
  query.transport = name;

  // session id if we already have one
  if (this.id) query.sid = this.id;

  var transport = new transports[name]({
    agent: this.agent,
    hostname: this.hostname,
    port: this.port,
    secure: this.secure,
    path: this.path,
    query: query,
    forceJSONP: this.forceJSONP,
    jsonp: this.jsonp,
    forceBase64: this.forceBase64,
    enablesXDR: this.enablesXDR,
    timestampRequests: this.timestampRequests,
    timestampParam: this.timestampParam,
    policyPort: this.policyPort,
    socket: this,
    pfx: this.pfx,
    key: this.key,
    passphrase: this.passphrase,
    cert: this.cert,
    ca: this.ca,
    ciphers: this.ciphers,
    rejectUnauthorized: this.rejectUnauthorized,
    perMessageDeflate: this.perMessageDeflate,
    extraHeaders: this.extraHeaders
  });

  return transport;
};

function clone (obj) {
  var o = {};
  for (var i in obj) {
    if (obj.hasOwnProperty(i)) {
      o[i] = obj[i];
    }
  }
  return o;
}

/**
 * Initializes transport to use and starts probe.
 *
 * @api private
 */
Socket.prototype.open = function () {
  var transport;
  if (this.rememberUpgrade && Socket.priorWebsocketSuccess && this.transports.indexOf('websocket') !== -1) {
    transport = 'websocket';
  } else if (0 === this.transports.length) {
    // Emit error on next tick so it can be listened to
    var self = this;
    setTimeout(function () {
      self.emit('error', 'No transports available');
    }, 0);
    return;
  } else {
    transport = this.transports[0];
  }
  this.readyState = 'opening';

  // Retry with the next transport if the transport is disabled (jsonp: false)
  try {
    transport = this.createTransport(transport);
  } catch (e) {
    this.transports.shift();
    this.open();
    return;
  }

  transport.open();
  this.setTransport(transport);
};

/**
 * Sets the current transport. Disables the existing one (if any).
 *
 * @api private
 */

Socket.prototype.setTransport = function (transport) {
  debug('setting transport %s', transport.name);
  var self = this;

  if (this.transport) {
    debug('clearing existing transport %s', this.transport.name);
    this.transport.removeAllListeners();
  }

  // set up transport
  this.transport = transport;

  // set up transport listeners
  transport
  .on('drain', function () {
    self.onDrain();
  })
  .on('packet', function (packet) {
    self.onPacket(packet);
  })
  .on('error', function (e) {
    self.onError(e);
  })
  .on('close', function () {
    self.onClose('transport close');
  });
};

/**
 * Probes a transport.
 *
 * @param {String} transport name
 * @api private
 */

Socket.prototype.probe = function (name) {
  debug('probing transport "%s"', name);
  var transport = this.createTransport(name, { probe: 1 });
  var failed = false;
  var self = this;

  Socket.priorWebsocketSuccess = false;

  function onTransportOpen () {
    if (self.onlyBinaryUpgrades) {
      var upgradeLosesBinary = !this.supportsBinary && self.transport.supportsBinary;
      failed = failed || upgradeLosesBinary;
    }
    if (failed) return;

    debug('probe transport "%s" opened', name);
    transport.send([{ type: 'ping', data: 'probe' }]);
    transport.once('packet', function (msg) {
      if (failed) return;
      if ('pong' === msg.type && 'probe' === msg.data) {
        debug('probe transport "%s" pong', name);
        self.upgrading = true;
        self.emit('upgrading', transport);
        if (!transport) return;
        Socket.priorWebsocketSuccess = 'websocket' === transport.name;

        debug('pausing current transport "%s"', self.transport.name);
        self.transport.pause(function () {
          if (failed) return;
          if ('closed' === self.readyState) return;
          debug('changing transport and sending upgrade packet');

          cleanup();

          self.setTransport(transport);
          transport.send([{ type: 'upgrade' }]);
          self.emit('upgrade', transport);
          transport = null;
          self.upgrading = false;
          self.flush();
        });
      } else {
        debug('probe transport "%s" failed', name);
        var err = new Error('probe error');
        err.transport = transport.name;
        self.emit('upgradeError', err);
      }
    });
  }

  function freezeTransport () {
    if (failed) return;

    // Any callback called by transport should be ignored since now
    failed = true;

    cleanup();

    transport.close();
    transport = null;
  }

  // Handle any error that happens while probing
  function onerror (err) {
    var error = new Error('probe error: ' + err);
    error.transport = transport.name;

    freezeTransport();

    debug('probe transport "%s" failed because of error: %s', name, err);

    self.emit('upgradeError', error);
  }

  function onTransportClose () {
    onerror('transport closed');
  }

  // When the socket is closed while we're probing
  function onclose () {
    onerror('socket closed');
  }

  // When the socket is upgraded while we're probing
  function onupgrade (to) {
    if (transport && to.name !== transport.name) {
      debug('"%s" works - aborting "%s"', to.name, transport.name);
      freezeTransport();
    }
  }

  // Remove all listeners on the transport and on self
  function cleanup () {
    transport.removeListener('open', onTransportOpen);
    transport.removeListener('error', onerror);
    transport.removeListener('close', onTransportClose);
    self.removeListener('close', onclose);
    self.removeListener('upgrading', onupgrade);
  }

  transport.once('open', onTransportOpen);
  transport.once('error', onerror);
  transport.once('close', onTransportClose);

  this.once('close', onclose);
  this.once('upgrading', onupgrade);

  transport.open();
};

/**
 * Called when connection is deemed open.
 *
 * @api public
 */

Socket.prototype.onOpen = function () {
  debug('socket open');
  this.readyState = 'open';
  Socket.priorWebsocketSuccess = 'websocket' === this.transport.name;
  this.emit('open');
  this.flush();

  // we check for `readyState` in case an `open`
  // listener already closed the socket
  if ('open' === this.readyState && this.upgrade && this.transport.pause) {
    debug('starting upgrade probes');
    for (var i = 0, l = this.upgrades.length; i < l; i++) {
      this.probe(this.upgrades[i]);
    }
  }
};

/**
 * Handles a packet.
 *
 * @api private
 */

Socket.prototype.onPacket = function (packet) {
  if ('opening' === this.readyState || 'open' === this.readyState ||
      'closing' === this.readyState) {
    debug('socket receive: type "%s", data "%s"', packet.type, packet.data);

    this.emit('packet', packet);

    // Socket is live - any packet counts
    this.emit('heartbeat');

    switch (packet.type) {
      case 'open':
        this.onHandshake(parsejson(packet.data));
        break;

      case 'pong':
        this.setPing();
        this.emit('pong');
        break;

      case 'error':
        var err = new Error('server error');
        err.code = packet.data;
        this.onError(err);
        break;

      case 'message':
        this.emit('data', packet.data);
        this.emit('message', packet.data);
        break;
    }
  } else {
    debug('packet received with socket readyState "%s"', this.readyState);
  }
};

/**
 * Called upon handshake completion.
 *
 * @param {Object} handshake obj
 * @api private
 */

Socket.prototype.onHandshake = function (data) {
  this.emit('handshake', data);
  this.id = data.sid;
  this.transport.query.sid = data.sid;
  this.upgrades = this.filterUpgrades(data.upgrades);
  this.pingInterval = data.pingInterval;
  this.pingTimeout = data.pingTimeout;
  this.onOpen();
  // In case open handler closes socket
  if ('closed' === this.readyState) return;
  this.setPing();

  // Prolong liveness of socket on heartbeat
  this.removeListener('heartbeat', this.onHeartbeat);
  this.on('heartbeat', this.onHeartbeat);
};

/**
 * Resets ping timeout.
 *
 * @api private
 */

Socket.prototype.onHeartbeat = function (timeout) {
  clearTimeout(this.pingTimeoutTimer);
  var self = this;
  self.pingTimeoutTimer = setTimeout(function () {
    if ('closed' === self.readyState) return;
    self.onClose('ping timeout');
  }, timeout || (self.pingInterval + self.pingTimeout));
};

/**
 * Pings server every `this.pingInterval` and expects response
 * within `this.pingTimeout` or closes connection.
 *
 * @api private
 */

Socket.prototype.setPing = function () {
  var self = this;
  clearTimeout(self.pingIntervalTimer);
  self.pingIntervalTimer = setTimeout(function () {
    debug('writing ping packet - expecting pong within %sms', self.pingTimeout);
    self.ping();
    self.onHeartbeat(self.pingTimeout);
  }, self.pingInterval);
};

/**
* Sends a ping packet.
*
* @api private
*/

Socket.prototype.ping = function () {
  var self = this;
  this.sendPacket('ping', function () {
    self.emit('ping');
  });
};

/**
 * Called on `drain` event
 *
 * @api private
 */

Socket.prototype.onDrain = function () {
  this.writeBuffer.splice(0, this.prevBufferLen);

  // setting prevBufferLen = 0 is very important
  // for example, when upgrading, upgrade packet is sent over,
  // and a nonzero prevBufferLen could cause problems on `drain`
  this.prevBufferLen = 0;

  if (0 === this.writeBuffer.length) {
    this.emit('drain');
  } else {
    this.flush();
  }
};

/**
 * Flush write buffers.
 *
 * @api private
 */

Socket.prototype.flush = function () {
  if ('closed' !== this.readyState && this.transport.writable &&
    !this.upgrading && this.writeBuffer.length) {
    debug('flushing %d packets in socket', this.writeBuffer.length);
    this.transport.send(this.writeBuffer);
    // keep track of current length of writeBuffer
    // splice writeBuffer and callbackBuffer on `drain`
    this.prevBufferLen = this.writeBuffer.length;
    this.emit('flush');
  }
};

/**
 * Sends a message.
 *
 * @param {String} message.
 * @param {Function} callback function.
 * @param {Object} options.
 * @return {Socket} for chaining.
 * @api public
 */

Socket.prototype.write =
Socket.prototype.send = function (msg, options, fn) {
  this.sendPacket('message', msg, options, fn);
  return this;
};

/**
 * Sends a packet.
 *
 * @param {String} packet type.
 * @param {String} data.
 * @param {Object} options.
 * @param {Function} callback function.
 * @api private
 */

Socket.prototype.sendPacket = function (type, data, options, fn) {
  if ('function' === typeof data) {
    fn = data;
    data = undefined;
  }

  if ('function' === typeof options) {
    fn = options;
    options = null;
  }

  if ('closing' === this.readyState || 'closed' === this.readyState) {
    return;
  }

  options = options || {};
  options.compress = false !== options.compress;

  var packet = {
    type: type,
    data: data,
    options: options
  };
  this.emit('packetCreate', packet);
  this.writeBuffer.push(packet);
  if (fn) this.once('flush', fn);
  this.flush();
};

/**
 * Closes the connection.
 *
 * @api private
 */

Socket.prototype.close = function () {
  if ('opening' === this.readyState || 'open' === this.readyState) {
    this.readyState = 'closing';

    var self = this;

    if (this.writeBuffer.length) {
      this.once('drain', function () {
        if (this.upgrading) {
          waitForUpgrade();
        } else {
          close();
        }
      });
    } else if (this.upgrading) {
      waitForUpgrade();
    } else {
      close();
    }
  }

  function close () {
    self.onClose('forced close');
    debug('socket closing - telling transport to close');
    self.transport.close();
  }

  function cleanupAndClose () {
    self.removeListener('upgrade', cleanupAndClose);
    self.removeListener('upgradeError', cleanupAndClose);
    close();
  }

  function waitForUpgrade () {
    // wait for upgrade to finish since we can't send packets while pausing a transport
    self.once('upgrade', cleanupAndClose);
    self.once('upgradeError', cleanupAndClose);
  }

  return this;
};

/**
 * Called upon transport error
 *
 * @api private
 */

Socket.prototype.onError = function (err) {
  debug('socket error %j', err);
  Socket.priorWebsocketSuccess = false;
  this.emit('error', err);
  this.onClose('transport error', err);
};

/**
 * Called upon transport close.
 *
 * @api private
 */

Socket.prototype.onClose = function (reason, desc) {
  if ('opening' === this.readyState || 'open' === this.readyState || 'closing' === this.readyState) {
    debug('socket close with reason: "%s"', reason);
    var self = this;

    // clear timers
    clearTimeout(this.pingIntervalTimer);
    clearTimeout(this.pingTimeoutTimer);

    // stop event from firing again for transport
    this.transport.removeAllListeners('close');

    // ensure transport won't stay open
    this.transport.close();

    // ignore further transport communication
    this.transport.removeAllListeners();

    // set ready state
    this.readyState = 'closed';

    // clear session id
    this.id = null;

    // emit close event
    this.emit('close', reason, desc);

    // clean buffers after, so users can still
    // grab the buffers on `close` event
    self.writeBuffer = [];
    self.prevBufferLen = 0;
  }
};

/**
 * Filters upgrades, returning only those matching client transports.
 *
 * @param {Array} server upgrades
 * @api private
 *
 */

Socket.prototype.filterUpgrades = function (upgrades) {
  var filteredUpgrades = [];
  for (var i = 0, j = upgrades.length; i < j; i++) {
    if (~index(this.transports, upgrades[i])) filteredUpgrades.push(upgrades[i]);
  }
  return filteredUpgrades;
};

}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./transport":32,"./transports/index":33,"component-emitter":25,"debug":39,"engine.io-parser":42,"indexof":47,"parsejson":65,"parseqs":66,"parseuri":67}],32:[function(_dereq_,module,exports){
/**
 * Module dependencies.
 */

var parser = _dereq_('engine.io-parser');
var Emitter = _dereq_('component-emitter');

/**
 * Module exports.
 */

module.exports = Transport;

/**
 * Transport abstract constructor.
 *
 * @param {Object} options.
 * @api private
 */

function Transport (opts) {
  this.path = opts.path;
  this.hostname = opts.hostname;
  this.port = opts.port;
  this.secure = opts.secure;
  this.query = opts.query;
  this.timestampParam = opts.timestampParam;
  this.timestampRequests = opts.timestampRequests;
  this.readyState = '';
  this.agent = opts.agent || false;
  this.socket = opts.socket;
  this.enablesXDR = opts.enablesXDR;

  // SSL options for Node.js client
  this.pfx = opts.pfx;
  this.key = opts.key;
  this.passphrase = opts.passphrase;
  this.cert = opts.cert;
  this.ca = opts.ca;
  this.ciphers = opts.ciphers;
  this.rejectUnauthorized = opts.rejectUnauthorized;

  // other options for Node.js client
  this.extraHeaders = opts.extraHeaders;
}

/**
 * Mix in `Emitter`.
 */

Emitter(Transport.prototype);

/**
 * Emits an error.
 *
 * @param {String} str
 * @return {Transport} for chaining
 * @api public
 */

Transport.prototype.onError = function (msg, desc) {
  var err = new Error(msg);
  err.type = 'TransportError';
  err.description = desc;
  this.emit('error', err);
  return this;
};

/**
 * Opens the transport.
 *
 * @api public
 */

Transport.prototype.open = function () {
  if ('closed' === this.readyState || '' === this.readyState) {
    this.readyState = 'opening';
    this.doOpen();
  }

  return this;
};

/**
 * Closes the transport.
 *
 * @api private
 */

Transport.prototype.close = function () {
  if ('opening' === this.readyState || 'open' === this.readyState) {
    this.doClose();
    this.onClose();
  }

  return this;
};

/**
 * Sends multiple packets.
 *
 * @param {Array} packets
 * @api private
 */

Transport.prototype.send = function (packets) {
  if ('open' === this.readyState) {
    this.write(packets);
  } else {
    throw new Error('Transport not open');
  }
};

/**
 * Called upon open
 *
 * @api private
 */

Transport.prototype.onOpen = function () {
  this.readyState = 'open';
  this.writable = true;
  this.emit('open');
};

/**
 * Called with data.
 *
 * @param {String} data
 * @api private
 */

Transport.prototype.onData = function (data) {
  var packet = parser.decodePacket(data, this.socket.binaryType);
  this.onPacket(packet);
};

/**
 * Called with a decoded packet.
 */

Transport.prototype.onPacket = function (packet) {
  this.emit('packet', packet);
};

/**
 * Called upon close.
 *
 * @api private
 */

Transport.prototype.onClose = function () {
  this.readyState = 'closed';
  this.emit('close');
};

},{"component-emitter":25,"engine.io-parser":42}],33:[function(_dereq_,module,exports){
(function (global){
/**
 * Module dependencies
 */

var XMLHttpRequest = _dereq_('xmlhttprequest-ssl');
var XHR = _dereq_('./polling-xhr');
var JSONP = _dereq_('./polling-jsonp');
var websocket = _dereq_('./websocket');

/**
 * Export transports.
 */

exports.polling = polling;
exports.websocket = websocket;

/**
 * Polling transport polymorphic constructor.
 * Decides on xhr vs jsonp based on feature detection.
 *
 * @api private
 */

function polling (opts) {
  var xhr;
  var xd = false;
  var xs = false;
  var jsonp = false !== opts.jsonp;

  if (global.location) {
    var isSSL = 'https:' === location.protocol;
    var port = location.port;

    // some user agents have empty `location.port`
    if (!port) {
      port = isSSL ? 443 : 80;
    }

    xd = opts.hostname !== location.hostname || port !== opts.port;
    xs = opts.secure !== isSSL;
  }

  opts.xdomain = xd;
  opts.xscheme = xs;
  xhr = new XMLHttpRequest(opts);

  if ('open' in xhr && !opts.forceJSONP) {
    return new XHR(opts);
  } else {
    if (!jsonp) throw new Error('JSONP disabled');
    return new JSONP(opts);
  }
}

}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./polling-jsonp":34,"./polling-xhr":35,"./websocket":37,"xmlhttprequest-ssl":38}],34:[function(_dereq_,module,exports){
(function (global){

/**
 * Module requirements.
 */

var Polling = _dereq_('./polling');
var inherit = _dereq_('component-inherit');

/**
 * Module exports.
 */

module.exports = JSONPPolling;

/**
 * Cached regular expressions.
 */

var rNewline = /\n/g;
var rEscapedNewline = /\\n/g;

/**
 * Global JSONP callbacks.
 */

var callbacks;

/**
 * Noop.
 */

function empty () { }

/**
 * JSONP Polling constructor.
 *
 * @param {Object} opts.
 * @api public
 */

function JSONPPolling (opts) {
  Polling.call(this, opts);

  this.query = this.query || {};

  // define global callbacks array if not present
  // we do this here (lazily) to avoid unneeded global pollution
  if (!callbacks) {
    // we need to consider multiple engines in the same page
    if (!global.___eio) global.___eio = [];
    callbacks = global.___eio;
  }

  // callback identifier
  this.index = callbacks.length;

  // add callback to jsonp global
  var self = this;
  callbacks.push(function (msg) {
    self.onData(msg);
  });

  // append to query string
  this.query.j = this.index;

  // prevent spurious errors from being emitted when the window is unloaded
  if (global.document && global.addEventListener) {
    global.addEventListener('beforeunload', function () {
      if (self.script) self.script.onerror = empty;
    }, false);
  }
}

/**
 * Inherits from Polling.
 */

inherit(JSONPPolling, Polling);

/*
 * JSONP only supports binary as base64 encoded strings
 */

JSONPPolling.prototype.supportsBinary = false;

/**
 * Closes the socket.
 *
 * @api private
 */

JSONPPolling.prototype.doClose = function () {
  if (this.script) {
    this.script.parentNode.removeChild(this.script);
    this.script = null;
  }

  if (this.form) {
    this.form.parentNode.removeChild(this.form);
    this.form = null;
    this.iframe = null;
  }

  Polling.prototype.doClose.call(this);
};

/**
 * Starts a poll cycle.
 *
 * @api private
 */

JSONPPolling.prototype.doPoll = function () {
  var self = this;
  var script = document.createElement('script');

  if (this.script) {
    this.script.parentNode.removeChild(this.script);
    this.script = null;
  }

  script.async = true;
  script.src = this.uri();
  script.onerror = function (e) {
    self.onError('jsonp poll error', e);
  };

  var insertAt = document.getElementsByTagName('script')[0];
  if (insertAt) {
    insertAt.parentNode.insertBefore(script, insertAt);
  } else {
    (document.head || document.body).appendChild(script);
  }
  this.script = script;

  var isUAgecko = 'undefined' !== typeof navigator && /gecko/i.test(navigator.userAgent);

  if (isUAgecko) {
    setTimeout(function () {
      var iframe = document.createElement('iframe');
      document.body.appendChild(iframe);
      document.body.removeChild(iframe);
    }, 100);
  }
};

/**
 * Writes with a hidden iframe.
 *
 * @param {String} data to send
 * @param {Function} called upon flush.
 * @api private
 */

JSONPPolling.prototype.doWrite = function (data, fn) {
  var self = this;

  if (!this.form) {
    var form = document.createElement('form');
    var area = document.createElement('textarea');
    var id = this.iframeId = 'eio_iframe_' + this.index;
    var iframe;

    form.className = 'socketio';
    form.style.position = 'absolute';
    form.style.top = '-1000px';
    form.style.left = '-1000px';
    form.target = id;
    form.method = 'POST';
    form.setAttribute('accept-charset', 'utf-8');
    area.name = 'd';
    form.appendChild(area);
    document.body.appendChild(form);

    this.form = form;
    this.area = area;
  }

  this.form.action = this.uri();

  function complete () {
    initIframe();
    fn();
  }

  function initIframe () {
    if (self.iframe) {
      try {
        self.form.removeChild(self.iframe);
      } catch (e) {
        self.onError('jsonp polling iframe removal error', e);
      }
    }

    try {
      // ie6 dynamic iframes with target="" support (thanks Chris Lambacher)
      var html = '<iframe src="javascript:0" name="' + self.iframeId + '">';
      iframe = document.createElement(html);
    } catch (e) {
      iframe = document.createElement('iframe');
      iframe.name = self.iframeId;
      iframe.src = 'javascript:0';
    }

    iframe.id = self.iframeId;

    self.form.appendChild(iframe);
    self.iframe = iframe;
  }

  initIframe();

  // escape \n to prevent it from being converted into \r\n by some UAs
  // double escaping is required for escaped new lines because unescaping of new lines can be done safely on server-side
  data = data.replace(rEscapedNewline, '\\\n');
  this.area.value = data.replace(rNewline, '\\n');

  try {
    this.form.submit();
  } catch (e) {}

  if (this.iframe.attachEvent) {
    this.iframe.onreadystatechange = function () {
      if (self.iframe.readyState === 'complete') {
        complete();
      }
    };
  } else {
    this.iframe.onload = complete;
  }
};

}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./polling":36,"component-inherit":26}],35:[function(_dereq_,module,exports){
(function (global){
/**
 * Module requirements.
 */

var XMLHttpRequest = _dereq_('xmlhttprequest-ssl');
var Polling = _dereq_('./polling');
var Emitter = _dereq_('component-emitter');
var inherit = _dereq_('component-inherit');
var debug = _dereq_('debug')('engine.io-client:polling-xhr');

/**
 * Module exports.
 */

module.exports = XHR;
module.exports.Request = Request;

/**
 * Empty function
 */

function empty () {}

/**
 * XHR Polling constructor.
 *
 * @param {Object} opts
 * @api public
 */

function XHR (opts) {
  Polling.call(this, opts);

  if (global.location) {
    var isSSL = 'https:' === location.protocol;
    var port = location.port;

    // some user agents have empty `location.port`
    if (!port) {
      port = isSSL ? 443 : 80;
    }

    this.xd = opts.hostname !== global.location.hostname ||
      port !== opts.port;
    this.xs = opts.secure !== isSSL;
  } else {
    this.extraHeaders = opts.extraHeaders;
  }
}

/**
 * Inherits from Polling.
 */

inherit(XHR, Polling);

/**
 * XHR supports binary
 */

XHR.prototype.supportsBinary = true;

/**
 * Creates a request.
 *
 * @param {String} method
 * @api private
 */

XHR.prototype.request = function (opts) {
  opts = opts || {};
  opts.uri = this.uri();
  opts.xd = this.xd;
  opts.xs = this.xs;
  opts.agent = this.agent || false;
  opts.supportsBinary = this.supportsBinary;
  opts.enablesXDR = this.enablesXDR;

  // SSL options for Node.js client
  opts.pfx = this.pfx;
  opts.key = this.key;
  opts.passphrase = this.passphrase;
  opts.cert = this.cert;
  opts.ca = this.ca;
  opts.ciphers = this.ciphers;
  opts.rejectUnauthorized = this.rejectUnauthorized;

  // other options for Node.js client
  opts.extraHeaders = this.extraHeaders;

  return new Request(opts);
};

/**
 * Sends data.
 *
 * @param {String} data to send.
 * @param {Function} called upon flush.
 * @api private
 */

XHR.prototype.doWrite = function (data, fn) {
  var isBinary = typeof data !== 'string' && data !== undefined;
  var req = this.request({ method: 'POST', data: data, isBinary: isBinary });
  var self = this;
  req.on('success', fn);
  req.on('error', function (err) {
    self.onError('xhr post error', err);
  });
  this.sendXhr = req;
};

/**
 * Starts a poll cycle.
 *
 * @api private
 */

XHR.prototype.doPoll = function () {
  debug('xhr poll');
  var req = this.request();
  var self = this;
  req.on('data', function (data) {
    self.onData(data);
  });
  req.on('error', function (err) {
    self.onError('xhr poll error', err);
  });
  this.pollXhr = req;
};

/**
 * Request constructor
 *
 * @param {Object} options
 * @api public
 */

function Request (opts) {
  this.method = opts.method || 'GET';
  this.uri = opts.uri;
  this.xd = !!opts.xd;
  this.xs = !!opts.xs;
  this.async = false !== opts.async;
  this.data = undefined !== opts.data ? opts.data : null;
  this.agent = opts.agent;
  this.isBinary = opts.isBinary;
  this.supportsBinary = opts.supportsBinary;
  this.enablesXDR = opts.enablesXDR;

  // SSL options for Node.js client
  this.pfx = opts.pfx;
  this.key = opts.key;
  this.passphrase = opts.passphrase;
  this.cert = opts.cert;
  this.ca = opts.ca;
  this.ciphers = opts.ciphers;
  this.rejectUnauthorized = opts.rejectUnauthorized;

  // other options for Node.js client
  this.extraHeaders = opts.extraHeaders;

  this.create();
}

/**
 * Mix in `Emitter`.
 */

Emitter(Request.prototype);

/**
 * Creates the XHR object and sends the request.
 *
 * @api private
 */

Request.prototype.create = function () {
  var opts = { agent: this.agent, xdomain: this.xd, xscheme: this.xs, enablesXDR: this.enablesXDR };

  // SSL options for Node.js client
  opts.pfx = this.pfx;
  opts.key = this.key;
  opts.passphrase = this.passphrase;
  opts.cert = this.cert;
  opts.ca = this.ca;
  opts.ciphers = this.ciphers;
  opts.rejectUnauthorized = this.rejectUnauthorized;

  var xhr = this.xhr = new XMLHttpRequest(opts);
  var self = this;

  try {
    debug('xhr open %s: %s', this.method, this.uri);
    xhr.open(this.method, this.uri, this.async);
    try {
      if (this.extraHeaders) {
        xhr.setDisableHeaderCheck(true);
        for (var i in this.extraHeaders) {
          if (this.extraHeaders.hasOwnProperty(i)) {
            xhr.setRequestHeader(i, this.extraHeaders[i]);
          }
        }
      }
    } catch (e) {}
    if (this.supportsBinary) {
      // This has to be done after open because Firefox is stupid
      // http://stackoverflow.com/questions/13216903/get-binary-data-with-xmlhttprequest-in-a-firefox-extension
      xhr.responseType = 'arraybuffer';
    }

    if ('POST' === this.method) {
      try {
        if (this.isBinary) {
          xhr.setRequestHeader('Content-type', 'application/octet-stream');
        } else {
          xhr.setRequestHeader('Content-type', 'text/plain;charset=UTF-8');
        }
      } catch (e) {}
    }

    try {
      xhr.setRequestHeader('Accept', '*/*');
    } catch (e) {}

    // ie6 check
    if ('withCredentials' in xhr) {
      xhr.withCredentials = true;
    }

    if (this.hasXDR()) {
      xhr.onload = function () {
        self.onLoad();
      };
      xhr.onerror = function () {
        self.onError(xhr.responseText);
      };
    } else {
      xhr.onreadystatechange = function () {
        if (4 !== xhr.readyState) return;
        if (200 === xhr.status || 1223 === xhr.status) {
          self.onLoad();
        } else {
          // make sure the `error` event handler that's user-set
          // does not throw in the same tick and gets caught here
          setTimeout(function () {
            self.onError(xhr.status);
          }, 0);
        }
      };
    }

    debug('xhr data %s', this.data);
    xhr.send(this.data);
  } catch (e) {
    // Need to defer since .create() is called directly fhrom the constructor
    // and thus the 'error' event can only be only bound *after* this exception
    // occurs.  Therefore, also, we cannot throw here at all.
    setTimeout(function () {
      self.onError(e);
    }, 0);
    return;
  }

  if (global.document) {
    this.index = Request.requestsCount++;
    Request.requests[this.index] = this;
  }
};

/**
 * Called upon successful response.
 *
 * @api private
 */

Request.prototype.onSuccess = function () {
  this.emit('success');
  this.cleanup();
};

/**
 * Called if we have data.
 *
 * @api private
 */

Request.prototype.onData = function (data) {
  this.emit('data', data);
  this.onSuccess();
};

/**
 * Called upon error.
 *
 * @api private
 */

Request.prototype.onError = function (err) {
  this.emit('error', err);
  this.cleanup(true);
};

/**
 * Cleans up house.
 *
 * @api private
 */

Request.prototype.cleanup = function (fromError) {
  if ('undefined' === typeof this.xhr || null === this.xhr) {
    return;
  }
  // xmlhttprequest
  if (this.hasXDR()) {
    this.xhr.onload = this.xhr.onerror = empty;
  } else {
    this.xhr.onreadystatechange = empty;
  }

  if (fromError) {
    try {
      this.xhr.abort();
    } catch (e) {}
  }

  if (global.document) {
    delete Request.requests[this.index];
  }

  this.xhr = null;
};

/**
 * Called upon load.
 *
 * @api private
 */

Request.prototype.onLoad = function () {
  var data;
  try {
    var contentType;
    try {
      contentType = this.xhr.getResponseHeader('Content-Type').split(';')[0];
    } catch (e) {}
    if (contentType === 'application/octet-stream') {
      data = this.xhr.response || this.xhr.responseText;
    } else {
      if (!this.supportsBinary) {
        data = this.xhr.responseText;
      } else {
        try {
          data = String.fromCharCode.apply(null, new Uint8Array(this.xhr.response));
        } catch (e) {
          var ui8Arr = new Uint8Array(this.xhr.response);
          var dataArray = [];
          for (var idx = 0, length = ui8Arr.length; idx < length; idx++) {
            dataArray.push(ui8Arr[idx]);
          }

          data = String.fromCharCode.apply(null, dataArray);
        }
      }
    }
  } catch (e) {
    this.onError(e);
  }
  if (null != data) {
    this.onData(data);
  }
};

/**
 * Check if it has XDomainRequest.
 *
 * @api private
 */

Request.prototype.hasXDR = function () {
  return 'undefined' !== typeof global.XDomainRequest && !this.xs && this.enablesXDR;
};

/**
 * Aborts the request.
 *
 * @api public
 */

Request.prototype.abort = function () {
  this.cleanup();
};

/**
 * Aborts pending requests when unloading the window. This is needed to prevent
 * memory leaks (e.g. when using IE) and to ensure that no spurious error is
 * emitted.
 */

Request.requestsCount = 0;
Request.requests = {};

if (global.document) {
  if (global.attachEvent) {
    global.attachEvent('onunload', unloadHandler);
  } else if (global.addEventListener) {
    global.addEventListener('beforeunload', unloadHandler, false);
  }
}

function unloadHandler () {
  for (var i in Request.requests) {
    if (Request.requests.hasOwnProperty(i)) {
      Request.requests[i].abort();
    }
  }
}

}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./polling":36,"component-emitter":25,"component-inherit":26,"debug":39,"xmlhttprequest-ssl":38}],36:[function(_dereq_,module,exports){
/**
 * Module dependencies.
 */

var Transport = _dereq_('../transport');
var parseqs = _dereq_('parseqs');
var parser = _dereq_('engine.io-parser');
var inherit = _dereq_('component-inherit');
var yeast = _dereq_('yeast');
var debug = _dereq_('debug')('engine.io-client:polling');

/**
 * Module exports.
 */

module.exports = Polling;

/**
 * Is XHR2 supported?
 */

var hasXHR2 = (function () {
  var XMLHttpRequest = _dereq_('xmlhttprequest-ssl');
  var xhr = new XMLHttpRequest({ xdomain: false });
  return null != xhr.responseType;
})();

/**
 * Polling interface.
 *
 * @param {Object} opts
 * @api private
 */

function Polling (opts) {
  var forceBase64 = (opts && opts.forceBase64);
  if (!hasXHR2 || forceBase64) {
    this.supportsBinary = false;
  }
  Transport.call(this, opts);
}

/**
 * Inherits from Transport.
 */

inherit(Polling, Transport);

/**
 * Transport name.
 */

Polling.prototype.name = 'polling';

/**
 * Opens the socket (triggers polling). We write a PING message to determine
 * when the transport is open.
 *
 * @api private
 */

Polling.prototype.doOpen = function () {
  this.poll();
};

/**
 * Pauses polling.
 *
 * @param {Function} callback upon buffers are flushed and transport is paused
 * @api private
 */

Polling.prototype.pause = function (onPause) {
  var self = this;

  this.readyState = 'pausing';

  function pause () {
    debug('paused');
    self.readyState = 'paused';
    onPause();
  }

  if (this.polling || !this.writable) {
    var total = 0;

    if (this.polling) {
      debug('we are currently polling - waiting to pause');
      total++;
      this.once('pollComplete', function () {
        debug('pre-pause polling complete');
        --total || pause();
      });
    }

    if (!this.writable) {
      debug('we are currently writing - waiting to pause');
      total++;
      this.once('drain', function () {
        debug('pre-pause writing complete');
        --total || pause();
      });
    }
  } else {
    pause();
  }
};

/**
 * Starts polling cycle.
 *
 * @api public
 */

Polling.prototype.poll = function () {
  debug('polling');
  this.polling = true;
  this.doPoll();
  this.emit('poll');
};

/**
 * Overloads onData to detect payloads.
 *
 * @api private
 */

Polling.prototype.onData = function (data) {
  var self = this;
  debug('polling got data %s', data);
  var callback = function (packet, index, total) {
    // if its the first message we consider the transport open
    if ('opening' === self.readyState) {
      self.onOpen();
    }

    // if its a close packet, we close the ongoing requests
    if ('close' === packet.type) {
      self.onClose();
      return false;
    }

    // otherwise bypass onData and handle the message
    self.onPacket(packet);
  };

  // decode payload
  parser.decodePayload(data, this.socket.binaryType, callback);

  // if an event did not trigger closing
  if ('closed' !== this.readyState) {
    // if we got data we're not polling
    this.polling = false;
    this.emit('pollComplete');

    if ('open' === this.readyState) {
      this.poll();
    } else {
      debug('ignoring poll - transport state "%s"', this.readyState);
    }
  }
};

/**
 * For polling, send a close packet.
 *
 * @api private
 */

Polling.prototype.doClose = function () {
  var self = this;

  function close () {
    debug('writing close packet');
    self.write([{ type: 'close' }]);
  }

  if ('open' === this.readyState) {
    debug('transport open - closing');
    close();
  } else {
    // in case we're trying to close while
    // handshaking is in progress (GH-164)
    debug('transport not open - deferring close');
    this.once('open', close);
  }
};

/**
 * Writes a packets payload.
 *
 * @param {Array} data packets
 * @param {Function} drain callback
 * @api private
 */

Polling.prototype.write = function (packets) {
  var self = this;
  this.writable = false;
  var callbackfn = function () {
    self.writable = true;
    self.emit('drain');
  };

  parser.encodePayload(packets, this.supportsBinary, function (data) {
    self.doWrite(data, callbackfn);
  });
};

/**
 * Generates uri for connection.
 *
 * @api private
 */

Polling.prototype.uri = function () {
  var query = this.query || {};
  var schema = this.secure ? 'https' : 'http';
  var port = '';

  // cache busting is forced
  if (false !== this.timestampRequests) {
    query[this.timestampParam] = yeast();
  }

  if (!this.supportsBinary && !query.sid) {
    query.b64 = 1;
  }

  query = parseqs.encode(query);

  // avoid port if default for schema
  if (this.port && (('https' === schema && this.port !== 443) ||
     ('http' === schema && this.port !== 80))) {
    port = ':' + this.port;
  }

  // prepend ? to query
  if (query.length) {
    query = '?' + query;
  }

  var ipv6 = this.hostname.indexOf(':') !== -1;
  return schema + '://' + (ipv6 ? '[' + this.hostname + ']' : this.hostname) + port + this.path + query;
};

},{"../transport":32,"component-inherit":26,"debug":39,"engine.io-parser":42,"parseqs":66,"xmlhttprequest-ssl":38,"yeast":73}],37:[function(_dereq_,module,exports){
(function (global){
/**
 * Module dependencies.
 */

var Transport = _dereq_('../transport');
var parser = _dereq_('engine.io-parser');
var parseqs = _dereq_('parseqs');
var inherit = _dereq_('component-inherit');
var yeast = _dereq_('yeast');
var debug = _dereq_('debug')('engine.io-client:websocket');
var BrowserWebSocket = global.WebSocket || global.MozWebSocket;

/**
 * Get either the `WebSocket` or `MozWebSocket` globals
 * in the browser or try to resolve WebSocket-compatible
 * interface exposed by `ws` for Node-like environment.
 */

var WebSocket = BrowserWebSocket;
if (!WebSocket && typeof window === 'undefined') {
  try {
    WebSocket = _dereq_('ws');
  } catch (e) { }
}

/**
 * Module exports.
 */

module.exports = WS;

/**
 * WebSocket transport constructor.
 *
 * @api {Object} connection options
 * @api public
 */

function WS (opts) {
  var forceBase64 = (opts && opts.forceBase64);
  if (forceBase64) {
    this.supportsBinary = false;
  }
  this.perMessageDeflate = opts.perMessageDeflate;
  Transport.call(this, opts);
}

/**
 * Inherits from Transport.
 */

inherit(WS, Transport);

/**
 * Transport name.
 *
 * @api public
 */

WS.prototype.name = 'websocket';

/*
 * WebSockets support binary
 */

WS.prototype.supportsBinary = true;

/**
 * Opens socket.
 *
 * @api private
 */

WS.prototype.doOpen = function () {
  if (!this.check()) {
    // let probe timeout
    return;
  }

  var uri = this.uri();
  var protocols = void (0);
  var opts = {
    agent: this.agent,
    perMessageDeflate: this.perMessageDeflate
  };

  // SSL options for Node.js client
  opts.pfx = this.pfx;
  opts.key = this.key;
  opts.passphrase = this.passphrase;
  opts.cert = this.cert;
  opts.ca = this.ca;
  opts.ciphers = this.ciphers;
  opts.rejectUnauthorized = this.rejectUnauthorized;
  if (this.extraHeaders) {
    opts.headers = this.extraHeaders;
  }

  try {
    this.ws = BrowserWebSocket ? new WebSocket(uri) : new WebSocket(uri, protocols, opts);
  } catch (err) {
    return this.emit('error', err);
  }

  if (this.ws.binaryType === undefined) {
    this.supportsBinary = false;
  }

  if (this.ws.supports && this.ws.supports.binary) {
    this.supportsBinary = true;
    this.ws.binaryType = 'nodebuffer';
  } else {
    this.ws.binaryType = 'arraybuffer';
  }

  this.addEventListeners();
};

/**
 * Adds event listeners to the socket
 *
 * @api private
 */

WS.prototype.addEventListeners = function () {
  var self = this;

  this.ws.onopen = function () {
    self.onOpen();
  };
  this.ws.onclose = function () {
    self.onClose();
  };
  this.ws.onmessage = function (ev) {
    self.onData(ev.data);
  };
  this.ws.onerror = function (e) {
    self.onError('websocket error', e);
  };
};

/**
 * Writes data to socket.
 *
 * @param {Array} array of packets.
 * @api private
 */

WS.prototype.write = function (packets) {
  var self = this;
  this.writable = false;

  // encodePacket efficient as it uses WS framing
  // no need for encodePayload
  var total = packets.length;
  for (var i = 0, l = total; i < l; i++) {
    (function (packet) {
      parser.encodePacket(packet, self.supportsBinary, function (data) {
        if (!BrowserWebSocket) {
          // always create a new object (GH-437)
          var opts = {};
          if (packet.options) {
            opts.compress = packet.options.compress;
          }

          if (self.perMessageDeflate) {
            var len = 'string' === typeof data ? global.Buffer.byteLength(data) : data.length;
            if (len < self.perMessageDeflate.threshold) {
              opts.compress = false;
            }
          }
        }

        // Sometimes the websocket has already been closed but the browser didn't
        // have a chance of informing us about it yet, in that case send will
        // throw an error
        try {
          if (BrowserWebSocket) {
            // TypeError is thrown when passing the second argument on Safari
            self.ws.send(data);
          } else {
            self.ws.send(data, opts);
          }
        } catch (e) {
          debug('websocket closed before onclose event');
        }

        --total || done();
      });
    })(packets[i]);
  }

  function done () {
    self.emit('flush');

    // fake drain
    // defer to next tick to allow Socket to clear writeBuffer
    setTimeout(function () {
      self.writable = true;
      self.emit('drain');
    }, 0);
  }
};

/**
 * Called upon close
 *
 * @api private
 */

WS.prototype.onClose = function () {
  Transport.prototype.onClose.call(this);
};

/**
 * Closes socket.
 *
 * @api private
 */

WS.prototype.doClose = function () {
  if (typeof this.ws !== 'undefined') {
    this.ws.close();
  }
};

/**
 * Generates uri for connection.
 *
 * @api private
 */

WS.prototype.uri = function () {
  var query = this.query || {};
  var schema = this.secure ? 'wss' : 'ws';
  var port = '';

  // avoid port if default for schema
  if (this.port && (('wss' === schema && this.port !== 443) ||
    ('ws' === schema && this.port !== 80))) {
    port = ':' + this.port;
  }

  // append timestamp to URI
  if (this.timestampRequests) {
    query[this.timestampParam] = yeast();
  }

  // communicate binary support capabilities
  if (!this.supportsBinary) {
    query.b64 = 1;
  }

  query = parseqs.encode(query);

  // prepend ? to query
  if (query.length) {
    query = '?' + query;
  }

  var ipv6 = this.hostname.indexOf(':') !== -1;
  return schema + '://' + (ipv6 ? '[' + this.hostname + ']' : this.hostname) + port + this.path + query;
};

/**
 * Feature detection for WebSocket.
 *
 * @return {Boolean} whether this transport is available.
 * @api public
 */

WS.prototype.check = function () {
  return !!WebSocket && !('__initialize' in WebSocket && this.name === WS.prototype.name);
};

}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"../transport":32,"component-inherit":26,"debug":39,"engine.io-parser":42,"parseqs":66,"ws":24,"yeast":73}],38:[function(_dereq_,module,exports){
(function (global){
// browser shim for xmlhttprequest module

var hasCORS = _dereq_('has-cors');

module.exports = function (opts) {
  var xdomain = opts.xdomain;

  // scheme must be same when usign XDomainRequest
  // http://blogs.msdn.com/b/ieinternals/archive/2010/05/13/xdomainrequest-restrictions-limitations-and-workarounds.aspx
  var xscheme = opts.xscheme;

  // XDomainRequest has a flow of not sending cookie, therefore it should be disabled as a default.
  // https://github.com/Automattic/engine.io-client/pull/217
  var enablesXDR = opts.enablesXDR;

  // XMLHttpRequest can be disabled on IE
  try {
    if ('undefined' !== typeof XMLHttpRequest && (!xdomain || hasCORS)) {
      return new XMLHttpRequest();
    }
  } catch (e) { }

  // Use XDomainRequest for IE8 if enablesXDR is true
  // because loading bar keeps flashing when using jsonp-polling
  // https://github.com/yujiosaka/socke.io-ie8-loading-example
  try {
    if ('undefined' !== typeof XDomainRequest && !xscheme && enablesXDR) {
      return new XDomainRequest();
    }
  } catch (e) { }

  if (!xdomain) {
    try {
      return new global[['Active'].concat('Object').join('X')]('Microsoft.XMLHTTP');
    } catch (e) { }
  }
};

}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"has-cors":45}],39:[function(_dereq_,module,exports){

/**
 * This is the web browser implementation of `debug()`.
 *
 * Expose `debug()` as the module.
 */

exports = module.exports = _dereq_('./debug');
exports.log = log;
exports.formatArgs = formatArgs;
exports.save = save;
exports.load = load;
exports.useColors = useColors;
exports.storage = 'undefined' != typeof chrome
               && 'undefined' != typeof chrome.storage
                  ? chrome.storage.local
                  : localstorage();

/**
 * Colors.
 */

exports.colors = [
  'lightseagreen',
  'forestgreen',
  'goldenrod',
  'dodgerblue',
  'darkorchid',
  'crimson'
];

/**
 * Currently only WebKit-based Web Inspectors, Firefox >= v31,
 * and the Firebug extension (any Firefox version) are known
 * to support "%c" CSS customizations.
 *
 * TODO: add a `localStorage` variable to explicitly enable/disable colors
 */

function useColors() {
  // is webkit? http://stackoverflow.com/a/16459606/376773
  return ('WebkitAppearance' in document.documentElement.style) ||
    // is firebug? http://stackoverflow.com/a/398120/376773
    (window.console && (console.firebug || (console.exception && console.table))) ||
    // is firefox >= v31?
    // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
    (navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31);
}

/**
 * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
 */

exports.formatters.j = function(v) {
  return JSON.stringify(v);
};


/**
 * Colorize log arguments if enabled.
 *
 * @api public
 */

function formatArgs() {
  var args = arguments;
  var useColors = this.useColors;

  args[0] = (useColors ? '%c' : '')
    + this.namespace
    + (useColors ? ' %c' : ' ')
    + args[0]
    + (useColors ? '%c ' : ' ')
    + '+' + exports.humanize(this.diff);

  if (!useColors) return args;

  var c = 'color: ' + this.color;
  args = [args[0], c, 'color: inherit'].concat(Array.prototype.slice.call(args, 1));

  // the final "%c" is somewhat tricky, because there could be other
  // arguments passed either before or after the %c, so we need to
  // figure out the correct index to insert the CSS into
  var index = 0;
  var lastC = 0;
  args[0].replace(/%[a-z%]/g, function(match) {
    if ('%%' === match) return;
    index++;
    if ('%c' === match) {
      // we only are interested in the *last* %c
      // (the user may have provided their own)
      lastC = index;
    }
  });

  args.splice(lastC, 0, c);
  return args;
}

/**
 * Invokes `console.log()` when available.
 * No-op when `console.log` is not a "function".
 *
 * @api public
 */

function log() {
  // this hackery is required for IE8/9, where
  // the `console.log` function doesn't have 'apply'
  return 'object' === typeof console
    && console.log
    && Function.prototype.apply.call(console.log, console, arguments);
}

/**
 * Save `namespaces`.
 *
 * @param {String} namespaces
 * @api private
 */

function save(namespaces) {
  try {
    if (null == namespaces) {
      exports.storage.removeItem('debug');
    } else {
      exports.storage.debug = namespaces;
    }
  } catch(e) {}
}

/**
 * Load `namespaces`.
 *
 * @return {String} returns the previously persisted debug modes
 * @api private
 */

function load() {
  var r;
  try {
    r = exports.storage.debug;
  } catch(e) {}
  return r;
}

/**
 * Enable namespaces listed in `localStorage.debug` initially.
 */

exports.enable(load());

/**
 * Localstorage attempts to return the localstorage.
 *
 * This is necessary because safari throws
 * when a user disables cookies/localstorage
 * and you attempt to access it.
 *
 * @return {LocalStorage}
 * @api private
 */

function localstorage(){
  try {
    return window.localStorage;
  } catch (e) {}
}

},{"./debug":40}],40:[function(_dereq_,module,exports){

/**
 * This is the common logic for both the Node.js and web browser
 * implementations of `debug()`.
 *
 * Expose `debug()` as the module.
 */

exports = module.exports = debug;
exports.coerce = coerce;
exports.disable = disable;
exports.enable = enable;
exports.enabled = enabled;
exports.humanize = _dereq_('ms');

/**
 * The currently active debug mode names, and names to skip.
 */

exports.names = [];
exports.skips = [];

/**
 * Map of special "%n" handling functions, for the debug "format" argument.
 *
 * Valid key names are a single, lowercased letter, i.e. "n".
 */

exports.formatters = {};

/**
 * Previously assigned color.
 */

var prevColor = 0;

/**
 * Previous log timestamp.
 */

var prevTime;

/**
 * Select a color.
 *
 * @return {Number}
 * @api private
 */

function selectColor() {
  return exports.colors[prevColor++ % exports.colors.length];
}

/**
 * Create a debugger with the given `namespace`.
 *
 * @param {String} namespace
 * @return {Function}
 * @api public
 */

function debug(namespace) {

  // define the `disabled` version
  function disabled() {
  }
  disabled.enabled = false;

  // define the `enabled` version
  function enabled() {

    var self = enabled;

    // set `diff` timestamp
    var curr = +new Date();
    var ms = curr - (prevTime || curr);
    self.diff = ms;
    self.prev = prevTime;
    self.curr = curr;
    prevTime = curr;

    // add the `color` if not set
    if (null == self.useColors) self.useColors = exports.useColors();
    if (null == self.color && self.useColors) self.color = selectColor();

    var args = Array.prototype.slice.call(arguments);

    args[0] = exports.coerce(args[0]);

    if ('string' !== typeof args[0]) {
      // anything else let's inspect with %o
      args = ['%o'].concat(args);
    }

    // apply any `formatters` transformations
    var index = 0;
    args[0] = args[0].replace(/%([a-z%])/g, function(match, format) {
      // if we encounter an escaped % then don't increase the array index
      if (match === '%%') return match;
      index++;
      var formatter = exports.formatters[format];
      if ('function' === typeof formatter) {
        var val = args[index];
        match = formatter.call(self, val);

        // now we need to remove `args[index]` since it's inlined in the `format`
        args.splice(index, 1);
        index--;
      }
      return match;
    });

    if ('function' === typeof exports.formatArgs) {
      args = exports.formatArgs.apply(self, args);
    }
    var logFn = enabled.log || exports.log || console.log.bind(console);
    logFn.apply(self, args);
  }
  enabled.enabled = true;

  var fn = exports.enabled(namespace) ? enabled : disabled;

  fn.namespace = namespace;

  return fn;
}

/**
 * Enables a debug mode by namespaces. This can include modes
 * separated by a colon and wildcards.
 *
 * @param {String} namespaces
 * @api public
 */

function enable(namespaces) {
  exports.save(namespaces);

  var split = (namespaces || '').split(/[\s,]+/);
  var len = split.length;

  for (var i = 0; i < len; i++) {
    if (!split[i]) continue; // ignore empty strings
    namespaces = split[i].replace(/\*/g, '.*?');
    if (namespaces[0] === '-') {
      exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
    } else {
      exports.names.push(new RegExp('^' + namespaces + '$'));
    }
  }
}

/**
 * Disable debug output.
 *
 * @api public
 */

function disable() {
  exports.enable('');
}

/**
 * Returns true if the given mode name is enabled, false otherwise.
 *
 * @param {String} name
 * @return {Boolean}
 * @api public
 */

function enabled(name) {
  var i, len;
  for (i = 0, len = exports.skips.length; i < len; i++) {
    if (exports.skips[i].test(name)) {
      return false;
    }
  }
  for (i = 0, len = exports.names.length; i < len; i++) {
    if (exports.names[i].test(name)) {
      return true;
    }
  }
  return false;
}

/**
 * Coerce `val`.
 *
 * @param {Mixed} val
 * @return {Mixed}
 * @api private
 */

function coerce(val) {
  if (val instanceof Error) return val.stack || val.message;
  return val;
}

},{"ms":41}],41:[function(_dereq_,module,exports){
/**
 * Helpers.
 */

var s = 1000;
var m = s * 60;
var h = m * 60;
var d = h * 24;
var y = d * 365.25;

/**
 * Parse or format the given `val`.
 *
 * Options:
 *
 *  - `long` verbose formatting [false]
 *
 * @param {String|Number} val
 * @param {Object} options
 * @return {String|Number}
 * @api public
 */

module.exports = function(val, options){
  options = options || {};
  if ('string' == typeof val) return parse(val);
  return options["long"]
    ? long(val)
    : short(val);
};

/**
 * Parse the given `str` and return milliseconds.
 *
 * @param {String} str
 * @return {Number}
 * @api private
 */

function parse(str) {
  str = '' + str;
  if (str.length > 10000) return;
  var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(str);
  if (!match) return;
  var n = parseFloat(match[1]);
  var type = (match[2] || 'ms').toLowerCase();
  switch (type) {
    case 'years':
    case 'year':
    case 'yrs':
    case 'yr':
    case 'y':
      return n * y;
    case 'days':
    case 'day':
    case 'd':
      return n * d;
    case 'hours':
    case 'hour':
    case 'hrs':
    case 'hr':
    case 'h':
      return n * h;
    case 'minutes':
    case 'minute':
    case 'mins':
    case 'min':
    case 'm':
      return n * m;
    case 'seconds':
    case 'second':
    case 'secs':
    case 'sec':
    case 's':
      return n * s;
    case 'milliseconds':
    case 'millisecond':
    case 'msecs':
    case 'msec':
    case 'ms':
      return n;
  }
}

/**
 * Short format for `ms`.
 *
 * @param {Number} ms
 * @return {String}
 * @api private
 */

function short(ms) {
  if (ms >= d) return Math.round(ms / d) + 'd';
  if (ms >= h) return Math.round(ms / h) + 'h';
  if (ms >= m) return Math.round(ms / m) + 'm';
  if (ms >= s) return Math.round(ms / s) + 's';
  return ms + 'ms';
}

/**
 * Long format for `ms`.
 *
 * @param {Number} ms
 * @return {String}
 * @api private
 */

function long(ms) {
  return plural(ms, d, 'day')
    || plural(ms, h, 'hour')
    || plural(ms, m, 'minute')
    || plural(ms, s, 'second')
    || ms + ' ms';
}

/**
 * Pluralization helper.
 */

function plural(ms, n, name) {
  if (ms < n) return;
  if (ms < n * 1.5) return Math.floor(ms / n) + ' ' + name;
  return Math.ceil(ms / n) + ' ' + name + 's';
}

},{}],42:[function(_dereq_,module,exports){
(function (global){
/**
 * Module dependencies.
 */

var keys = _dereq_('./keys');
var hasBinary = _dereq_('has-binary');
var sliceBuffer = _dereq_('arraybuffer.slice');
var after = _dereq_('after');
var utf8 = _dereq_('wtf-8');

var base64encoder;
if (global && global.ArrayBuffer) {
  base64encoder = _dereq_('base64-arraybuffer');
}

/**
 * Check if we are running an android browser. That requires us to use
 * ArrayBuffer with polling transports...
 *
 * http://ghinda.net/jpeg-blob-ajax-android/
 */

var isAndroid = typeof navigator !== 'undefined' && /Android/i.test(navigator.userAgent);

/**
 * Check if we are running in PhantomJS.
 * Uploading a Blob with PhantomJS does not work correctly, as reported here:
 * https://github.com/ariya/phantomjs/issues/11395
 * @type boolean
 */
var isPhantomJS = typeof navigator !== 'undefined' && /PhantomJS/i.test(navigator.userAgent);

/**
 * When true, avoids using Blobs to encode payloads.
 * @type boolean
 */
var dontSendBlobs = isAndroid || isPhantomJS;

/**
 * Current protocol version.
 */

exports.protocol = 3;

/**
 * Packet types.
 */

var packets = exports.packets = {
    open:     0    // non-ws
  , close:    1    // non-ws
  , ping:     2
  , pong:     3
  , message:  4
  , upgrade:  5
  , noop:     6
};

var packetslist = keys(packets);

/**
 * Premade error packet.
 */

var err = { type: 'error', data: 'parser error' };

/**
 * Create a blob api even for blob builder when vendor prefixes exist
 */

var Blob = _dereq_('blob');

/**
 * Encodes a packet.
 *
 *     <packet type id> [ <data> ]
 *
 * Example:
 *
 *     5hello world
 *     3
 *     4
 *
 * Binary is encoded in an identical principle
 *
 * @api private
 */

exports.encodePacket = function (packet, supportsBinary, utf8encode, callback) {
  if ('function' == typeof supportsBinary) {
    callback = supportsBinary;
    supportsBinary = false;
  }

  if ('function' == typeof utf8encode) {
    callback = utf8encode;
    utf8encode = null;
  }

  var data = (packet.data === undefined)
    ? undefined
    : packet.data.buffer || packet.data;

  if (global.ArrayBuffer && data instanceof ArrayBuffer) {
    return encodeArrayBuffer(packet, supportsBinary, callback);
  } else if (Blob && data instanceof global.Blob) {
    return encodeBlob(packet, supportsBinary, callback);
  }

  // might be an object with { base64: true, data: dataAsBase64String }
  if (data && data.base64) {
    return encodeBase64Object(packet, callback);
  }

  // Sending data as a utf-8 string
  var encoded = packets[packet.type];

  // data fragment is optional
  if (undefined !== packet.data) {
    encoded += utf8encode ? utf8.encode(String(packet.data)) : String(packet.data);
  }

  return callback('' + encoded);

};

function encodeBase64Object(packet, callback) {
  // packet data is an object { base64: true, data: dataAsBase64String }
  var message = 'b' + exports.packets[packet.type] + packet.data.data;
  return callback(message);
}

/**
 * Encode packet helpers for binary types
 */

function encodeArrayBuffer(packet, supportsBinary, callback) {
  if (!supportsBinary) {
    return exports.encodeBase64Packet(packet, callback);
  }

  var data = packet.data;
  var contentArray = new Uint8Array(data);
  var resultBuffer = new Uint8Array(1 + data.byteLength);

  resultBuffer[0] = packets[packet.type];
  for (var i = 0; i < contentArray.length; i++) {
    resultBuffer[i+1] = contentArray[i];
  }

  return callback(resultBuffer.buffer);
}

function encodeBlobAsArrayBuffer(packet, supportsBinary, callback) {
  if (!supportsBinary) {
    return exports.encodeBase64Packet(packet, callback);
  }

  var fr = new FileReader();
  fr.onload = function() {
    packet.data = fr.result;
    exports.encodePacket(packet, supportsBinary, true, callback);
  };
  return fr.readAsArrayBuffer(packet.data);
}

function encodeBlob(packet, supportsBinary, callback) {
  if (!supportsBinary) {
    return exports.encodeBase64Packet(packet, callback);
  }

  if (dontSendBlobs) {
    return encodeBlobAsArrayBuffer(packet, supportsBinary, callback);
  }

  var length = new Uint8Array(1);
  length[0] = packets[packet.type];
  var blob = new Blob([length.buffer, packet.data]);

  return callback(blob);
}

/**
 * Encodes a packet with binary data in a base64 string
 *
 * @param {Object} packet, has `type` and `data`
 * @return {String} base64 encoded message
 */

exports.encodeBase64Packet = function(packet, callback) {
  var message = 'b' + exports.packets[packet.type];
  if (Blob && packet.data instanceof global.Blob) {
    var fr = new FileReader();
    fr.onload = function() {
      var b64 = fr.result.split(',')[1];
      callback(message + b64);
    };
    return fr.readAsDataURL(packet.data);
  }

  var b64data;
  try {
    b64data = String.fromCharCode.apply(null, new Uint8Array(packet.data));
  } catch (e) {
    // iPhone Safari doesn't let you apply with typed arrays
    var typed = new Uint8Array(packet.data);
    var basic = new Array(typed.length);
    for (var i = 0; i < typed.length; i++) {
      basic[i] = typed[i];
    }
    b64data = String.fromCharCode.apply(null, basic);
  }
  message += global.btoa(b64data);
  return callback(message);
};

/**
 * Decodes a packet. Changes format to Blob if requested.
 *
 * @return {Object} with `type` and `data` (if any)
 * @api private
 */

exports.decodePacket = function (data, binaryType, utf8decode) {
  if (data === undefined) {
    return err;
  }
  // String data
  if (typeof data == 'string') {
    if (data.charAt(0) == 'b') {
      return exports.decodeBase64Packet(data.substr(1), binaryType);
    }

    if (utf8decode) {
      data = tryDecode(data);
      if (data === false) {
        return err;
      }
    }
    var type = data.charAt(0);

    if (Number(type) != type || !packetslist[type]) {
      return err;
    }

    if (data.length > 1) {
      return { type: packetslist[type], data: data.substring(1) };
    } else {
      return { type: packetslist[type] };
    }
  }

  var asArray = new Uint8Array(data);
  var type = asArray[0];
  var rest = sliceBuffer(data, 1);
  if (Blob && binaryType === 'blob') {
    rest = new Blob([rest]);
  }
  return { type: packetslist[type], data: rest };
};

function tryDecode(data) {
  try {
    data = utf8.decode(data);
  } catch (e) {
    return false;
  }
  return data;
}

/**
 * Decodes a packet encoded in a base64 string
 *
 * @param {String} base64 encoded message
 * @return {Object} with `type` and `data` (if any)
 */

exports.decodeBase64Packet = function(msg, binaryType) {
  var type = packetslist[msg.charAt(0)];
  if (!base64encoder) {
    return { type: type, data: { base64: true, data: msg.substr(1) } };
  }

  var data = base64encoder.decode(msg.substr(1));

  if (binaryType === 'blob' && Blob) {
    data = new Blob([data]);
  }

  return { type: type, data: data };
};

/**
 * Encodes multiple messages (payload).
 *
 *     <length>:data
 *
 * Example:
 *
 *     11:hello world2:hi
 *
 * If any contents are binary, they will be encoded as base64 strings. Base64
 * encoded strings are marked with a b before the length specifier
 *
 * @param {Array} packets
 * @api private
 */

exports.encodePayload = function (packets, supportsBinary, callback) {
  if (typeof supportsBinary == 'function') {
    callback = supportsBinary;
    supportsBinary = null;
  }

  var isBinary = hasBinary(packets);

  if (supportsBinary && isBinary) {
    if (Blob && !dontSendBlobs) {
      return exports.encodePayloadAsBlob(packets, callback);
    }

    return exports.encodePayloadAsArrayBuffer(packets, callback);
  }

  if (!packets.length) {
    return callback('0:');
  }

  function setLengthHeader(message) {
    return message.length + ':' + message;
  }

  function encodeOne(packet, doneCallback) {
    exports.encodePacket(packet, !isBinary ? false : supportsBinary, true, function(message) {
      doneCallback(null, setLengthHeader(message));
    });
  }

  map(packets, encodeOne, function(err, results) {
    return callback(results.join(''));
  });
};

/**
 * Async array map using after
 */

function map(ary, each, done) {
  var result = new Array(ary.length);
  var next = after(ary.length, done);

  var eachWithIndex = function(i, el, cb) {
    each(el, function(error, msg) {
      result[i] = msg;
      cb(error, result);
    });
  };

  for (var i = 0; i < ary.length; i++) {
    eachWithIndex(i, ary[i], next);
  }
}

/*
 * Decodes data when a payload is maybe expected. Possible binary contents are
 * decoded from their base64 representation
 *
 * @param {String} data, callback method
 * @api public
 */

exports.decodePayload = function (data, binaryType, callback) {
  if (typeof data != 'string') {
    return exports.decodePayloadAsBinary(data, binaryType, callback);
  }

  if (typeof binaryType === 'function') {
    callback = binaryType;
    binaryType = null;
  }

  var packet;
  if (data == '') {
    // parser error - ignoring payload
    return callback(err, 0, 1);
  }

  var length = ''
    , n, msg;

  for (var i = 0, l = data.length; i < l; i++) {
    var chr = data.charAt(i);

    if (':' != chr) {
      length += chr;
    } else {
      if ('' == length || (length != (n = Number(length)))) {
        // parser error - ignoring payload
        return callback(err, 0, 1);
      }

      msg = data.substr(i + 1, n);

      if (length != msg.length) {
        // parser error - ignoring payload
        return callback(err, 0, 1);
      }

      if (msg.length) {
        packet = exports.decodePacket(msg, binaryType, true);

        if (err.type == packet.type && err.data == packet.data) {
          // parser error in individual packet - ignoring payload
          return callback(err, 0, 1);
        }

        var ret = callback(packet, i + n, l);
        if (false === ret) return;
      }

      // advance cursor
      i += n;
      length = '';
    }
  }

  if (length != '') {
    // parser error - ignoring payload
    return callback(err, 0, 1);
  }

};

/**
 * Encodes multiple messages (payload) as binary.
 *
 * <1 = binary, 0 = string><number from 0-9><number from 0-9>[...]<number
 * 255><data>
 *
 * Example:
 * 1 3 255 1 2 3, if the binary contents are interpreted as 8 bit integers
 *
 * @param {Array} packets
 * @return {ArrayBuffer} encoded payload
 * @api private
 */

exports.encodePayloadAsArrayBuffer = function(packets, callback) {
  if (!packets.length) {
    return callback(new ArrayBuffer(0));
  }

  function encodeOne(packet, doneCallback) {
    exports.encodePacket(packet, true, true, function(data) {
      return doneCallback(null, data);
    });
  }

  map(packets, encodeOne, function(err, encodedPackets) {
    var totalLength = encodedPackets.reduce(function(acc, p) {
      var len;
      if (typeof p === 'string'){
        len = p.length;
      } else {
        len = p.byteLength;
      }
      return acc + len.toString().length + len + 2; // string/binary identifier + separator = 2
    }, 0);

    var resultArray = new Uint8Array(totalLength);

    var bufferIndex = 0;
    encodedPackets.forEach(function(p) {
      var isString = typeof p === 'string';
      var ab = p;
      if (isString) {
        var view = new Uint8Array(p.length);
        for (var i = 0; i < p.length; i++) {
          view[i] = p.charCodeAt(i);
        }
        ab = view.buffer;
      }

      if (isString) { // not true binary
        resultArray[bufferIndex++] = 0;
      } else { // true binary
        resultArray[bufferIndex++] = 1;
      }

      var lenStr = ab.byteLength.toString();
      for (var i = 0; i < lenStr.length; i++) {
        resultArray[bufferIndex++] = parseInt(lenStr[i]);
      }
      resultArray[bufferIndex++] = 255;

      var view = new Uint8Array(ab);
      for (var i = 0; i < view.length; i++) {
        resultArray[bufferIndex++] = view[i];
      }
    });

    return callback(resultArray.buffer);
  });
};

/**
 * Encode as Blob
 */

exports.encodePayloadAsBlob = function(packets, callback) {
  function encodeOne(packet, doneCallback) {
    exports.encodePacket(packet, true, true, function(encoded) {
      var binaryIdentifier = new Uint8Array(1);
      binaryIdentifier[0] = 1;
      if (typeof encoded === 'string') {
        var view = new Uint8Array(encoded.length);
        for (var i = 0; i < encoded.length; i++) {
          view[i] = encoded.charCodeAt(i);
        }
        encoded = view.buffer;
        binaryIdentifier[0] = 0;
      }

      var len = (encoded instanceof ArrayBuffer)
        ? encoded.byteLength
        : encoded.size;

      var lenStr = len.toString();
      var lengthAry = new Uint8Array(lenStr.length + 1);
      for (var i = 0; i < lenStr.length; i++) {
        lengthAry[i] = parseInt(lenStr[i]);
      }
      lengthAry[lenStr.length] = 255;

      if (Blob) {
        var blob = new Blob([binaryIdentifier.buffer, lengthAry.buffer, encoded]);
        doneCallback(null, blob);
      }
    });
  }

  map(packets, encodeOne, function(err, results) {
    return callback(new Blob(results));
  });
};

/*
 * Decodes data when a payload is maybe expected. Strings are decoded by
 * interpreting each byte as a key code for entries marked to start with 0. See
 * description of encodePayloadAsBinary
 *
 * @param {ArrayBuffer} data, callback method
 * @api public
 */

exports.decodePayloadAsBinary = function (data, binaryType, callback) {
  if (typeof binaryType === 'function') {
    callback = binaryType;
    binaryType = null;
  }

  var bufferTail = data;
  var buffers = [];

  var numberTooLong = false;
  while (bufferTail.byteLength > 0) {
    var tailArray = new Uint8Array(bufferTail);
    var isString = tailArray[0] === 0;
    var msgLength = '';

    for (var i = 1; ; i++) {
      if (tailArray[i] == 255) break;

      if (msgLength.length > 310) {
        numberTooLong = true;
        break;
      }

      msgLength += tailArray[i];
    }

    if(numberTooLong) return callback(err, 0, 1);

    bufferTail = sliceBuffer(bufferTail, 2 + msgLength.length);
    msgLength = parseInt(msgLength);

    var msg = sliceBuffer(bufferTail, 0, msgLength);
    if (isString) {
      try {
        msg = String.fromCharCode.apply(null, new Uint8Array(msg));
      } catch (e) {
        // iPhone Safari doesn't let you apply to typed arrays
        var typed = new Uint8Array(msg);
        msg = '';
        for (var i = 0; i < typed.length; i++) {
          msg += String.fromCharCode(typed[i]);
        }
      }
    }

    buffers.push(msg);
    bufferTail = sliceBuffer(bufferTail, msgLength);
  }

  var total = buffers.length;
  buffers.forEach(function(buffer, i) {
    callback(exports.decodePacket(buffer, binaryType, true), i, total);
  });
};

}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./keys":43,"after":19,"arraybuffer.slice":20,"base64-arraybuffer":21,"blob":23,"has-binary":44,"wtf-8":72}],43:[function(_dereq_,module,exports){

/**
 * Gets the keys for an object.
 *
 * @return {Array} keys
 * @api private
 */

module.exports = Object.keys || function keys (obj){
  var arr = [];
  var has = Object.prototype.hasOwnProperty;

  for (var i in obj) {
    if (has.call(obj, i)) {
      arr.push(i);
    }
  }
  return arr;
};

},{}],44:[function(_dereq_,module,exports){
(function (global){

/*
 * Module requirements.
 */

var isArray = _dereq_('isarray');

/**
 * Module exports.
 */

module.exports = hasBinary;

/**
 * Checks for binary data.
 *
 * Right now only Buffer and ArrayBuffer are supported..
 *
 * @param {Object} anything
 * @api public
 */

function hasBinary(data) {

  function _hasBinary(obj) {
    if (!obj) return false;

    if ( (global.Buffer && global.Buffer.isBuffer(obj)) ||
         (global.ArrayBuffer && obj instanceof ArrayBuffer) ||
         (global.Blob && obj instanceof Blob) ||
         (global.File && obj instanceof File)
        ) {
      return true;
    }

    if (isArray(obj)) {
      for (var i = 0; i < obj.length; i++) {
          if (_hasBinary(obj[i])) {
              return true;
          }
      }
    } else if (obj && 'object' == typeof obj) {
      if (obj.toJSON) {
        obj = obj.toJSON();
      }

      for (var key in obj) {
        if (Object.prototype.hasOwnProperty.call(obj, key) && _hasBinary(obj[key])) {
          return true;
        }
      }
    }

    return false;
  }

  return _hasBinary(data);
}

}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"isarray":49}],45:[function(_dereq_,module,exports){

/**
 * Module exports.
 *
 * Logic borrowed from Modernizr:
 *
 *   - https://github.com/Modernizr/Modernizr/blob/master/feature-detects/cors.js
 */

try {
  module.exports = typeof XMLHttpRequest !== 'undefined' &&
    'withCredentials' in new XMLHttpRequest();
} catch (err) {
  // if XMLHttp support is disabled in IE then it will throw
  // when trying to create
  module.exports = false;
}

},{}],46:[function(_dereq_,module,exports){
(function (global){
'use strict';
var Mutation = global.MutationObserver || global.WebKitMutationObserver;

var scheduleDrain;

{
  if (Mutation) {
    var called = 0;
    var observer = new Mutation(nextTick);
    var element = global.document.createTextNode('');
    observer.observe(element, {
      characterData: true
    });
    scheduleDrain = function () {
      element.data = (called = ++called % 2);
    };
  } else if (!global.setImmediate && typeof global.MessageChannel !== 'undefined') {
    var channel = new global.MessageChannel();
    channel.port1.onmessage = nextTick;
    scheduleDrain = function () {
      channel.port2.postMessage(0);
    };
  } else if ('document' in global && 'onreadystatechange' in global.document.createElement('script')) {
    scheduleDrain = function () {

      // Create a <script> element; its readystatechange event will be fired asynchronously once it is inserted
      // into the document. Do so, thus queuing up the task. Remember to clean up once it's been called.
      var scriptEl = global.document.createElement('script');
      scriptEl.onreadystatechange = function () {
        nextTick();

        scriptEl.onreadystatechange = null;
        scriptEl.parentNode.removeChild(scriptEl);
        scriptEl = null;
      };
      global.document.documentElement.appendChild(scriptEl);
    };
  } else {
    scheduleDrain = function () {
      setTimeout(nextTick, 0);
    };
  }
}

var draining;
var queue = [];
//named nextTick for less confusing stack traces
function nextTick() {
  draining = true;
  var i, oldQueue;
  var len = queue.length;
  while (len) {
    oldQueue = queue;
    queue = [];
    i = -1;
    while (++i < len) {
      oldQueue[i]();
    }
    len = queue.length;
  }
  draining = false;
}

module.exports = immediate;
function immediate(task) {
  if (queue.push(task) === 1 && !draining) {
    scheduleDrain();
  }
}

}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],47:[function(_dereq_,module,exports){

var indexOf = [].indexOf;

module.exports = function(arr, obj){
  if (indexOf) return arr.indexOf(obj);
  for (var i = 0; i < arr.length; ++i) {
    if (arr[i] === obj) return i;
  }
  return -1;
};
},{}],48:[function(_dereq_,module,exports){
if (typeof Object.create === 'function') {
  // implementation from standard node.js 'util' module
  module.exports = function inherits(ctor, superCtor) {
    ctor.super_ = superCtor
    ctor.prototype = Object.create(superCtor.prototype, {
      constructor: {
        value: ctor,
        enumerable: false,
        writable: true,
        configurable: true
      }
    });
  };
} else {
  // old school shim for old browsers
  module.exports = function inherits(ctor, superCtor) {
    ctor.super_ = superCtor
    var TempCtor = function () {}
    TempCtor.prototype = superCtor.prototype
    ctor.prototype = new TempCtor()
    ctor.prototype.constructor = ctor
  }
}

},{}],49:[function(_dereq_,module,exports){
module.exports = Array.isArray || function (arr) {
  return Object.prototype.toString.call(arr) == '[object Array]';
};

},{}],50:[function(_dereq_,module,exports){
'use strict';

module.exports = INTERNAL;

function INTERNAL() {}
},{}],51:[function(_dereq_,module,exports){
'use strict';
var Promise = _dereq_('./promise');
var reject = _dereq_('./reject');
var resolve = _dereq_('./resolve');
var INTERNAL = _dereq_('./INTERNAL');
var handlers = _dereq_('./handlers');
module.exports = all;
function all(iterable) {
  if (Object.prototype.toString.call(iterable) !== '[object Array]') {
    return reject(new TypeError('must be an array'));
  }

  var len = iterable.length;
  var called = false;
  if (!len) {
    return resolve([]);
  }

  var values = new Array(len);
  var resolved = 0;
  var i = -1;
  var promise = new Promise(INTERNAL);
  
  while (++i < len) {
    allResolver(iterable[i], i);
  }
  return promise;
  function allResolver(value, i) {
    resolve(value).then(resolveFromAll, function (error) {
      if (!called) {
        called = true;
        handlers.reject(promise, error);
      }
    });
    function resolveFromAll(outValue) {
      values[i] = outValue;
      if (++resolved === len & !called) {
        called = true;
        handlers.resolve(promise, values);
      }
    }
  }
}
},{"./INTERNAL":50,"./handlers":52,"./promise":54,"./reject":57,"./resolve":58}],52:[function(_dereq_,module,exports){
'use strict';
var tryCatch = _dereq_('./tryCatch');
var resolveThenable = _dereq_('./resolveThenable');
var states = _dereq_('./states');

exports.resolve = function (self, value) {
  var result = tryCatch(getThen, value);
  if (result.status === 'error') {
    return exports.reject(self, result.value);
  }
  var thenable = result.value;

  if (thenable) {
    resolveThenable.safely(self, thenable);
  } else {
    self.state = states.FULFILLED;
    self.outcome = value;
    var i = -1;
    var len = self.queue.length;
    while (++i < len) {
      self.queue[i].callFulfilled(value);
    }
  }
  return self;
};
exports.reject = function (self, error) {
  self.state = states.REJECTED;
  self.outcome = error;
  var i = -1;
  var len = self.queue.length;
  while (++i < len) {
    self.queue[i].callRejected(error);
  }
  return self;
};

function getThen(obj) {
  // Make sure we only access the accessor once as required by the spec
  var then = obj && obj.then;
  if (obj && typeof obj === 'object' && typeof then === 'function') {
    return function appyThen() {
      then.apply(obj, arguments);
    };
  }
}

},{"./resolveThenable":59,"./states":60,"./tryCatch":61}],53:[function(_dereq_,module,exports){
module.exports = exports = _dereq_('./promise');

exports.resolve = _dereq_('./resolve');
exports.reject = _dereq_('./reject');
exports.all = _dereq_('./all');
exports.race = _dereq_('./race');

},{"./all":51,"./promise":54,"./race":56,"./reject":57,"./resolve":58}],54:[function(_dereq_,module,exports){
'use strict';

var unwrap = _dereq_('./unwrap');
var INTERNAL = _dereq_('./INTERNAL');
var resolveThenable = _dereq_('./resolveThenable');
var states = _dereq_('./states');
var QueueItem = _dereq_('./queueItem');

module.exports = Promise;
function Promise(resolver) {
  if (!(this instanceof Promise)) {
    return new Promise(resolver);
  }
  if (typeof resolver !== 'function') {
    throw new TypeError('resolver must be a function');
  }
  this.state = states.PENDING;
  this.queue = [];
  this.outcome = void 0;
  if (resolver !== INTERNAL) {
    resolveThenable.safely(this, resolver);
  }
}

Promise.prototype['catch'] = function (onRejected) {
  return this.then(null, onRejected);
};
Promise.prototype.then = function (onFulfilled, onRejected) {
  if (typeof onFulfilled !== 'function' && this.state === states.FULFILLED ||
    typeof onRejected !== 'function' && this.state === states.REJECTED) {
    return this;
  }
  var promise = new Promise(INTERNAL);
  if (this.state !== states.PENDING) {
    var resolver = this.state === states.FULFILLED ? onFulfilled : onRejected;
    unwrap(promise, resolver, this.outcome);
  } else {
    this.queue.push(new QueueItem(promise, onFulfilled, onRejected));
  }

  return promise;
};

},{"./INTERNAL":50,"./queueItem":55,"./resolveThenable":59,"./states":60,"./unwrap":62}],55:[function(_dereq_,module,exports){
'use strict';
var handlers = _dereq_('./handlers');
var unwrap = _dereq_('./unwrap');

module.exports = QueueItem;
function QueueItem(promise, onFulfilled, onRejected) {
  this.promise = promise;
  if (typeof onFulfilled === 'function') {
    this.onFulfilled = onFulfilled;
    this.callFulfilled = this.otherCallFulfilled;
  }
  if (typeof onRejected === 'function') {
    this.onRejected = onRejected;
    this.callRejected = this.otherCallRejected;
  }
}
QueueItem.prototype.callFulfilled = function (value) {
  handlers.resolve(this.promise, value);
};
QueueItem.prototype.otherCallFulfilled = function (value) {
  unwrap(this.promise, this.onFulfilled, value);
};
QueueItem.prototype.callRejected = function (value) {
  handlers.reject(this.promise, value);
};
QueueItem.prototype.otherCallRejected = function (value) {
  unwrap(this.promise, this.onRejected, value);
};

},{"./handlers":52,"./unwrap":62}],56:[function(_dereq_,module,exports){
'use strict';
var Promise = _dereq_('./promise');
var reject = _dereq_('./reject');
var resolve = _dereq_('./resolve');
var INTERNAL = _dereq_('./INTERNAL');
var handlers = _dereq_('./handlers');
module.exports = race;
function race(iterable) {
  if (Object.prototype.toString.call(iterable) !== '[object Array]') {
    return reject(new TypeError('must be an array'));
  }

  var len = iterable.length;
  var called = false;
  if (!len) {
    return resolve([]);
  }

  var i = -1;
  var promise = new Promise(INTERNAL);

  while (++i < len) {
    resolver(iterable[i]);
  }
  return promise;
  function resolver(value) {
    resolve(value).then(function (response) {
      if (!called) {
        called = true;
        handlers.resolve(promise, response);
      }
    }, function (error) {
      if (!called) {
        called = true;
        handlers.reject(promise, error);
      }
    });
  }
}

},{"./INTERNAL":50,"./handlers":52,"./promise":54,"./reject":57,"./resolve":58}],57:[function(_dereq_,module,exports){
'use strict';

var Promise = _dereq_('./promise');
var INTERNAL = _dereq_('./INTERNAL');
var handlers = _dereq_('./handlers');
module.exports = reject;

function reject(reason) {
	var promise = new Promise(INTERNAL);
	return handlers.reject(promise, reason);
}
},{"./INTERNAL":50,"./handlers":52,"./promise":54}],58:[function(_dereq_,module,exports){
'use strict';

var Promise = _dereq_('./promise');
var INTERNAL = _dereq_('./INTERNAL');
var handlers = _dereq_('./handlers');
module.exports = resolve;

var FALSE = handlers.resolve(new Promise(INTERNAL), false);
var NULL = handlers.resolve(new Promise(INTERNAL), null);
var UNDEFINED = handlers.resolve(new Promise(INTERNAL), void 0);
var ZERO = handlers.resolve(new Promise(INTERNAL), 0);
var EMPTYSTRING = handlers.resolve(new Promise(INTERNAL), '');

function resolve(value) {
  if (value) {
    if (value instanceof Promise) {
      return value;
    }
    return handlers.resolve(new Promise(INTERNAL), value);
  }
  var valueType = typeof value;
  switch (valueType) {
    case 'boolean':
      return FALSE;
    case 'undefined':
      return UNDEFINED;
    case 'object':
      return NULL;
    case 'number':
      return ZERO;
    case 'string':
      return EMPTYSTRING;
  }
}
},{"./INTERNAL":50,"./handlers":52,"./promise":54}],59:[function(_dereq_,module,exports){
'use strict';
var handlers = _dereq_('./handlers');
var tryCatch = _dereq_('./tryCatch');
function safelyResolveThenable(self, thenable) {
  // Either fulfill, reject or reject with error
  var called = false;
  function onError(value) {
    if (called) {
      return;
    }
    called = true;
    handlers.reject(self, value);
  }

  function onSuccess(value) {
    if (called) {
      return;
    }
    called = true;
    handlers.resolve(self, value);
  }

  function tryToUnwrap() {
    thenable(onSuccess, onError);
  }
  
  var result = tryCatch(tryToUnwrap);
  if (result.status === 'error') {
    onError(result.value);
  }
}
exports.safely = safelyResolveThenable;
},{"./handlers":52,"./tryCatch":61}],60:[function(_dereq_,module,exports){
// Lazy man's symbols for states

exports.REJECTED = ['REJECTED'];
exports.FULFILLED = ['FULFILLED'];
exports.PENDING = ['PENDING'];

},{}],61:[function(_dereq_,module,exports){
'use strict';

module.exports = tryCatch;

function tryCatch(func, value) {
  var out = {};
  try {
    out.value = func(value);
    out.status = 'success';
  } catch (e) {
    out.status = 'error';
    out.value = e;
  }
  return out;
}
},{}],62:[function(_dereq_,module,exports){
'use strict';

var immediate = _dereq_('immediate');
var handlers = _dereq_('./handlers');
module.exports = unwrap;

function unwrap(promise, func, value) {
  immediate(function () {
    var returnValue;
    try {
      returnValue = func(value);
    } catch (e) {
      return handlers.reject(promise, e);
    }
    if (returnValue === promise) {
      handlers.reject(promise, new TypeError('Cannot resolve promise with itself'));
    } else {
      handlers.resolve(promise, returnValue);
    }
  });
}
},{"./handlers":52,"immediate":46}],63:[function(_dereq_,module,exports){
/**
 * Helpers.
 */

var s = 1000
var m = s * 60
var h = m * 60
var d = h * 24
var y = d * 365.25

/**
 * Parse or format the given `val`.
 *
 * Options:
 *
 *  - `long` verbose formatting [false]
 *
 * @param {String|Number} val
 * @param {Object} options
 * @throws {Error} throw an error if val is not a non-empty string or a number
 * @return {String|Number}
 * @api public
 */

module.exports = function (val, options) {
  options = options || {}
  var type = typeof val
  if (type === 'string' && val.length > 0) {
    return parse(val)
  } else if (type === 'number' && isNaN(val) === false) {
    return options["long"] ?
			fmtLong(val) :
			fmtShort(val)
  }
  throw new Error('val is not a non-empty string or a valid number. val=' + JSON.stringify(val))
}

/**
 * Parse the given `str` and return milliseconds.
 *
 * @param {String} str
 * @return {Number}
 * @api private
 */

function parse(str) {
  str = String(str)
  if (str.length > 10000) {
    return
  }
  var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(str)
  if (!match) {
    return
  }
  var n = parseFloat(match[1])
  var type = (match[2] || 'ms').toLowerCase()
  switch (type) {
    case 'years':
    case 'year':
    case 'yrs':
    case 'yr':
    case 'y':
      return n * y
    case 'days':
    case 'day':
    case 'd':
      return n * d
    case 'hours':
    case 'hour':
    case 'hrs':
    case 'hr':
    case 'h':
      return n * h
    case 'minutes':
    case 'minute':
    case 'mins':
    case 'min':
    case 'm':
      return n * m
    case 'seconds':
    case 'second':
    case 'secs':
    case 'sec':
    case 's':
      return n * s
    case 'milliseconds':
    case 'millisecond':
    case 'msecs':
    case 'msec':
    case 'ms':
      return n
    default:
      return undefined
  }
}

/**
 * Short format for `ms`.
 *
 * @param {Number} ms
 * @return {String}
 * @api private
 */

function fmtShort(ms) {
  if (ms >= d) {
    return Math.round(ms / d) + 'd'
  }
  if (ms >= h) {
    return Math.round(ms / h) + 'h'
  }
  if (ms >= m) {
    return Math.round(ms / m) + 'm'
  }
  if (ms >= s) {
    return Math.round(ms / s) + 's'
  }
  return ms + 'ms'
}

/**
 * Long format for `ms`.
 *
 * @param {Number} ms
 * @return {String}
 * @api private
 */

function fmtLong(ms) {
  return plural(ms, d, 'day') ||
    plural(ms, h, 'hour') ||
    plural(ms, m, 'minute') ||
    plural(ms, s, 'second') ||
    ms + ' ms'
}

/**
 * Pluralization helper.
 */

function plural(ms, n, name) {
  if (ms < n) {
    return
  }
  if (ms < n * 1.5) {
    return Math.floor(ms / n) + ' ' + name
  }
  return Math.ceil(ms / n) + ' ' + name + 's'
}

},{}],64:[function(_dereq_,module,exports){
module.exports = typeof Promise === 'function' ? Promise : _dereq_('lie');

},{"lie":53}],65:[function(_dereq_,module,exports){
(function (global){
/**
 * JSON parse.
 *
 * @see Based on jQuery#parseJSON (MIT) and JSON2
 * @api private
 */

var rvalidchars = /^[\],:{}\s]*$/;
var rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g;
var rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g;
var rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g;
var rtrimLeft = /^\s+/;
var rtrimRight = /\s+$/;

module.exports = function parsejson(data) {
  if ('string' != typeof data || !data) {
    return null;
  }

  data = data.replace(rtrimLeft, '').replace(rtrimRight, '');

  // Attempt to parse using the native JSON parser first
  if (global.JSON && JSON.parse) {
    return JSON.parse(data);
  }

  if (rvalidchars.test(data.replace(rvalidescape, '@')
      .replace(rvalidtokens, ']')
      .replace(rvalidbraces, ''))) {
    return (new Function('return ' + data))();
  }
};
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],66:[function(_dereq_,module,exports){
/**
 * Compiles a querystring
 * Returns string representation of the object
 *
 * @param {Object}
 * @api private
 */

exports.encode = function (obj) {
  var str = '';

  for (var i in obj) {
    if (obj.hasOwnProperty(i)) {
      if (str.length) str += '&';
      str += encodeURIComponent(i) + '=' + encodeURIComponent(obj[i]);
    }
  }

  return str;
};

/**
 * Parses a simple querystring into an object
 *
 * @param {String} qs
 * @api private
 */

exports.decode = function(qs){
  var qry = {};
  var pairs = qs.split('&');
  for (var i = 0, l = pairs.length; i < l; i++) {
    var pair = pairs[i].split('=');
    qry[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
  }
  return qry;
};

},{}],67:[function(_dereq_,module,exports){
/**
 * Parses an URI
 *
 * @author Steven Levithan <stevenlevithan.com> (MIT license)
 * @api private
 */

var re = /^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;

var parts = [
    'source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'
];

module.exports = function parseuri(str) {
    var src = str,
        b = str.indexOf('['),
        e = str.indexOf(']');

    if (b != -1 && e != -1) {
        str = str.substring(0, b) + str.substring(b, e).replace(/:/g, ';') + str.substring(e, str.length);
    }

    var m = re.exec(str || ''),
        uri = {},
        i = 14;

    while (i--) {
        uri[parts[i]] = m[i] || '';
    }

    if (b != -1 && e != -1) {
        uri.source = src;
        uri.host = uri.host.substring(1, uri.host.length - 1).replace(/;/g, ':');
        uri.authority = uri.authority.replace('[', '').replace(']', '').replace(/;/g, ':');
        uri.ipv6uri = true;
    }

    return uri;
};

},{}],68:[function(_dereq_,module,exports){
(function (global){
"use strict";

//Abstracts constructing a Blob object, so it also works in older
//browsers that don't support the native Blob constructor. (i.e.
//old QtWebKit versions, at least).
function createBlob(parts, properties) {
  parts = parts || [];
  properties = properties || {};
  try {
    return new Blob(parts, properties);
  } catch (e) {
    if (e.name !== "TypeError") {
      throw e;
    }
    var BlobBuilder = global.BlobBuilder ||
                      global.MSBlobBuilder ||
                      global.MozBlobBuilder ||
                      global.WebKitBlobBuilder;
    var builder = new BlobBuilder();
    for (var i = 0; i < parts.length; i += 1) {
      builder.append(parts[i]);
    }
    return builder.getBlob(properties.type);
  }
}

//Can't find original post, but this is close
//http://stackoverflow.com/questions/6965107/ (continues on next line)
//converting-between-strings-and-arraybuffers
function arrayBufferToBinaryString(buffer) {
  var binary = "";
  var bytes = new Uint8Array(buffer);
  var length = bytes.byteLength;
  for (var i = 0; i < length; i++) {
    binary += String.fromCharCode(bytes[i]);
  }
  return binary;
}

// This used to be called "fixBinary", which wasn't a very evocative name
// From http://stackoverflow.com/questions/14967647/ (continues on next line)
// encode-decode-image-with-base64-breaks-image (2013-04-21)
function binaryStringToArrayBuffer(bin) {
  var length = bin.length;
  var buf = new ArrayBuffer(length);
  var arr = new Uint8Array(buf);
  for (var i = 0; i < length; i++) {
    arr[i] = bin.charCodeAt(i);
  }
  return buf;
}

// shim for browsers that don't support it
function readAsBinaryString(blob, callback) {
  var reader = new FileReader();
  var hasBinaryString = typeof reader.readAsBinaryString === 'function';
  reader.onloadend = function (e) {
    var result = e.target.result || '';
    if (hasBinaryString) {
      return callback(result);
    }
    callback(arrayBufferToBinaryString(result));
  };
  if (hasBinaryString) {
    reader.readAsBinaryString(blob);
  } else {
    reader.readAsArrayBuffer(blob);
  }
}

// simplified API. universal browser support is assumed
function readAsArrayBuffer(blob, callback) {
  var reader = new FileReader();
  reader.onloadend = function (e) {
    var result = e.target.result || new ArrayBuffer(0);
    callback(result);
  };
  reader.readAsArrayBuffer(blob);
}

module.exports = {
  createBlob: createBlob,
  readAsArrayBuffer: readAsArrayBuffer,
  readAsBinaryString: readAsBinaryString,
  binaryStringToArrayBuffer: binaryStringToArrayBuffer,
  arrayBufferToBinaryString: arrayBufferToBinaryString
};


}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],69:[function(_dereq_,module,exports){
'use strict';

function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var lie = _interopDefault(_dereq_('lie'));

/* istanbul ignore next */
var PouchPromise = typeof Promise === 'function' ? Promise : lie;

module.exports = PouchPromise;
},{"lie":70}],70:[function(_dereq_,module,exports){
'use strict';
var immediate = _dereq_('immediate');

/* istanbul ignore next */
function INTERNAL() {}

var handlers = {};

var REJECTED = ['REJECTED'];
var FULFILLED = ['FULFILLED'];
var PENDING = ['PENDING'];

module.exports = Promise;

function Promise(resolver) {
  if (typeof resolver !== 'function') {
    throw new TypeError('resolver must be a function');
  }
  this.state = PENDING;
  this.queue = [];
  this.outcome = void 0;
  if (resolver !== INTERNAL) {
    safelyResolveThenable(this, resolver);
  }
}

Promise.prototype["catch"] = function (onRejected) {
  return this.then(null, onRejected);
};
Promise.prototype.then = function (onFulfilled, onRejected) {
  if (typeof onFulfilled !== 'function' && this.state === FULFILLED ||
    typeof onRejected !== 'function' && this.state === REJECTED) {
    return this;
  }
  var promise = new this.constructor(INTERNAL);
  if (this.state !== PENDING) {
    var resolver = this.state === FULFILLED ? onFulfilled : onRejected;
    unwrap(promise, resolver, this.outcome);
  } else {
    this.queue.push(new QueueItem(promise, onFulfilled, onRejected));
  }

  return promise;
};
function QueueItem(promise, onFulfilled, onRejected) {
  this.promise = promise;
  if (typeof onFulfilled === 'function') {
    this.onFulfilled = onFulfilled;
    this.callFulfilled = this.otherCallFulfilled;
  }
  if (typeof onRejected === 'function') {
    this.onRejected = onRejected;
    this.callRejected = this.otherCallRejected;
  }
}
QueueItem.prototype.callFulfilled = function (value) {
  handlers.resolve(this.promise, value);
};
QueueItem.prototype.otherCallFulfilled = function (value) {
  unwrap(this.promise, this.onFulfilled, value);
};
QueueItem.prototype.callRejected = function (value) {
  handlers.reject(this.promise, value);
};
QueueItem.prototype.otherCallRejected = function (value) {
  unwrap(this.promise, this.onRejected, value);
};

function unwrap(promise, func, value) {
  immediate(function () {
    var returnValue;
    try {
      returnValue = func(value);
    } catch (e) {
      return handlers.reject(promise, e);
    }
    if (returnValue === promise) {
      handlers.reject(promise, new TypeError('Cannot resolve promise with itself'));
    } else {
      handlers.resolve(promise, returnValue);
    }
  });
}

handlers.resolve = function (self, value) {
  var result = tryCatch(getThen, value);
  if (result.status === 'error') {
    return handlers.reject(self, result.value);
  }
  var thenable = result.value;

  if (thenable) {
    safelyResolveThenable(self, thenable);
  } else {
    self.state = FULFILLED;
    self.outcome = value;
    var i = -1;
    var len = self.queue.length;
    while (++i < len) {
      self.queue[i].callFulfilled(value);
    }
  }
  return self;
};
handlers.reject = function (self, error) {
  self.state = REJECTED;
  self.outcome = error;
  var i = -1;
  var len = self.queue.length;
  while (++i < len) {
    self.queue[i].callRejected(error);
  }
  return self;
};

function getThen(obj) {
  // Make sure we only access the accessor once as required by the spec
  var then = obj && obj.then;
  if (obj && typeof obj === 'object' && typeof then === 'function') {
    return function appyThen() {
      then.apply(obj, arguments);
    };
  }
}

function safelyResolveThenable(self, thenable) {
  // Either fulfill, reject or reject with error
  var called = false;
  function onError(value) {
    if (called) {
      return;
    }
    called = true;
    handlers.reject(self, value);
  }

  function onSuccess(value) {
    if (called) {
      return;
    }
    called = true;
    handlers.resolve(self, value);
  }

  function tryToUnwrap() {
    thenable(onSuccess, onError);
  }

  var result = tryCatch(tryToUnwrap);
  if (result.status === 'error') {
    onError(result.value);
  }
}

function tryCatch(func, value) {
  var out = {};
  try {
    out.value = func(value);
    out.status = 'success';
  } catch (e) {
    out.status = 'error';
    out.value = e;
  }
  return out;
}

Promise.resolve = resolve;
function resolve(value) {
  if (value instanceof this) {
    return value;
  }
  return handlers.resolve(ne
Download .txt
gitextract_5blrnppl/

├── .gitignore
├── .jshintrc
├── .npmignore
├── .travis.yml
├── LICENSE
├── README.md
├── bin/
│   ├── dev-server.js
│   ├── es3ify.js
│   ├── run-test.sh
│   ├── test-browser.js
│   └── test-node.sh
├── client/
│   └── index.js
├── dist/
│   └── socket-pouch.client.js
├── lib/
│   ├── client/
│   │   ├── arrayBufferToBinaryString.js
│   │   ├── base64.js
│   │   ├── base64StringToBlobOrBuffer-browser.js
│   │   ├── base64StringToBlobOrBuffer.js
│   │   ├── binaryStringToArrayBuffer.js
│   │   ├── binaryStringToBlobOrBuffer-browser.js
│   │   ├── binaryStringToBlobOrBuffer.js
│   │   ├── blob.js
│   │   ├── index.js
│   │   ├── readAsArrayBuffer.js
│   │   ├── readAsBinaryString-browser.js
│   │   ├── readAsBinaryString.js
│   │   ├── typedBuffer.js
│   │   └── utils.js
│   ├── server/
│   │   ├── index.js
│   │   ├── make-pouch-creator.js
│   │   ├── safe-eval.js
│   │   └── utils.js
│   └── shared/
│       ├── buffer-browser.js
│       ├── buffer.js
│       ├── cloneBinaryObject-browser.js
│       ├── cloneBinaryObject.js
│       ├── errors.js
│       ├── isBinaryObject-browser.js
│       ├── isBinaryObject.js
│       ├── parse-message.js
│       ├── pouchdb-clone.js
│       ├── utils.js
│       └── uuid.js
├── package.json
├── server/
│   └── index.js
└── test/
    ├── bind-polyfill.js
    ├── deps/
    │   └── bigimage.js
    ├── index.html
    ├── node.setup.js
    ├── pouchdb/
    │   ├── integration/
    │   │   ├── deps/
    │   │   │   └── bigimage.js
    │   │   ├── pouchdb-for-coverage.js
    │   │   ├── test.aa.setup.js
    │   │   ├── test.all_docs.js
    │   │   ├── test.attachments.js
    │   │   ├── test.basics.js
    │   │   ├── test.bulk_docs.js
    │   │   ├── test.bulk_get.js
    │   │   ├── test.changes.js
    │   │   ├── test.compaction.js
    │   │   ├── test.conflicts.js
    │   │   ├── test.constructor.js
    │   │   ├── test.design_docs.js
    │   │   ├── test.events.js
    │   │   ├── test.get.js
    │   │   ├── test.http.js
    │   │   ├── test.issue1175.js
    │   │   ├── test.issue221.js
    │   │   ├── test.issue3179.js
    │   │   ├── test.issue3646.js
    │   │   ├── test.local_docs.js
    │   │   ├── test.replication.js
    │   │   ├── test.replication_events.js
    │   │   ├── test.reserved.js
    │   │   ├── test.retry.js
    │   │   ├── test.revs_diff.js
    │   │   ├── test.slash_id.js
    │   │   ├── test.sync.js
    │   │   ├── test.sync_events.js
    │   │   ├── test.taskqueue.js
    │   │   ├── test.uuids.js
    │   │   ├── utils-bundle.js
    │   │   └── utils.js
    │   └── mapreduce/
    │       ├── test.mapreduce.js
    │       ├── test.persisted.js
    │       └── test.views.js
    ├── test.js
    └── webrunner.js
Download .txt
SYMBOL INDEX (1174 symbols across 35 files)

FILE: bin/dev-server.js
  function bundle (line 36) | function bundle() {
  function startSocketServer (line 54) | function startSocketServer() {
  function startServers (line 62) | function startServers(callback) {
  function checkReady (line 92) | function checkReady() {

FILE: bin/test-browser.js
  function testError (line 51) | function testError(e) {
  function postResult (line 58) | function postResult(result) {
  function testComplete (line 62) | function testComplete(result) {
  function startSelenium (line 76) | function startSelenium(callback) {
  function startSauceConnect (line 91) | function startSauceConnect(callback) {
  function startTest (line 111) | function startTest() {

FILE: dist/socket-pouch.client.js
  function s (line 1) | function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&re...
  function createBlob (line 91) | function createBlob(parts, properties) {
  function close (line 141) | function close(api, callback) {
  function SocketPouch (line 162) | function SocketPouch(opts, callback) {
  function logApiCall (line 851) | function logApiCall(self, name, args) {
  function cloneArrayBuffer (line 903) | function cloneArrayBuffer(buff) {
  function PouchError (line 935) | function PouchError(opts) {
  function CustomPouchError (line 1089) | function CustomPouchError(reason) {
  function parseMessage (line 1201) | function parseMessage(msg, numArgs) {
  function getValue (line 1430) | function getValue(radix) {
  function uuid (line 1433) | function uuid(len, radix) {
  function after (line 1475) | function after(count, callback, err_cb) {
  function noop (line 1500) | function noop() {}
  function binaryStringToArrayBuffer (line 1615) | function binaryStringToArrayBuffer(binary) {
  function arrayBufferToBinaryString (line 1629) | function arrayBufferToBinaryString(buffer) {
  function loadImage (line 1642) | function loadImage(src, crossOrigin) {
  function imgToCanvas (line 1656) | function imgToCanvas(img) {
  function createBlob (line 1688) | function createBlob(parts, options) {
  function createObjectURL (line 1704) | function createObjectURL(blob) {
  function revokeObjectURL (line 1715) | function revokeObjectURL(url) {
  function blobToBinaryString (line 1725) | function blobToBinaryString(blob) {
  function base64StringToBlob (line 1751) | function base64StringToBlob(base64, type) {
  function binaryStringToBlob (line 1764) | function binaryStringToBlob(binary, type) {
  function blobToBase64String (line 1775) | function blobToBase64String(blob) {
  function dataURLToBlob (line 1788) | function dataURLToBlob(dataURL) {
  function imgSrcToDataURL (line 1813) | function imgSrcToDataURL(src, type, crossOrigin, quality) {
  function canvasToBlob (line 1831) | function canvasToBlob(canvas, type, quality) {
  function imgSrcToBlob (line 1857) | function imgSrcToBlob(src, type, crossOrigin, quality) {
  function arrayBufferToBlob (line 1874) | function arrayBufferToBlob(buffer, type) {
  function blobToArrayBuffer (line 1885) | function blobToArrayBuffer(blob) {
  function mapArrayBufferViews (line 1965) | function mapArrayBufferViews(ary) {
  function BlobBuilderConstructor (line 1984) | function BlobBuilderConstructor(ary, options) {
  function BlobConstructor (line 1997) | function BlobConstructor(ary, options) {
  function Emitter (line 2029) | function Emitter(obj) {
  function mixin (line 2041) | function mixin(obj) {
  function on (line 2079) | function on() {
  function useColors (line 2230) | function useColors() {
  function formatArgs (line 2256) | function formatArgs() {
  function log (line 2298) | function log() {
  function save (line 2313) | function save(namespaces) {
  function load (line 2330) | function load() {
  function localstorage (line 2361) | function localstorage(){
  function selectColor (line 2418) | function selectColor() {
  function debug (line 2430) | function debug(namespace) {
  function enable (line 2507) | function enable(namespaces) {
  function disable (line 2530) | function disable() {
  function enabled (line 2542) | function enabled(name) {
  function coerce (line 2565) | function coerce(val) {
  function Socket (line 2615) | function Socket (uri, opts) {
  function clone (line 2780) | function clone (obj) {
  function onTransportOpen (line 2873) | function onTransportOpen () {
  function freezeTransport (line 2915) | function freezeTransport () {
  function onerror (line 2928) | function onerror (err) {
  function onTransportClose (line 2939) | function onTransportClose () {
  function onclose (line 2944) | function onclose () {
  function onupgrade (line 2949) | function onupgrade (to) {
  function cleanup (line 2957) | function cleanup () {
  function close (line 3230) | function close () {
  function cleanupAndClose (line 3236) | function cleanupAndClose () {
  function waitForUpgrade (line 3242) | function waitForUpgrade () {
  function Transport (line 3342) | function Transport (opts) {
  function polling (line 3503) | function polling (opts) {
  function empty (line 3568) | function empty () { }
  function JSONPPolling (line 3577) | function JSONPPolling (opts) {
  function complete (line 3717) | function complete () {
  function initIframe (line 3722) | function initIframe () {
  function empty (line 3793) | function empty () {}
  function XHR (line 3802) | function XHR (opts) {
  function Request (line 3910) | function Request (opts) {
  function unloadHandler (line 4182) | function unloadHandler () {
  function Polling (line 4226) | function Polling (opts) {
  function pause (line 4269) | function pause () {
  function close (line 4364) | function close () {
  function WS (line 4478) | function WS (opts) {
  function done (line 4632) | function done () {
  function useColors (line 4797) | function useColors() {
  function formatArgs (line 4822) | function formatArgs() {
  function log (line 4864) | function log() {
  function save (line 4879) | function save(namespaces) {
  function load (line 4896) | function load() {
  function localstorage (line 4921) | function localstorage(){
  function selectColor (line 4977) | function selectColor() {
  function debug (line 4989) | function debug(namespace) {
  function enable (line 5063) | function enable(namespaces) {
  function disable (line 5086) | function disable() {
  function enabled (line 5098) | function enabled(name) {
  function coerce (line 5121) | function coerce(val) {
  function parse (line 5166) | function parse(str) {
  function short (line 5219) | function short(ms) {
  function long (line 5235) | function long(ms) {
  function plural (line 5247) | function plural(ms, n, name) {
  function encodeBase64Object (line 5381) | function encodeBase64Object(packet, callback) {
  function encodeArrayBuffer (line 5391) | function encodeArrayBuffer(packet, supportsBinary, callback) {
  function encodeBlobAsArrayBuffer (line 5408) | function encodeBlobAsArrayBuffer(packet, supportsBinary, callback) {
  function encodeBlob (line 5421) | function encodeBlob(packet, supportsBinary, callback) {
  function tryDecode (line 5516) | function tryDecode(data) {
  function setLengthHeader (line 5583) | function setLengthHeader(message) {
  function encodeOne (line 5587) | function encodeOne(packet, doneCallback) {
  function map (line 5602) | function map(ary, each, done) {
  function encodeOne (line 5707) | function encodeOne(packet, doneCallback) {
  function encodeOne (line 5765) | function encodeOne(packet, doneCallback) {
  function hasBinary (line 5911) | function hasBinary(data) {
  function nextTick (line 6017) | function nextTick() {
  function immediate (line 6034) | function immediate(task) {
  function INTERNAL (line 6087) | function INTERNAL() {}
  function all (line 6096) | function all(iterable) {
  function getThen (line 6169) | function getThen(obj) {
  function Promise (line 6197) | function Promise(resolver) {
  function QueueItem (line 6237) | function QueueItem(promise, onFulfilled, onRejected) {
  function race (line 6269) | function race(iterable) {
  function reject (line 6310) | function reject(reason) {
  function resolve (line 6328) | function resolve(value) {
  function safelyResolveThenable (line 6353) | function safelyResolveThenable(self, thenable) {
  function tryCatch (line 6394) | function tryCatch(func, value) {
  function unwrap (line 6412) | function unwrap(promise, func, value) {
  function parse (line 6473) | function parse(str) {
  function fmtShort (line 6532) | function fmtShort(ms) {
  function fmtLong (line 6556) | function fmtLong(ms) {
  function plural (line 6568) | function plural(ms, n, name) {
  function createBlob (line 6703) | function createBlob(parts, properties) {
  function arrayBufferToBinaryString (line 6727) | function arrayBufferToBinaryString(buffer) {
  function binaryStringToArrayBuffer (line 6740) | function binaryStringToArrayBuffer(bin) {
  function readAsBinaryString (line 6751) | function readAsBinaryString(blob, callback) {
  function readAsArrayBuffer (line 6769) | function readAsArrayBuffer(blob, callback) {
  function _interopDefault (line 6791) | function _interopDefault (ex) { return (ex && (typeof ex === 'object') &...
  function INTERNAL (line 6804) | function INTERNAL() {}
  function Promise (line 6814) | function Promise(resolver) {
  function QueueItem (line 6844) | function QueueItem(promise, onFulfilled, onRejected) {
  function unwrap (line 6868) | function unwrap(promise, func, value) {
  function getThen (line 6915) | function getThen(obj) {
  function safelyResolveThenable (line 6925) | function safelyResolveThenable(self, thenable) {
  function tryCatch (line 6954) | function tryCatch(func, value) {
  function resolve (line 6967) | function resolve(value) {
  function reject (line 6975) | function reject(reason) {
  function all (line 6981) | function all(iterable) {
  function race (line 7020) | function race(iterable) {
  function drainQueue (line 7061) | function drainQueue() {
  function noop (line 7093) | function noop() {}
  function ucs2decode (line 7138) | function ucs2decode(string) {
  function ucs2encode (line 7165) | function ucs2encode(array) {
  function createByte (line 7184) | function createByte(codePoint, shift) {
  function encodeCodePoint (line 7188) | function encodeCodePoint(codePoint) {
  function wtf8encode (line 7209) | function wtf8encode(string) {
  function readContinuationByte (line 7224) | function readContinuationByte() {
  function decodeSymbol (line 7240) | function decodeSymbol() {
  function wtf8decode (line 7305) | function wtf8decode(byteString) {
  function encode (line 7369) | function encode(num) {
  function decode (line 7387) | function decode(str) {
  function yeast (line 7403) | function yeast() {

FILE: lib/client/blob.js
  function createBlob (line 6) | function createBlob(parts, properties) {

FILE: lib/client/index.js
  function close (line 24) | function close(api, callback) {
  function SocketPouch (line 45) | function SocketPouch(opts, callback) {

FILE: lib/client/typedBuffer.js
  function typedBuffer (line 5) | function typedBuffer(binString, buffType, type) {

FILE: lib/client/utils.js
  function logApiCall (line 73) | function logApiCall(self, name, args) {

FILE: lib/server/index.js
  function destringifyArgs (line 16) | function destringifyArgs(argsString) {
  function sendUncaughtError (line 33) | function sendUncaughtError(socket, data) {
  function sendError (line 38) | function sendError(socket, messageId, data) {
  function sendSuccess (line 43) | function sendSuccess(socket, messageId, data) {
  function sendBinarySuccess (line 48) | function sendBinarySuccess(socket, messageId, type, buff) {
  function sendUpdate (line 57) | function sendUpdate(socket, messageId, data) {
  function dbMethod (line 62) | function dbMethod(socket, methodName, messageId, args) {
  function changes (line 79) | function changes(socket, messageId, args) {
  function possiblyBinaryDbMethod (line 92) | function possiblyBinaryDbMethod(socket, methodName, messageId, args) {
  function getAttachment (line 101) | function getAttachment(socket, messageId, args) {
  function destroy (line 131) | function destroy(socket, messageId, args) {
  function liveChanges (line 151) | function liveChanges(socket, messageId, args) {
  function cancelChanges (line 179) | function cancelChanges(messageId) {
  function addUncaughtErrorHandler (line 186) | function addUncaughtErrorHandler(db, socket) {
  function createDatabase (line 194) | function createDatabase(socket, messageId, args, pouchCreator) {
  function onReceiveMessage (line 220) | function onReceiveMessage(socket, type, messageId, args, pouchCreator) {
  function onReceiveTextMessage (line 258) | function onReceiveTextMessage(message, socket, pouchCreator) {
  function onReceiveBinaryMessage (line 270) | function onReceiveBinaryMessage(message, socket) {
  function listen (line 282) | function listen(port, options, callback) {

FILE: lib/server/make-pouch-creator.js
  function createLocalPouch (line 6) | function createLocalPouch(args) {
  function createHttpPouch (line 19) | function createHttpPouch(options) {
  function makePouchCreator (line 35) | function makePouchCreator(options) {

FILE: lib/shared/cloneBinaryObject-browser.js
  function cloneArrayBuffer (line 3) | function cloneArrayBuffer(buff) {

FILE: lib/shared/errors.js
  function PouchError (line 6) | function PouchError(opts) {
  function CustomPouchError (line 160) | function CustomPouchError(reason) {

FILE: lib/shared/parse-message.js
  function parseMessage (line 3) | function parseMessage(msg, numArgs) {

FILE: lib/shared/uuid.js
  function getValue (line 43) | function getValue(radix) {
  function uuid (line 46) | function uuid(len, radix) {

FILE: test/pouchdb/integration/pouchdb-for-coverage.js
  function _interopDefault (line 3) | function _interopDefault (ex) { return (ex && (typeof ex === 'object') &...
  function isBinaryObject (line 29) | function isBinaryObject(object) {
  function cloneBinaryObject (line 33) | function cloneBinaryObject(object) {
  function isPlainObject (line 46) | function isPlainObject(value) {
  function clone (line 57) | function clone(object) {
  function once (line 101) | function once(fun) {
  function toPromise (line 115) | function toPromise(func) {
  function adapterFun (line 167) | function adapterFun(name, callback) {
  function pick (line 215) | function pick(obj, arr) {
  function identityFunction (line 231) | function identityFunction(x) {
  function formatResultForOpenRevsGet (line 235) | function formatResultForOpenRevsGet(result) {
  function bulkGet (line 242) | function bulkGet(db, opts, callback) {
  function isChromeApp (line 355) | function isChromeApp() {
  function hasLocalStorage (line 360) | function hasLocalStorage() {
  function attachBrowserEvents (line 367) | function attachBrowserEvents(self) {
  function Changes (line 389) | function Changes() {
  function eventFunction (line 402) | function eventFunction() {
  function guardedConsole (line 467) | function guardedConsole(method) {
  function randomNumber (line 475) | function randomNumber(min, max) {
  function defaultBackOff (line 495) | function defaultBackOff(min) {
  function extend$1 (line 513) | function extend$1(obj) {
  function PouchError (line 537) | function PouchError(opts) {
  function createError (line 697) | function createError(error, reason) {
  function generateErrorFromResponse (line 716) | function generateErrorFromResponse(err) {
  function tryFilter (line 744) | function tryFilter(filter, doc, req) {
  function filterChange (line 753) | function filterChange(opts) {
  function flatten (line 789) | function flatten(arrs) {
  function f (line 801) | function f() {}
  function invalidIdError (line 825) | function invalidIdError(id) {
  function listenerCount (line 839) | function listenerCount(ee, type) {
  function parseDesignDocFunctionName (line 844) | function parseDesignDocFunctionName(s) {
  function normalizeDesignDocFunctionName (line 858) | function normalizeDesignDocFunctionName(s) {
  function parseUri (line 875) | function parseUri(str) {
  function upsert (line 900) | function upsert(db, docId, diffFun) {
  function tryAndPut (line 930) | function tryAndPut(db, doc, diffFun) {
  function getValue (line 985) | function getValue(radix) {
  function uuid (line 988) | function uuid(len, radix) {
  function mangle (line 1023) | function mangle(key) {
  function unmangle (line 1026) | function unmangle(key) {
  function _Map (line 1029) | function _Map() {
  function _Set (line 1061) | function _Set(array) {
  function winningRev (line 1083) | function winningRev(metadata) {
  function traverseRevTree (line 1117) | function traverseRevTree(revs, callback) {
  function sortByPos (line 1133) | function sortByPos(a, b) {
  function collectLeaves (line 1137) | function collectLeaves(revs) {
  function collectConflicts (line 1154) | function collectConflicts(metadata) {
  function compactTree (line 1169) | function compactTree(metadata) {
  function rootToLeaf (line 1182) | function rootToLeaf(revs) {
  function sortByPos$1 (line 1217) | function sortByPos$1(a, b) {
  function binarySearch (line 1222) | function binarySearch(arr, item, comparator) {
  function insertSorted (line 1238) | function insertSorted(arr, item, comparator) {
  function pathToTree (line 1246) | function pathToTree(path, numStemmed) {
  function compareTree (line 1263) | function compareTree(a, b) {
  function mergeTree (line 1269) | function mergeTree(in_tree1, in_tree2) {
  function doMerge (line 1306) | function doMerge(tree, path, dontExpand) {
  function stem (line 1388) | function stem(tree, depth) {
  function merge (line 1430) | function merge(tree, path, depth) {
  function revExists (line 1441) | function revExists(revs, rev) {
  function getTrees (line 1460) | function getTrees(node) {
  function isDeleted (line 1467) | function isDeleted(metadata, rev) {
  function isLocalId (line 1483) | function isLocalId(id) {
  function evalFilter (line 1487) | function evalFilter(input) {
  function evalView (line 1493) | function evalView(input) {
  function tryCatchInChangeListener (line 1512) | function tryCatchInChangeListener(self, change) {
  function Changes$1 (line 1521) | function Changes$1(db, opts, callback) {
  function processChange (line 1597) | function processChange(doc, metadata, opts) {
  function compare (line 1746) | function compare(left, right) {
  function arrayFirst (line 1751) | function arrayFirst(arr, callback) {
  function yankError (line 1761) | function yankError(callback) {
  function cleanDocs (line 1772) | function cleanDocs(docs) {
  function compareByIdThenRev (line 1790) | function compareByIdThenRev(a, b) {
  function computeHeight (line 1802) | function computeHeight(revs) {
  function allDocsKeysQuery (line 1827) | function allDocsKeysQuery(api, opts, callback) {
  function doNextCompaction (line 1863) | function doNextCompaction(self) {
  function attachmentNameError (line 1890) | function attachmentNameError(name) {
  function AbstractPouchDB (line 1900) | function AbstractPouchDB() {
  function createAttachment (line 1956) | function createAttachment(doc) {
  function addToMissing (line 2059) | function addToMissing(id, revId) {
  function processDoc (line 2066) | function processDoc(id, rev_tree) {
  function onChange (line 2182) | function onChange(row) {
  function onComplete (line 2185) | function onComplete(resp) {
  function finishOpenRevs (line 2220) | function finishOpenRevs() {
  function diffFun (line 2537) | function diffFun(doc) {
  function destroyDb (line 2562) | function destroyDb() {
  function TaskQueue (line 2601) | function TaskQueue() {
  function parseAdapter (line 2638) | function parseAdapter(name, opts) {
  function prepareForDestruction (line 2693) | function prepareForDestruction(self) {
  function PouchDB (line 2716) | function PouchDB(name, opts) {
  function setUpEventEmitter (line 2783) | function setUpEventEmitter(Pouch) {
  function PouchAlt (line 2827) | function PouchAlt(name, opts) {
  function isFunction (line 2861) | function isFunction(f) {
  function getPrefix (line 2865) | function getPrefix(db) {
  function clone$1 (line 2872) | function clone$1(_obj) {
  function nut (line 2880) | function nut(db, precodec, codec) {
  function NotFoundError (line 2992) | function NotFoundError() {
  function mergeOpts (line 3015) | function mergeOpts(opts) {
  function ReadStream (line 3136) | function ReadStream(options, makeData) {
  function sublevelPouch (line 3236) | function sublevelPouch(db) {
  function toObject (line 3240) | function toObject(array) {
  function parseRevisionInfo (line 3279) | function parseRevisionInfo(rev) {
  function makeRevTreeFromRevisions (line 3292) | function makeRevTreeFromRevisions(revisions, opts) {
  function parseDoc (line 3310) | function parseDoc(doc, newEdits) {
  function atob (line 3385) | function atob(str) {
  function btoa (line 3395) | function btoa(str) {
  function typedBuffer (line 3399) | function typedBuffer(binString, buffType, type) {
  function b64ToBluffer (line 3406) | function b64ToBluffer(b64, type) {
  function binStringToBluffer (line 3410) | function binStringToBluffer(binString, type) {
  function createBlob (line 3416) | function createBlob() {
  function blobToBase64 (line 3419) | function blobToBase64(blobOrBuffer, callback) {
  function binaryMd5 (line 3423) | function binaryMd5(data, callback) {
  function stringMd5 (line 3428) | function stringMd5(string) {
  function updateDoc (line 3432) | function updateDoc(revLimit, prev, docInfo, results,
  function rootIsMissing (line 3497) | function rootIsMissing(docInfo) {
  function processDocs (line 3501) | function processDocs(revLimit, docInfos, api, fetchedDocs, tx, results,
  function slowJsonParse (line 3595) | function slowJsonParse(str) {
  function safeJsonParse (line 3604) | function safeJsonParse(str) {
  function safeJsonStringify (line 3620) | function safeJsonStringify(json) {
  function readAsBlobOrBuffer (line 3629) | function readAsBlobOrBuffer(storedObject, type) {
  function prepareAttachmentForStorage (line 3636) | function prepareAttachmentForStorage(attData, cb) {
  function createEmptyBlobOrBuffer (line 3640) | function createEmptyBlobOrBuffer(type) {
  function getCacheFor (line 3649) | function getCacheFor(transaction, store) {
  function LevelTransaction (line 3660) | function LevelTransaction() {
  function getWinningRev (line 3755) | function getWinningRev(metadata) {
  function getIsDeleted (line 3760) | function getIsDeleted(metadata, winningRev) {
  function fetchAttachment (line 3765) | function fetchAttachment(att, stores, opts) {
  function fetchAttachments (line 3797) | function fetchAttachments(results, stores, opts) {
  function LevelPouch$1 (line 3817) | function LevelPouch$1(opts, callback) {
  function formatSeq (line 5185) | function formatSeq(n) {
  function move (line 5197) | function move(store, index, cb) {
  function LevelDownPouch (line 5367) | function LevelDownPouch(opts, callback) {
  function LevelPouch (line 5397) | function LevelPouch (PouchDB) {
  function applyTypeToBuffer (line 5406) | function applyTypeToBuffer(buffer, resp) {
  function defaultBody (line 5410) | function defaultBody() {
  function ajaxCore (line 5414) | function ajaxCore(options, callback) {
  function ajax (line 5502) | function ajax(opts, callback) {
  function readAttachmentsAsBlobOrBuffer (line 5514) | function readAttachmentsAsBlobOrBuffer(row) {
  function encodeDocId (line 5525) | function encodeDocId(id) {
  function preprocessAttachments$1 (line 5535) | function preprocessAttachments$1(doc) {
  function hasUrlPrefix (line 5552) | function hasUrlPrefix(opts) {
  function getHost (line 5564) | function getHost(name, opts) {
  function genDBUrl (line 5600) | function genDBUrl(opts, path) {
  function genUrl (line 5605) | function genUrl(opts, path) {
  function paramsToStr (line 5617) | function paramsToStr(params) {
  function HttpPouch (line 5624) | function HttpPouch(opts, callback) {
  function HttpPouch$1 (line 6473) | function HttpPouch$1 (PouchDB) {
  function pad (line 6478) | function pad(str, padWith, upToLength) {
  function padLeft (line 6488) | function padLeft(str, padWith, upToLength) {
  function collate (line 6497) | function collate(a, b) {
  function normalizeKey (line 6527) | function normalizeKey(key) {
  function indexify (line 6562) | function indexify(key) {
  function toIndexableString (line 6605) | function toIndexableString(key) {
  function parseNumber (line 6611) | function parseNumber(str, i) {
  function pop (line 6662) | function pop(stack, metaStack) {
  function parseIndexableString (line 6685) | function parseIndexableString(str) {
  function arrayCollate (line 6751) | function arrayCollate(a, b) {
  function stringCollate (line 6762) | function stringCollate(a, b) {
  function objectCollate (line 6768) | function objectCollate(a, b) {
  function collationIndex (line 6791) | function collationIndex(x) {
  function numToIndexableString (line 6815) | function numToIndexableString(num) {
  function TaskQueue$1 (line 6859) | function TaskQueue$1() {
  function createView (line 6874) | function createView(opts) {
  function QueryParseError (line 6951) | function QueryParseError(message) {
  function NotFoundError$1 (line 6963) | function NotFoundError$1(message) {
  function BuiltInError (line 6975) | function BuiltInError(message) {
  function createBuiltInError (line 6987) | function createBuiltInError(name) {
  function sum (line 6994) | function sum(values) {
  function createBuiltInErrorInVm (line 7026) | function createBuiltInErrorInVm(name) {
  function convertToTrueError (line 7033) | function convertToTrueError(err) {
  function isBuiltInError (line 7037) | function isBuiltInError(obj) {
  function evalFunctionInVm (line 7043) | function evalFunctionInVm(func, emit) {
  function parseViewName (line 7159) | function parseViewName(name) {
  function isGenOne (line 7165) | function isGenOne(changes) {
  function emitError (line 7171) | function emitError(db, e) {
  function tryCode (line 7184) | function tryCode(db, fun, args) {
  function sortByKeyThenValue (line 7197) | function sortByKeyThenValue(x, y) {
  function sliceResults (line 7202) | function sliceResults(results, limit, skip) {
  function rowToDocId (line 7212) | function rowToDocId(row) {
  function readAttachmentsAsBlobOrBuffer$1 (line 7220) | function readAttachmentsAsBlobOrBuffer$1(res) {
  function postprocessAttachments (line 7233) | function postprocessAttachments(opts) {
  function sumsqr (line 7254) | function sumsqr(values) {
  function addHttpParam (line 7272) | function addHttpParam(paramName, opts, params, asJson) {
  function coerceInteger (line 7283) | function coerceInteger(integerCandidate) {
  function coerceOptions (line 7295) | function coerceOptions(opts) {
  function checkPositiveInteger (line 7302) | function checkPositiveInteger(number) {
  function checkQueryParseError (line 7315) | function checkQueryParseError(options, fun) {
  function httpQuery (line 7341) | function httpQuery(db, fun, opts) {
  function customQuery (line 7424) | function customQuery(db, fun, opts) {
  function customViewCleanup (line 7438) | function customViewCleanup(db) {
  function defaultsTo (line 7449) | function defaultsTo(value) {
  function getDocsToPersist (line 7463) | function getDocsToPersist(docId, view, docIdsToChangesAndEmits) {
  function saveKeyValues (line 7540) | function saveKeyValues(view, docIdsToChangesAndEmits, seq) {
  function getQueue (line 7558) | function getQueue(view) {
  function updateView (line 7567) | function updateView(view) {
  function updateViewInQueue (line 7573) | function updateViewInQueue(view) {
  function reduceView (line 7678) | function reduceView(view, results, options) {
  function queryView (line 7734) | function queryView(view, opts) {
  function queryViewInQueue (line 7740) | function queryViewInQueue(view, opts) {
  function httpViewCleanup (line 7877) | function httpViewCleanup(db) {
  function localViewCleanup (line 7884) | function localViewCleanup(db) {
  function queryPromised (line 7946) | function queryPromised(db, fun, opts) {
  function isGenOne$1 (line 8042) | function isGenOne$1(rev) {
  function fileHasChanged (line 8046) | function fileHasChanged(localDoc, remoteDoc, filename) {
  function getDocAttachments (line 8052) | function getDocAttachments(db, doc) {
  function getDocAttachmentsFromTargetOrSource (line 8059) | function getDocAttachmentsFromTargetOrSource(target, src, doc) {
  function createBulkGetOpts (line 8085) | function createBulkGetOpts(diffs) {
  function getDocs (line 8109) | function getDocs(src, target, diffs, state) {
  function updateCheckpoint (line 8229) | function updateCheckpoint(db, id, checkpoint, session, returnValue) {
  function Checkpointer (line 8288) | function Checkpointer(src, target, id, returnValue) {
  function compareReplicationLogs (line 8394) | function compareReplicationLogs(srcDoc, tgtDoc) {
  function compareReplicationHistory (line 8405) | function compareReplicationHistory(sourceHistory, targetHistory) {
  function hasSessionId (line 8440) | function hasSessionId(sessionId, history) {
  function isForbiddenError (line 8455) | function isForbiddenError(err) {
  function backOff (line 8461) | function backOff(opts, returnValue, error, callback) {
  function sortObjectPropertiesByKey (line 8489) | function sortObjectPropertiesByKey(queryParams) {
  function generateReplicationId (line 8498) | function generateReplicationId(src, target, opts) {
  function replicate$1 (line 8527) | function replicate$1(src, target, opts, returnValue, result) {
  function Replication (line 8980) | function Replication() {
  function onDestroy (line 9013) | function onDestroy() {
  function cleanup (line 9018) | function cleanup() {
  function toPouch (line 9025) | function toPouch(db, opts) {
  function replicate (line 9034) | function replicate(src, target, opts, callback) {
  function sync (line 9063) | function sync(src, target, opts, callback) {
  function Sync (line 9079) | function Sync(src, target, opts, callback) {
  function replication (line 9265) | function replication(PouchDB) {

FILE: test/pouchdb/integration/test.all_docs.js
  function keyFunc (line 79) | function keyFunc(doc) {
  function paginate (line 616) | function paginate() {

FILE: test/pouchdb/integration/test.attachments.js
  function doneWithDoc (line 936) | function doneWithDoc() {
  function handleChange (line 943) | function handleChange(change) {
  function doneWithDoc (line 1047) | function doneWithDoc() {
  function handleChange (line 1054) | function handleChange(change) {
  function doneWithDoc (line 1108) | function doneWithDoc() {
  function handleChange (line 1115) | function handleChange(change) {
  function doneWithDoc (line 1167) | function doneWithDoc() {
  function handleChange (line 1174) | function handleChange(change) {
  function doneWithDoc (line 1222) | function doneWithDoc() {
  function handleChange (line 1229) | function handleChange(change) {
  function liveChangesPromise (line 1338) | function liveChangesPromise(opts) {
  function liveChangesPromise (line 1473) | function liveChangesPromise(opts) {
  function moreTests (line 1928) | function moreTests(rev) {
  function sort (line 2078) | function sort(a, b) {
  function checkAttachments (line 2419) | function checkAttachments() {
  function checkBlobType (line 3046) | function checkBlobType(blob, cb) {
  function getData (line 3114) | function getData(cb) {
  function isUnique (line 3869) | function isUnique(arr) {

FILE: test/pouchdb/integration/test.basics.js
  function writeAndDelete (line 602) | function writeAndDelete(cb) {
  function checkNumRevisions (line 910) | function checkNumRevisions(num) {
  function checkNumRevisions (line 940) | function checkNumRevisions(num) {

FILE: test/pouchdb/integration/test.bulk_docs.js
  function makeDocs (line 5) | function makeDocs(start, end, templateDoc) {
  function callback (line 769) | function callback(err, res) {
  function uuid (line 864) | function uuid() {
  function uuid (line 921) | function uuid() {
  function uuid (line 965) | function uuid() {

FILE: test/pouchdb/integration/test.changes.js
  function findById (line 15) | function findById(array, id) {
  function checkCount (line 929) | function checkCount() {
  function waitForDocPosted (line 983) | function waitForDocPosted() {
  function normalizeResult (line 1205) | function normalizeResult(result) {
  function getExpected (line 1369) | function getExpected(i) {
  function normalizeResult (line 1395) | function normalizeResult(result) {
  function getExpected (line 1492) | function getExpected(i) {
  function normalizeResult (line 1531) | function normalizeResult(result) {
  function normalizeResult (line 1652) | function normalizeResult(result) {
  function normalizeResult (line 1771) | function normalizeResult(result) {
  function checkDone (line 2276) | function checkDone() {
  function calldone (line 2427) | function calldone() {
  function maybeDone (line 2478) | function maybeDone() {
  function after (line 2484) | function after() {

FILE: test/pouchdb/integration/test.compaction.js
  function check (line 115) | function check(i) {
  function check (line 132) | function check(i) {
  function getRevisions (line 263) | function getRevisions(db, docId) {

FILE: test/pouchdb/integration/test.conflicts.js
  function addTask (line 484) | function addTask(batch) {

FILE: test/pouchdb/integration/test.events.js
  function checkDone (line 58) | function checkDone() {
  function destroyed (line 104) | function destroyed() {

FILE: test/pouchdb/integration/test.get.js
  function getDocWithDefault (line 374) | function getDocWithDefault(db, id, defaultDoc) {
  function getDocWithDefault (line 412) | function getDocWithDefault(db, id, defaultDoc) {

FILE: test/pouchdb/integration/test.issue1175.js
  function MockDatabase (line 2) | function MockDatabase(statusCodeToReturn, dataToReturn) {
  function getCallback (line 35) | function getCallback(expectError, done) {

FILE: test/pouchdb/integration/test.issue3179.js
  function waitForUptodate (line 113) | function waitForUptodate() {
  function waitForConflictsResolved (line 143) | function waitForConflictsResolved() {
  function cleanup (line 158) | function cleanup() {
  function waitForConflictsResolved (line 216) | function waitForConflictsResolved() {
  function waitForUptodate (line 231) | function waitForUptodate() {
  function cleanup (line 261) | function cleanup() {

FILE: test/pouchdb/integration/test.replication.js
  function simplifyChanges (line 40) | function simplifyChanges(res) {
  function verifyInfo (line 74) | function verifyInfo(info, expected) {
  function uuid (line 196) | function uuid() {
  function checkNumRevisions (line 277) | function checkNumRevisions(num) {
  function complete (line 539) | function complete(details) {
  function isFinished (line 560) | function isFinished() {
  function onChange (line 572) | function onChange() {
  function addConflict (line 661) | function addConflict(i) {
  function addConflict (line 712) | function addConflict(i) {
  function waitForChange (line 1815) | function waitForChange(db, fun) {
  function createConflicts (line 1984) | function createConflicts(db, callback) {
  function first_replicate (line 2148) | function first_replicate() {
  function second_replicate (line 2223) | function second_replicate() {
  function first_replicate (line 2316) | function first_replicate() {
  function second_replicate (line 2402) | function second_replicate() {
  function first_replicate (line 2504) | function first_replicate() {
  function second_replicate (line 2576) | function second_replicate() {
  function rebuildDocuments (line 3265) | function rebuildDocuments(db, docs, callback) {
  function bulkLoad (line 3284) | function bulkLoad(db, docs, callback) {
  function uuid (line 3569) | function uuid() {
  function timeoutPromise (line 4127) | function timeoutPromise(delay, fun) {
  function complete (line 4310) | function complete() {
  function change (line 4334) | function change() {
  function complete (line 4339) | function complete() {
  function paused (line 4346) | function paused() {

FILE: test/pouchdb/integration/test.replication_events.js
  function generateDocs (line 194) | function generateDocs(n) {
  function complete (line 204) | function complete() {
  function attachHandlers (line 289) | function attachHandlers(replication) {

FILE: test/pouchdb/integration/test.retry.js
  function cleanup (line 181) | function cleanup(err) {
  function finish (line 187) | function finish() {
  function cleanup (line 253) | function cleanup(err) {
  function finish (line 259) | function finish() {
  function cleanup (line 336) | function cleanup(err) {
  function finish (line 342) | function finish() {
  function cleanup (line 412) | function cleanup(err) {
  function finish (line 418) | function finish() {
  function cleanup (line 488) | function cleanup(err) {
  function finish (line 494) | function finish() {
  function getTotalListeners (line 500) | function getTotalListeners() {
  function replicatePromise (line 601) | function replicatePromise(fromDB, toDB) {

FILE: test/pouchdb/integration/test.revs_diff.js
  function createConflicts (line 86) | function createConflicts(db, callback) {
  function createDeletedRevision (line 109) | function createDeletedRevision(db, callback) {

FILE: test/pouchdb/integration/test.sync.js
  function syncThenCancel (line 383) | function syncThenCancel() {
  function changesCallback (line 471) | function changesCallback() {
  function otherCallback (line 497) | function otherCallback() {}
  function realCallback (line 498) | function realCallback() {
  function onChange (line 816) | function onChange() {

FILE: test/pouchdb/integration/test.uuids.js
  function makeUuids (line 5) | function makeUuids(count, length, radix) {

FILE: test/pouchdb/integration/utils-bundle.js
  function s (line 1) | function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&re...
  function argsArray (line 6) | function argsArray(fun) {
  function init (line 31) | function init () {
  function toByteArray (line 44) | function toByteArray (b64) {
  function tripletToBase64 (line 86) | function tripletToBase64 (num) {
  function encodeChunk (line 90) | function encodeChunk (uint8, start, end) {
  function fromByteArray (line 100) | function fromByteArray (uint8) {
  function typedArraySupport (line 187) | function typedArraySupport () {
  function kMaxLength (line 199) | function kMaxLength () {
  function createBuffer (line 205) | function createBuffer (that, length) {
  function Buffer (line 234) | function Buffer (arg, encodingOrOffset, length) {
  function from (line 259) | function from (that, value, encodingOrOffset, length) {
  function assertSize (line 300) | function assertSize (size) {
  function alloc (line 308) | function alloc (that, size, fill, encoding) {
  function allocUnsafe (line 332) | function allocUnsafe (that, size) {
  function fromString (line 356) | function fromString (that, string, encoding) {
  function fromArrayLike (line 380) | function fromArrayLike (that, array) {
  function fromArrayBuffer (line 389) | function fromArrayBuffer (that, array, byteOffset, length) {
  function fromObject (line 419) | function fromObject (that, obj) {
  function checked (line 449) | function checked (length) {
  function SlowBuffer (line 459) | function SlowBuffer (length) {
  function byteLength (line 542) | function byteLength (string, encoding) {
  function slowToString (line 587) | function slowToString (encoding, start, end) {
  function swap (line 661) | function swap (b, n, m) {
  function bidirectionalIndexOf (line 795) | function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
  function arrayIndexOf (line 852) | function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
  function hexWrite (line 920) | function hexWrite (buf, string, offset, length) {
  function utf8Write (line 947) | function utf8Write (buf, string, offset, length) {
  function asciiWrite (line 951) | function asciiWrite (buf, string, offset, length) {
  function latin1Write (line 955) | function latin1Write (buf, string, offset, length) {
  function base64Write (line 959) | function base64Write (buf, string, offset, length) {
  function ucs2Write (line 963) | function ucs2Write (buf, string, offset, length) {
  function base64Slice (line 1046) | function base64Slice (buf, start, end) {
  function utf8Slice (line 1054) | function utf8Slice (buf, start, end) {
  function decodeCodePointsArray (line 1132) | function decodeCodePointsArray (codePoints) {
  function asciiSlice (line 1150) | function asciiSlice (buf, start, end) {
  function latin1Slice (line 1160) | function latin1Slice (buf, start, end) {
  function hexSlice (line 1170) | function hexSlice (buf, start, end) {
  function utf16leSlice (line 1183) | function utf16leSlice (buf, start, end) {
  function checkOffset (line 1231) | function checkOffset (offset, ext, length) {
  function checkInt (line 1392) | function checkInt (buf, value, offset, ext, max, min) {
  function objectWriteUInt16 (line 1445) | function objectWriteUInt16 (buf, value, offset, littleEndian) {
  function objectWriteUInt32 (line 1479) | function objectWriteUInt32 (buf, value, offset, littleEndian) {
  function checkIEEE754 (line 1629) | function checkIEEE754 (buf, value, offset, ext, max, min) {
  function writeFloat (line 1634) | function writeFloat (buf, value, offset, littleEndian, noAssert) {
  function writeDouble (line 1650) | function writeDouble (buf, value, offset, littleEndian, noAssert) {
  function base64clean (line 1783) | function base64clean (str) {
  function stringtrim (line 1795) | function stringtrim (str) {
  function toHex (line 1800) | function toHex (n) {
  function utf8ToBytes (line 1805) | function utf8ToBytes (string, units) {
  function asciiToBytes (line 1885) | function asciiToBytes (str) {
  function utf16leToBytes (line 1894) | function utf16leToBytes (str, units) {
  function base64ToBytes (line 1910) | function base64ToBytes (str) {
  function blitBuffer (line 1914) | function blitBuffer (src, dst, offset, length) {
  function isnan (line 1922) | function isnan (val) {
  function useColors (line 1967) | function useColors() {
  function formatArgs (line 1992) | function formatArgs() {
  function log (line 2034) | function log() {
  function save (line 2049) | function save(namespaces) {
  function load (line 2066) | function load() {
  function localstorage (line 2091) | function localstorage(){
  function selectColor (line 2147) | function selectColor() {
  function debug (line 2159) | function debug(namespace) {
  function enable (line 2233) | function enable(namespaces) {
  function disable (line 2256) | function disable() {
  function enabled (line 2268) | function enabled(name) {
  function coerce (line 2291) | function coerce(val) {
  function EventEmitter (line 2536) | function EventEmitter() {
  function g (line 2674) | function g() {
  function isFunction (line 2802) | function isFunction(arg) {
  function isNumber (line 2806) | function isNumber(arg) {
  function isObject (line 2810) | function isObject(arg) {
  function isUndefined (line 2814) | function isUndefined(arg) {
  function nextTick (line 2953) | function nextTick() {
  function immediate (line 2970) | function immediate(task) {
  function INTERNAL (line 3049) | function INTERNAL() {}
  function Promise (line 3059) | function Promise(resolver) {
  function QueueItem (line 3089) | function QueueItem(promise, onFulfilled, onRejected) {
  function unwrap (line 3113) | function unwrap(promise, func, value) {
  function getThen (line 3160) | function getThen(obj) {
  function safelyResolveThenable (line 3170) | function safelyResolveThenable(self, thenable) {
  function tryCatch (line 3199) | function tryCatch(func, value) {
  function resolve (line 3212) | function resolve(value) {
  function reject (line 3220) | function reject(reason) {
  function all (line 3226) | function all(iterable) {
  function race (line 3265) | function race(iterable) {
  function mkdirP (line 3307) | function mkdirP (p, opts, f, made) {
  function parse (line 3441) | function parse(str) {
  function short (line 3494) | function short(ms) {
  function long (line 3510) | function long(ms) {
  function plural (line 3522) | function plural(ms, n, name) {
  function normalizeArray (line 3555) | function normalizeArray(parts, allowAboveRoot) {
  function trim (line 3664) | function trim(arr) {
  function filter (line 3737) | function filter (xs, f) {
  function defaultSetTimout (line 3768) | function defaultSetTimout() {
  function defaultClearTimeout (line 3771) | function defaultClearTimeout () {
  function runTimeout (line 3794) | function runTimeout(fun) {
  function runClearTimeout (line 3819) | function runClearTimeout(marker) {
  function cleanUpNextTick (line 3851) | function cleanUpNextTick() {
  function drainQueue (line 3866) | function drainQueue() {
  function Item (line 3904) | function Item(fun, array) {
  function noop (line 3918) | function noop() {}
  function cmn (line 4005) | function cmn(q, a, b, x, s, t) {
  function ff (line 4010) | function ff(a, b, c, d, x, s, t) {
  function gg (line 4014) | function gg(a, b, c, d, x, s, t) {
  function hh (line 4018) | function hh(a, b, c, d, x, s, t) {
  function ii (line 4022) | function ii(a, b, c, d, x, s, t) {
  function md5cycle (line 4026) | function md5cycle(x, k) {
  function md5blk (line 4106) | function md5blk(s) {
  function md5blk_array (line 4116) | function md5blk_array(a) {
  function md51 (line 4126) | function md51(s) {
  function md51_array (line 4166) | function md51_array(a) {
  function rhex (line 4214) | function rhex(n) {
  function hex (line 4223) | function hex(x) {
  function clamp (line 4250) | function clamp(val, length) {
  function toUtf8 (line 4295) | function toUtf8(str) {
  function utf8Str2ArrayBuffer (line 4303) | function utf8Str2ArrayBuffer(str, returnUInt8Array) {
  function arrayBuffer2Utf8Str (line 4316) | function arrayBuffer2Utf8Str(buff) {
  function concatenateArrayBuffers (line 4320) | function concatenateArrayBuffers(first, second, returnUInt8Array) {
  function hexToBinaryString (line 4329) | function hexToBinaryString(hex) {
  function SparkMD5 (line 4350) | function SparkMD5() {
  function pop (line 4723) | function pop(obj, stack, metaStack) {
  function _interopDefault (line 4846) | function _interopDefault (ex) { return (ex && (typeof ex === 'object') &...
  function mangle (line 4863) | function mangle(key) {
  function unmangle (line 4866) | function unmangle(key) {
  function _Map (line 4869) | function _Map() {
  function _Set (line 4901) | function _Set(array) {
  function isBinaryObject (line 4918) | function isBinaryObject(object) {
  function cloneArrayBuffer (line 4923) | function cloneArrayBuffer(buff) {
  function cloneBinaryObject (line 4935) | function cloneBinaryObject(object) {
  function isPlainObject (line 4956) | function isPlainObject(value) {
  function clone (line 4967) | function clone(object) {
  function once (line 5011) | function once(fun) {
  function toPromise (line 5025) | function toPromise(func) {
  function adapterFun (line 5077) | function adapterFun(name, callback) {
  function pick (line 5125) | function pick(obj, arr) {
  function identityFunction (line 5141) | function identityFunction(x) {
  function formatResultForOpenRevsGet (line 5145) | function formatResultForOpenRevsGet(result) {
  function bulkGet (line 5152) | function bulkGet(db, opts, callback) {
  function isChromeApp (line 5264) | function isChromeApp() {
  function hasLocalStorage (line 5283) | function hasLocalStorage() {
  function attachBrowserEvents (line 5290) | function attachBrowserEvents(self) {
  function Changes$1 (line 5312) | function Changes$1() {
  function eventFunction (line 5325) | function eventFunction() {
  function guardedConsole (line 5390) | function guardedConsole(method) {
  function randomNumber (line 5398) | function randomNumber(min, max) {
  function defaultBackOff (line 5418) | function defaultBackOff(min) {
  function explainError (line 5428) | function explainError(status, str) {
  function PouchError (line 5434) | function PouchError(opts) {
  function createError (line 5594) | function createError(error, reason) {
  function generateErrorFromResponse (line 5613) | function generateErrorFromResponse(err) {
  function tryFilter (line 5641) | function tryFilter(filter, doc, req) {
  function filterChange (line 5650) | function filterChange(opts) {
  function flatten (line 5686) | function flatten(arrs) {
  function invalidIdError (line 5699) | function invalidIdError(id) {
  function listenerCount (line 5713) | function listenerCount(ee, type) {
  function parseDesignDocFunctionName (line 5718) | function parseDesignDocFunctionName(s) {
  function normalizeDesignDocFunctionName (line 5732) | function normalizeDesignDocFunctionName(s) {
  function parseUri (line 5749) | function parseUri(str) {
  function upsert (line 5774) | function upsert(db, docId, diffFun) {
  function tryAndPut (line 5804) | function tryAndPut(db, doc, diffFun) {
  function getValue (line 5859) | function getValue(radix) {
  function uuid (line 5862) | function uuid(len, radix) {
  function winningRev (line 5901) | function winningRev(metadata) {
  function traverseRevTree (line 5935) | function traverseRevTree(revs, callback) {
  function sortByPos (line 5951) | function sortByPos(a, b) {
  function collectLeaves (line 5955) | function collectLeaves(revs) {
  function collectConflicts (line 5972) | function collectConflicts(metadata) {
  function compactTree (line 5987) | function compactTree(metadata) {
  function rootToLeaf (line 6000) | function rootToLeaf(revs) {
  function sortByPos$1 (line 6035) | function sortByPos$1(a, b) {
  function binarySearch (line 6040) | function binarySearch(arr, item, comparator) {
  function insertSorted (line 6056) | function insertSorted(arr, item, comparator) {
  function pathToTree (line 6064) | function pathToTree(path, numStemmed) {
  function compareTree (line 6081) | function compareTree(a, b) {
  function mergeTree (line 6087) | function mergeTree(in_tree1, in_tree2) {
  function doMerge (line 6124) | function doMerge(tree, path, dontExpand) {
  function stem (line 6206) | function stem(tree, depth) {
  function merge (line 6248) | function merge(tree, path, depth) {
  function revExists (line 6259) | function revExists(revs, rev) {
  function getTrees (line 6278) | function getTrees(node) {
  function isDeleted (line 6285) | function isDeleted(metadata, rev) {
  function isLocalId (line 6301) | function isLocalId(id) {
  function evalFilter (line 6305) | function evalFilter(input) {
  function evalView (line 6309) | function evalView(input) {
  function tryCatchInChangeListener (line 6330) | function tryCatchInChangeListener(self, change) {
  function Changes (line 6339) | function Changes(db, opts, callback) {
  function processChange (line 6415) | function processChange(doc, metadata, opts) {
  function compare (line 6564) | function compare(left, right) {
  function arrayFirst (line 6569) | function arrayFirst(arr, callback) {
  function yankError (line 6579) | function yankError(callback) {
  function cleanDocs (line 6590) | function cleanDocs(docs) {
  function compareByIdThenRev (line 6608) | function compareByIdThenRev(a, b) {
  function computeHeight (line 6620) | function computeHeight(revs) {
  function allDocsKeysQuery (line 6645) | function allDocsKeysQuery(api, opts, callback) {
  function doNextCompaction (line 6681) | function doNextCompaction(self) {
  function attachmentNameError (line 6708) | function attachmentNameError(name) {
  function AbstractPouchDB (line 6718) | function AbstractPouchDB() {
  function createAttachment (line 6774) | function createAttachment(doc) {
  function addToMissing (line 6877) | function addToMissing(id, revId) {
  function processDoc (line 6884) | function processDoc(id, rev_tree) {
  function onChange (line 7000) | function onChange(row) {
  function onComplete (line 7003) | function onComplete(resp) {
  function finishOpenRevs (line 7038) | function finishOpenRevs() {
  function diffFun (line 7355) | function diffFun(doc) {
  function destroyDb (line 7380) | function destroyDb() {
  function TaskQueue (line 7419) | function TaskQueue() {
  function parseAdapter (line 7456) | function parseAdapter(name, opts) {
  function prepareForDestruction (line 7511) | function prepareForDestruction(self) {
  function PouchDB (line 7534) | function PouchDB(name, opts) {
  function setUpEventEmitter (line 7601) | function setUpEventEmitter(Pouch) {
  function PouchAlt (line 7645) | function PouchAlt(name, opts) {
  function toObject (line 7679) | function toObject(array) {
  function parseRevisionInfo (line 7718) | function parseRevisionInfo(rev) {
  function makeRevTreeFromRevisions (line 7731) | function makeRevTreeFromRevisions(revisions, opts) {
  function parseDoc (line 7749) | function parseDoc(doc, newEdits) {
  function createBlob (line 7835) | function createBlob(parts, properties) {
  function binaryStringToArrayBuffer (line 7859) | function binaryStringToArrayBuffer(bin) {
  function binStringToBluffer (line 7869) | function binStringToBluffer(binString, type) {
  function b64ToBluffer (line 7873) | function b64ToBluffer(b64, type) {
  function arrayBufferToBinaryString (line 7880) | function arrayBufferToBinaryString(buffer) {
  function readAsBinaryString (line 7891) | function readAsBinaryString(blob, callback) {
  function blobToBinaryString (line 7915) | function blobToBinaryString(blobOrBuffer, callback) {
  function blobToBase64 (line 7921) | function blobToBase64(blobOrBuffer, callback) {
  function readAsArrayBuffer (line 7928) | function readAsArrayBuffer(blob, callback) {
  function rawToBase64 (line 7946) | function rawToBase64(raw) {
  function sliceBlob (line 7950) | function sliceBlob(blob, start, end) {
  function appendBlob (line 7957) | function appendBlob(buffer, blob, start, end, callback) {
  function appendString (line 7968) | function appendString(buffer, string, start, end, callback) {
  function binaryMd5 (line 7977) | function binaryMd5(data, callback) {
  function stringMd5 (line 8011) | function stringMd5(string) {
  function parseBase64 (line 8015) | function parseBase64(data) {
  function preprocessString (line 8025) | function preprocessString(att, blobType, callback) {
  function preprocessBlob (line 8045) | function preprocessBlob(att, blobType, callback) {
  function preprocessAttachment (line 8066) | function preprocessAttachment(att, blobType, callback) {
  function preprocessAttachments (line 8077) | function preprocessAttachments(docInfos, blobType, callback) {
  function updateDoc (line 8123) | function updateDoc(revLimit, prev, docInfo, results,
  function rootIsMissing (line 8188) | function rootIsMissing(docInfo) {
  function processDocs (line 8192) | function processDocs(revLimit, docInfos, api, fetchedDocs, tx, results,
  function slowJsonParse (line 8311) | function slowJsonParse(str) {
  function safeJsonParse (line 8320) | function safeJsonParse(str) {
  function safeJsonStringify (line 8336) | function safeJsonStringify(json) {
  function tryCode (line 8345) | function tryCode(fun, that, args, PouchDB) {
  function applyNext (line 8361) | function applyNext(PouchDB) {
  function idbError (line 8376) | function idbError(callback) {
  function encodeMetadata (line 8393) | function encodeMetadata(metadata, winningRev, deleted) {
  function decodeMetadata (line 8403) | function decodeMetadata(storedObject) {
  function decodeDoc (line 8416) | function decodeDoc(doc) {
  function readBlobData (line 8430) | function readBlobData(body, type, asBlob, callback) {
  function fetchAttachmentsIfNecessary (line 8452) | function fetchAttachmentsIfNecessary(doc, opts, txn, cb) {
  function postProcessAttachments (line 8489) | function postProcessAttachments(results, asBlob) {
  function compactRevs (line 8514) | function compactRevs(revs, docId, txn) {
  function openTransactionSafely (line 8575) | function openTransactionSafely(idb, stores, mode) {
  function idbBulkDocs (line 8587) | function idbBulkDocs(dbOpts, req, opts, api, idb, idbChanges, callback) {
  function createKeyRange (line 8932) | function createKeyRange(start, end, inclusiveEnd, key, descending) {
  function handleKeyRangeError (line 8961) | function handleKeyRangeError(api, opts, err, callback) {
  function idbAllDocs (line 8973) | function idbAllDocs(opts, api, idb, callback) {
  function checkBlobSupport (line 9110) | function checkBlobSupport(txn) {
  function IdbPouch (line 9141) | function IdbPouch(opts, callback) {
  function init (line 9153) | function init(api, opts, callback) {
  function tryStorageOption (line 10073) | function tryStorageOption(dbName, storage) {
  function IDBPouch (line 10084) | function IDBPouch (PouchDB) {
  function decodeUtf8 (line 10099) | function decodeUtf8(str) {
  function hexToInt (line 10103) | function hexToInt(charCode) {
  function parseHexUtf8 (line 10115) | function parseHexUtf8(str, start, end) {
  function parseHexUtf16 (line 10130) | function parseHexUtf16(str, start, end) {
  function parseHexString (line 10144) | function parseHexString(str, encoding) {
  function quote (line 10152) | function quote(str) {
  function escapeBlob (line 10177) | function escapeBlob(str) {
  function unescapeBlob (line 10184) | function unescapeBlob(str) {
  function stringifyDoc (line 10191) | function stringifyDoc(doc) {
  function unstringifyDoc (line 10199) | function unstringifyDoc(doc, id, rev) {
  function qMarks (line 10207) | function qMarks(num) {
  function select (line 10218) | function select(selector, table, joiner, where, orderBy) {
  function compactRevs$1 (line 10227) | function compactRevs$1(revs, docId, tx) {
  function websqlError (line 10310) | function websqlError(callback) {
  function getSize (line 10322) | function getSize(opts) {
  function websqlBulkDocs (line 10339) | function websqlBulkDocs(dbOpts, req, opts, api, db, websqlChanges, callb...
  function openDatabaseWithOpts (line 10646) | function openDatabaseWithOpts(opts) {
  function openDBSafely (line 10650) | function openDBSafely(opts) {
  function openDB$1 (line 10662) | function openDB$1(opts) {
  function fetchAttachmentsIfNecessary$1 (line 10673) | function fetchAttachmentsIfNecessary$1(doc, opts, api, txn, cb) {
  function WebSqlPouch$1 (line 10736) | function WebSqlPouch$1(opts, callback) {
  function canOpenTestDB (line 11656) | function canOpenTestDB() {
  function isValidWebSQL (line 11669) | function isValidWebSQL() {
  function valid (line 11705) | function valid() {
  function openDB (line 11712) | function openDB(name, version, description, size) {
  function WebSQLPouch (line 11717) | function WebSQLPouch(opts, callback) {
  function WebSqlPouch (line 11729) | function WebSqlPouch (PouchDB) {
  function wrappedFetch (line 11735) | function wrappedFetch() {
  function fetchRequest (line 11762) | function fetchRequest(options, callback) {
  function xhRequest (line 11835) | function xhRequest(options, callback) {
  function testXhr (line 11967) | function testXhr() {
  function ajax$1 (line 11978) | function ajax$1(options, callback) {
  function defaultBody (line 11989) | function defaultBody() {
  function ajaxCore (line 11993) | function ajaxCore(options, callback) {
  function ajax (line 12081) | function ajax(opts, callback) {
  function readAttachmentsAsBlobOrBuffer (line 12117) | function readAttachmentsAsBlobOrBuffer(row) {
  function encodeDocId (line 12128) | function encodeDocId(id) {
  function preprocessAttachments$1 (line 12138) | function preprocessAttachments$1(doc) {
  function hasUrlPrefix (line 12155) | function hasUrlPrefix(opts) {
  function getHost (line 12167) | function getHost(name, opts) {
  function genDBUrl (line 12203) | function genDBUrl(opts, path) {
  function genUrl (line 12208) | function genUrl(opts, path) {
  function paramsToStr (line 12220) | function paramsToStr(params) {
  function HttpPouch (line 12227) | function HttpPouch(opts, callback) {
  function HttpPouch$1 (line 13076) | function HttpPouch$1 (PouchDB) {
  function pad (line 13081) | function pad(str, padWith, upToLength) {
  function padLeft (line 13091) | function padLeft(str, padWith, upToLength) {
  function collate (line 13100) | function collate(a, b) {
  function normalizeKey (line 13130) | function normalizeKey(key) {
  function indexify (line 13165) | function indexify(key) {
  function toIndexableString (line 13208) | function toIndexableString(key) {
  function parseNumber (line 13214) | function parseNumber(str, i) {
  function pop (line 13265) | function pop(stack, metaStack) {
  function parseIndexableString (line 13288) | function parseIndexableString(str) {
  function arrayCollate (line 13354) | function arrayCollate(a, b) {
  function stringCollate (line 13365) | function stringCollate(a, b) {
  function objectCollate (line 13371) | function objectCollate(a, b) {
  function collationIndex (line 13394) | function collationIndex(x) {
  function numToIndexableString (line 13418) | function numToIndexableString(num) {
  function TaskQueue$1 (line 13462) | function TaskQueue$1() {
  function createView (line 13477) | function createView(opts) {
  function evalfunc (line 13554) | function evalfunc(func, emit, sum, log, isArray, toJSON) {
  function parseViewName (line 13640) | function parseViewName(name) {
  function isGenOne (line 13646) | function isGenOne(changes) {
  function emitError (line 13652) | function emitError(db, e) {
  function tryCode$1 (line 13665) | function tryCode$1(db, fun, args) {
  function sortByKeyThenValue (line 13678) | function sortByKeyThenValue(x, y) {
  function sliceResults (line 13683) | function sliceResults(results, limit, skip) {
  function rowToDocId (line 13693) | function rowToDocId(row) {
  function readAttachmentsAsBlobOrBuffer$1 (line 13701) | function readAttachmentsAsBlobOrBuffer$1(res) {
  function postprocessAttachments (line 13714) | function postprocessAttachments(opts) {
  function createBuiltInError (line 13723) | function createBuiltInError(name) {
  function sum (line 13730) | function sum(values) {
  function sumsqr (line 13772) | function sumsqr(values) {
  function addHttpParam (line 13790) | function addHttpParam(paramName, opts, params, asJson) {
  function coerceInteger (line 13801) | function coerceInteger(integerCandidate) {
  function coerceOptions (line 13813) | function coerceOptions(opts) {
  function checkPositiveInteger (line 13820) | function checkPositiveInteger(number) {
  function checkQueryParseError (line 13833) | function checkQueryParseError(options, fun) {
  function httpQuery (line 13859) | function httpQuery(db, fun, opts) {
  function customQuery (line 13942) | function customQuery(db, fun, opts) {
  function customViewCleanup (line 13956) | function customViewCleanup(db) {
  function defaultsTo (line 13967) | function defaultsTo(value) {
  function getDocsToPersist (line 13981) | function getDocsToPersist(docId, view, docIdsToChangesAndEmits) {
  function saveKeyValues (line 14058) | function saveKeyValues(view, docIdsToChangesAndEmits, seq) {
  function getQueue (line 14076) | function getQueue(view) {
  function updateView (line 14085) | function updateView(view) {
  function updateViewInQueue (line 14091) | function updateViewInQueue(view) {
  function reduceView (line 14197) | function reduceView(view, results, options) {
  function queryView (line 14254) | function queryView(view, opts) {
  function queryViewInQueue (line 14260) | function queryViewInQueue(view, opts) {
  function httpViewCleanup (line 14397) | function httpViewCleanup(db) {
  function localViewCleanup (line 14404) | function localViewCleanup(db) {
  function queryPromised (line 14466) | function queryPromised(db, fun, opts) {
  function QueryParseError (line 14556) | function QueryParseError(message) {
  function NotFoundError (line 14568) | function NotFoundError(message) {
  function BuiltInError (line 14580) | function BuiltInError(message) {
  function isGenOne$1 (line 14597) | function isGenOne$1(rev) {
  function fileHasChanged (line 14601) | function fileHasChanged(localDoc, remoteDoc, filename) {
  function getDocAttachments (line 14607) | function getDocAttachments(db, doc) {
  function getDocAttachmentsFromTargetOrSource (line 14614) | function getDocAttachmentsFromTargetOrSource(target, src, doc) {
  function createBulkGetOpts (line 14640) | function createBulkGetOpts(diffs) {
  function getDocs (line 14664) | function getDocs(src, target, diffs, state) {
  function updateCheckpoint (line 14779) | function updateCheckpoint(db, id, checkpoint, session, returnValue) {
  function Checkpointer (line 14838) | function Checkpointer(src, target, id, returnValue) {
  function compareReplicationLogs (line 14944) | function compareReplicationLogs(srcDoc, tgtDoc) {
  function compareReplicationHistory (line 14955) | function compareReplicationHistory(sourceHistory, targetHistory) {
  function hasSessionId (line 14990) | function hasSessionId(sessionId, history) {
  function isForbiddenError (line 15005) | function isForbiddenError(err) {
  function backOff (line 15011) | function backOff(opts, returnValue, error, callback) {
  function sortObjectPropertiesByKey (line 15039) | function sortObjectPropertiesByKey(queryParams) {
  function generateReplicationId (line 15048) | function generateReplicationId(src, target, opts) {
  function replicate$1 (line 15077) | function replicate$1(src, target, opts, returnValue, result) {
  function Replication (line 15530) | function Replication() {
  function onDestroy (line 15563) | function onDestroy() {
  function cleanup (line 15568) | function cleanup() {
  function toPouch (line 15575) | function toPouch(db, opts) {
  function replicate (line 15584) | function replicate(src, target, opts, callback) {
  function sync (line 15613) | function sync(src, target, opts, callback) {
  function Sync (line 15629) | function Sync(src, target, opts, callback) {
  function replication (line 15815) | function replication(PouchDB) {
  function _interopDefault (line 15920) | function _interopDefault (ex) { return (ex && (typeof ex === 'object') &...
  function mangle (line 15937) | function mangle(key) {
  function unmangle (line 15940) | function unmangle(key) {
  function _Map (line 15943) | function _Map() {
  function _Set (line 15975) | function _Set(array) {
  function isBinaryObject (line 15992) | function isBinaryObject(object) {
  function cloneArrayBuffer (line 15997) | function cloneArrayBuffer(buff) {
  function cloneBinaryObject (line 16009) | function cloneBinaryObject(object) {
  function isPlainObject (line 16030) | function isPlainObject(value) {
  function clone (line 16041) | function clone(object) {
  function once (line 16085) | function once(fun) {
  function toPromise (line 16099) | function toPromise(func) {
  function adapterFun (line 16151) | function adapterFun(name, callback) {
  function pick (line 16199) | function pick(obj, arr) {
  function identityFunction (line 16215) | function identityFunction(x) {
  function formatResultForOpenRevsGet (line 16219) | function formatResultForOpenRevsGet(result) {
  function bulkGet (line 16226) | function bulkGet(db, opts, callback) {
  function isChromeApp (line 16338) | function isChromeApp() {
  function hasLocalStorage (line 16357) | function hasLocalStorage() {
  function attachBrowserEvents (line 16364) | function attachBrowserEvents(self) {
  function Changes$1 (line 16386) | function Changes$1() {
  function eventFunction (line 16399) | function eventFunction() {
  function guardedConsole (line 16464) | function guardedConsole(method) {
  function randomNumber (line 16472) | function randomNumber(min, max) {
  function defaultBackOff (line 16492) | function defaultBackOff(min) {
  function explainError (line 16502) | function explainError(status, str) {
  function PouchError (line 16508) | function PouchError(opts) {
  function createError (line 16668) | function createError(error, reason) {
  function generateErrorFromResponse (line 16687) | function generateErrorFromResponse(err) {
  function tryFilter (line 16715) | function tryFilter(filter, doc, req) {
  function filterChange (line 16724) | function filterChange(opts) {
  function flatten (line 16760) | function flatten(arrs) {
  function invalidIdError (line 16773) | function invalidIdError(id) {
  function listenerCount (line 16787) | function listenerCount(ee, type) {
  function parseDesignDocFunctionName (line 16792) | function parseDesignDocFunctionName(s) {
  function normalizeDesignDocFunctionName (line 16806) | function normalizeDesignDocFunctionName(s) {
  function parseUri (line 16823) | function parseUri(str) {
  function upsert (line 16848) | function upsert(db, docId, diffFun) {
  function tryAndPut (line 16878) | function tryAndPut(db, doc, diffFun) {
  function getValue (line 16933) | function getValue(radix) {
  function uuid (line 16936) | function uuid(len, radix) {
  function winningRev (line 16975) | function winningRev(metadata) {
  function traverseRevTree (line 17009) | function traverseRevTree(revs, callback) {
  function sortByPos (line 17025) | function sortByPos(a, b) {
  function collectLeaves (line 17029) | function collectLeaves(revs) {
  function collectConflicts (line 17046) | function collectConflicts(metadata) {
  function compactTree (line 17061) | function compactTree(metadata) {
  function rootToLeaf (line 17074) | function rootToLeaf(revs) {
  function sortByPos$1 (line 17109) | function sortByPos$1(a, b) {
  function binarySearch (line 17114) | function binarySearch(arr, item, comparator) {
  function insertSorted (line 17130) | function insertSorted(arr, item, comparator) {
  function pathToTree (line 17138) | function pathToTree(path, numStemmed) {
  function compareTree (line 17155) | function compareTree(a, b) {
  function mergeTree (line 17161) | function mergeTree(in_tree1, in_tree2) {
  function doMerge (line 17198) | function doMerge(tree, path, dontExpand) {
  function stem (line 17280) | function stem(tree, depth) {
  function merge (line 17322) | function merge(tree, path, depth) {
  function revExists (line 17333) | function revExists(revs, rev) {
  function getTrees (line 17352) | function getTrees(node) {
  function isDeleted (line 17359) | function isDeleted(metadata, rev) {
  function isLocalId (line 17375) | function isLocalId(id) {
  function evalFilter (line 17379) | function evalFilter(input) {
  function evalView (line 17383) | function evalView(input) {
  function tryCatchInChangeListener (line 17404) | function tryCatchInChangeListener(self, change) {
  function Changes (line 17413) | function Changes(db, opts, callback) {
  function processChange (line 17489) | function processChange(doc, metadata, opts) {
  function compare (line 17638) | function compare(left, right) {
  function arrayFirst (line 17643) | function arrayFirst(arr, callback) {
  function yankError (line 17653) | function yankError(callback) {
  function cleanDocs (line 17664) | function cleanDocs(docs) {
  function compareByIdThenRev (line 17682) | function compareByIdThenRev(a, b) {
  function computeHeight (line 17694) | function computeHeight(revs) {
  function allDocsKeysQuery (line 17719) | function allDocsKeysQuery(api, opts, callback) {
  function doNextCompaction (line 17755) | function doNextCompaction(self) {
  function attachmentNameError (line 17782) | function attachmentNameError(name) {
  function AbstractPouchDB (line 17792) | function AbstractPouchDB() {
  function createAttachment (line 17848) | function createAttachment(doc) {
  function addToMissing (line 17951) | function addToMissing(id, revId) {
  function processDoc (line 17958) | function processDoc(id, rev_tree) {
  function onChange (line 18074) | function onChange(row) {
  function onComplete (line 18077) | function onComplete(resp) {
  function finishOpenRevs (line 18112) | function finishOpenRevs() {
  function diffFun (line 18429) | function diffFun(doc) {
  function destroyDb (line 18454) | function destroyDb() {
  function TaskQueue (line 18493) | function TaskQueue() {
  function parseAdapter (line 18530) | function parseAdapter(name, opts) {
  function prepareForDestruction (line 18585) | function prepareForDestruction(self) {
  function PouchDB (line 18608) | function PouchDB(name, opts) {
  function setUpEventEmitter (line 18675) | function setUpEventEmitter(Pouch) {
  function PouchAlt (line 18719) | function PouchAlt(name, opts) {
  function toObject (line 18753) | function toObject(array) {
  function parseRevisionInfo (line 18792) | function parseRevisionInfo(rev) {
  function makeRevTreeFromRevisions (line 18805) | function makeRevTreeFromRevisions(revisions, opts) {
  function parseDoc (line 18823) | function parseDoc(doc, newEdits) {
  function createBlob (line 18909) | function createBlob(parts, properties) {
  function binaryStringToArrayBuffer (line 18933) | function binaryStringToArrayBuffer(bin) {
  function binStringToBluffer (line 18943) | function binStringToBluffer(binString, type) {
  function b64ToBluffer (line 18947) | function b64ToBluffer(b64, type) {
  function arrayBufferToBinaryString (line 18954) | function arrayBufferToBinaryString(buffer) {
  function readAsBinaryString (line 18965) | function readAsBinaryString(blob, callback) {
  function blobToBinaryString (line 18989) | function blobToBinaryString(blobOrBuffer, callback) {
  function blobToBase64 (line 18995) | function blobToBase64(blobOrBuffer, callback) {
  function readAsArrayBuffer (line 19002) | function readAsArrayBuffer(blob, callback) {
  function rawToBase64 (line 19020) | function rawToBase64(raw) {
  function sliceBlob (line 19024) | function sliceBlob(blob, start, end) {
  function appendBlob (line 19031) | function appendBlob(buffer, blob, start, end, callback) {
  function appendString (line 19042) | function appendString(buffer, string, start, end, callback) {
  function binaryMd5 (line 19051) | function binaryMd5(data, callback) {
  function stringMd5 (line 19085) | function stringMd5(string) {
  function parseBase64 (line 19089) | function parseBase64(data) {
  function preprocessString (line 19099) | function preprocessString(att, blobType, callback) {
  function preprocessBlob (line 19119) | function preprocessBlob(att, blobType, callback) {
  function preprocessAttachment (line 19140) | function preprocessAttachment(att, blobType, callback) {
  function preprocessAttachments (line 19151) | function preprocessAttachments(docInfos, blobType, callback) {
  function updateDoc (line 19197) | function updateDoc(revLimit, prev, docInfo, results,
  function rootIsMissing (line 19262) | function rootIsMissing(docInfo) {
  function processDocs (line 19266) | function processDocs(revLimit, docInfos, api, fetchedDocs, tx, results,
  function slowJsonParse (line 19385) | function slowJsonParse(str) {
  function safeJsonParse (line 19394) | function safeJsonParse(str) {
  function safeJsonStringify (line 19410) | function safeJsonStringify(json) {
  function tryCode (line 19419) | function tryCode(fun, that, args, PouchDB) {
  function applyNext (line 19435) | function applyNext(PouchDB) {
  function idbError (line 19450) | function idbError(callback) {
  function encodeMetadata (line 19467) | function encodeMetadata(metadata, winningRev, deleted) {
  function decodeMetadata (line 19477) | function decodeMetadata(storedObject) {
  function decodeDoc (line 19490) | function decodeDoc(doc) {
  function readBlobData (line 19504) | function readBlobData(body, type, asBlob, callback) {
  function fetchAttachmentsIfNecessary (line 19526) | function fetchAttachmentsIfNecessary(doc, opts, txn, cb) {
  function postProcessAttachments (line 19563) | function postProcessAttachments(results, asBlob) {
  function compactRevs (line 19588) | function compactRevs(revs, docId, txn) {
  function openTransactionSafely (line 19649) | function openTransactionSafely(idb, stores, mode) {
  function idbBulkDocs (line 19661) | function idbBulkDocs(dbOpts, req, opts, api, idb, idbChanges, callback) {
  function createKeyRange (line 20006) | function createKeyRange(start, end, inclusiveEnd, key, descending) {
  function handleKeyRangeError (line 20035) | function handleKeyRangeError(api, opts, err, callback) {
  function idbAllDocs (line 20047) | function idbAllDocs(opts, api, idb, callback) {
  function checkBlobSupport (line 20184) | function checkBlobSupport(txn) {
  function IdbPouch (line 20215) | function IdbPouch(opts, callback) {
  function init (line 20227) | function init(api, opts, callback) {
  function tryStorageOption (line 21147) | function tryStorageOption(dbName, storage) {
  function IDBPouch (line 21158) | function IDBPouch (PouchDB) {
  function decodeUtf8 (line 21173) | function decodeUtf8(str) {
  function hexToInt (line 21177) | function hexToInt(charCode) {
  function parseHexUtf8 (line 21189) | function parseHexUtf8(str, start, end) {
  function parseHexUtf16 (line 21204) | function parseHexUtf16(str, start, end) {
  function parseHexString (line 21218) | function parseHexString(str, encoding) {
  function quote (line 21226) | function quote(str) {
  function escapeBlob (line 21251) | function escapeBlob(str) {
  function unescapeBlob (line 21258) | function unescapeBlob(str) {
  function stringifyDoc (line 21265) | function stringifyDoc(doc) {
  function unstringifyDoc (line 21273) | function unstringifyDoc(doc, id, rev) {
  function qMarks (line 21281) | function qMarks(num) {
  function select (line 21292) | function select(selector, table, joiner, where, orderBy) {
  function compactRevs$1 (line 21301) | function compactRevs$1(revs, docId, tx) {
  function websqlError (line 21384) | function websqlError(callback) {
  function getSize (line 21396) | function getSize(opts) {
  function websqlBulkDocs (line 21413) | function websqlBulkDocs(dbOpts, req, opts, api, db, websqlChanges, callb...
  function openDatabaseWithOpts (line 21720) | function openDatabaseWithOpts(opts) {
  function openDBSafely (line 21724) | function openDBSafely(opts) {
  function openDB$1 (line 21736) | function openDB$1(opts) {
  function fetchAttachmentsIfNecessary$1 (line 21747) | function fetchAttachmentsIfNecessary$1(doc, opts, api, txn, cb) {
  function WebSqlPouch$1 (line 21810) | function WebSqlPouch$1(opts, callback) {
  function canOpenTestDB (line 22730) | function canOpenTestDB() {
  function isValidWebSQL (line 22743) | function isValidWebSQL() {
  function valid (line 22779) | function valid() {
  function openDB (line 22786) | function openDB(name, version, description, size) {
  function WebSQLPouch (line 22791) | function WebSQLPouch(opts, callback) {
  function WebSqlPouch (line 22803) | function WebSqlPouch (PouchDB) {
  function wrappedFetch (line 22809) | function wrappedFetch() {
  function fetchRequest (line 22836) | function fetchRequest(options, callback) {
  function xhRequest (line 22909) | function xhRequest(options, callback) {
  function testXhr (line 23041) | function testXhr() {
  function ajax$1 (line 23052) | function ajax$1(options, callback) {
  function defaultBody (line 23063) | function defaultBody() {
  function ajaxCore (line 23067) | function ajaxCore(options, callback) {
  function ajax (line 23155) | function ajax(opts, callback) {
  function readAttachmentsAsBlobOrBuffer (line 23191) | function readAttachmentsAsBlobOrBuffer(row) {
  function encodeDocId (line 23202) | function encodeDocId(id) {
  function preprocessAttachments$1 (line 23212) | function preprocessAttachments$1(doc) {
  function hasUrlPrefix (line 23229) | function hasUrlPrefix(opts) {
  function getHost (line 23241) | function getHost(name, opts) {
  function genDBUrl (line 23277) | function genDBUrl(opts, path) {
  function genUrl (line 23282) | function genUrl(opts, path) {
  function paramsToStr (line 23294) | function paramsToStr(params) {
  function HttpPouch (line 23301) | function HttpPouch(opts, callback) {
  function HttpPouch$1 (line 24150) | function HttpPouch$1 (PouchDB) {
  function pad (line 24155) | function pad(str, padWith, upToLength) {
  function padLeft (line 24165) | function padLeft(str, padWith, upToLength) {
  function collate (line 24174) | function collate(a, b) {
  function normalizeKey (line 24204) | function normalizeKey(key) {
  function indexify (line 24239) | function indexify(key) {
  function toIndexableString (line 24282) | function toIndexableString(key) {
  function parseNumber (line 24288) | function parseNumber(str, i) {
  function pop (line 24339) | function pop(stack, metaStack) {
  function parseIndexableString (line 24362) | function parseIndexableString(str) {
  function arrayCollate (line 24428) | function arrayCollate(a, b) {
  function stringCollate (line 24439) | function stringCollate(a, b) {
  function objectCollate (line 24445) | function objectCollate(a, b) {
  function collationIndex (line 24468) | function collationIndex(x) {
  function numToIndexableString (line 24492) | function numToIndexableString(num) {
  function TaskQueue$1 (line 24536) | function TaskQueue$1() {
  function createView (line 24551) | function createView(opts) {
  function evalfunc (line 24628) | function evalfunc(func, emit, sum, log, isArray, toJSON) {
  function parseViewName (line 24714) | function parseViewName(name) {
  function isGenOne (line 24720) | function isGenOne(changes) {
  function emitError (line 24726) | function emitError(db, e) {
  function tryCode$1 (line 24739) | function tryCode$1(db, fun, args) {
  function sortByKeyThenValue (line 24752) | function sortByKeyThenValue(x, y) {
  function sliceResults (line 24757) | function sliceResults(results, limit, skip) {
  function rowToDocId (line 24767) | function rowToDocId(row) {
  function readAttachmentsAsBlobOrBuffer$1 (line 24775) | function readAttachmentsAsBlobOrBuffer$1(res) {
  function postprocessAttachments (line 24788) | function postprocessAttachments(opts) {
  function createBuiltInError (line 24797) | function createBuiltInError(name) {
  function sum (line 24804) | function sum(values) {
  function sumsqr (line 24846) | function sumsqr(values) {
  function addHttpParam (line 24864) | function addHttpParam(paramName, opts, params, asJson) {
  function coerceInteger (line 24875) | function coerceInteger(integerCandidate) {
  function coerceOptions (line 24887) | function coerceOptions(opts) {
  function checkPositiveInteger (line 24894) | function checkPositiveInteger(number) {
  function checkQueryParseError (line 24907) | function checkQueryParseError(options, fun) {
  function httpQuery (line 24933) | function httpQuery(db, fun, opts) {
  function customQuery (line 25016) | function customQuery(db, fun, opts) {
  function customViewCleanup (line 25030) | function customViewCleanup(db) {
  function defaultsTo (line 25041) | function defaultsTo(value) {
  function getDocsToPersist (line 25055) | function getDocsToPersist(docId, view, docIdsToChangesAndEmits) {
  function saveKeyValues (line 25132) | function saveKeyValues(view, docIdsToChangesAndEmits, seq) {
  function getQueue (line 25150) | function getQueue(view) {
  function updateView (line 25159) | function updateView(view) {
  function updateViewInQueue (line 25165) | function updateViewInQueue(view) {
  function reduceView (line 25271) | function reduceView(view, results, options) {
  function queryView (line 25328) | function queryView(view, opts) {
  function queryViewInQueue (line 25334) | function queryViewInQueue(view, opts) {
  function httpViewCleanup (line 25471) | function httpViewCleanup(db) {
  function localViewCleanup (line 25478) | function localViewCleanup(db) {
  function queryPromised (line 25540) | function queryPromised(db, fun, opts) {
  function QueryParseError (line 25630) | function QueryParseError(message) {
  function NotFoundError (line 25642) | function NotFoundError(message) {
  function BuiltInError (line 25654) | function BuiltInError(message) {
  function isGenOne$1 (line 25671) | function isGenOne$1(rev) {
  function fileHasChanged (line 25675) | function fileHasChanged(localDoc, remoteDoc, filename) {
  function getDocAttachments (line 25681) | function getDocAttachments(db, doc) {
  function getDocAttachmentsFromTargetOrSource (line 25688) | function getDocAttachmentsFromTargetOrSource(target, src, doc) {
  function createBulkGetOpts (line 25714) | function createBulkGetOpts(diffs) {
  function getDocs (line 25738) | function getDocs(src, target, diffs, state) {
  function updateCheckpoint (line 25853) | function updateCheckpoint(db, id, checkpoint, session, returnValue) {
  function Checkpointer (line 25912) | function Checkpointer(src, target, id, returnValue) {
  function compareReplicationLogs (line 26018) | function compareReplicationLogs(srcDoc, tgtDoc) {
  function compareReplicationHistory (line 26029) | function compareReplicationHistory(sourceHistory, targetHistory) {
  function hasSessionId (line 26064) | function hasSessionId(sessionId, history) {
  function isForbiddenError (line 26079) | function isForbiddenError(err) {
  function backOff (line 26085) | function backOff(opts, returnValue, error, callback) {
  function sortObjectPropertiesByKey (line 26113) | function sortObjectPropertiesByKey(queryParams) {
  function generateReplicationId (line 26122) | function generateReplicationId(src, target, opts) {
  function replicate$1 (line 26151) | function replicate$1(src, target, opts, returnValue, result) {
  function Replication (line 26604) | function Replication() {
  function onDestroy (line 26637) | function onDestroy() {
  function cleanup (line 26642) | function cleanup() {
  function toPouch (line 26649) | function toPouch(db, opts) {
  function replicate (line 26658) | function replicate(src, target, opts, callback) {
  function sync (line 26687) | function sync(src, target, opts, callback) {
  function Sync (line 26703) | function Sync(src, target, opts, callback) {
  function replication (line 26889) | function replication(PouchDB) {
  function uniq (line 26929) | function uniq(list) {
  function insert (line 27071) | function insert(i) {
  function insert (line 27095) | function insert(i) {

FILE: test/pouchdb/integration/utils.js
  function uniq (line 8) | function uniq(list) {
  function insert (line 157) | function insert(i) {
  function insert (line 181) | function insert(i) {

FILE: test/pouchdb/mapreduce/test.mapreduce.js
  function tests (line 17) | function tests(suiteName, dbName, dbType, viewType) {

FILE: test/pouchdb/mapreduce/test.persisted.js
  function tests (line 13) | function tests(suiteName, dbName, dbType) {
Condensed preview — 86 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (3,998K chars).
[
  {
    "path": ".gitignore",
    "chars": 77,
    "preview": "node_modules\n.DS_Store\n*~\ncoverage\ntest/test-bundle.js\nnpm-debug.log\ntestdb*\n"
  },
  {
    "path": ".jshintrc",
    "chars": 518,
    "preview": "{\r\n  \"curly\": true,\r\n  \"eqeqeq\": true,\r\n  \"immed\": true,\r\n  \"newcap\": true,\r\n  \"noarg\": true,\r\n  \"sub\": true,\r\n  \"undef\""
  },
  {
    "path": ".npmignore",
    "chars": 63,
    "preview": ".git*\nnode_modules\n.DS_Store\n*~\ncoverage\nnpm-debug.log\nvendor/\n"
  },
  {
    "path": ".travis.yml",
    "chars": 431,
    "preview": "language: node_js\n\nservices:\n  - couchdb\n\nnode_js:\n  - \"5\"\nsudo: false\naddons:\n  firefox: \"41.0.1\"\nscript: npm run $COMM"
  },
  {
    "path": "LICENSE",
    "chars": 11189,
    "preview": "\n                                Apache License\n                          Version 2.0, January 2004\n                    "
  },
  {
    "path": "README.md",
    "chars": 7880,
    "preview": "socket-pouch [![Build Status](https://travis-ci.org/nolanlawson/socket-pouch.svg)](https://travis-ci.org/nolanlawson/soc"
  },
  {
    "path": "bin/dev-server.js",
    "chars": 2386,
    "preview": "#!/usr/bin/env node\n\n'use strict';\n\nvar COUCH_HOST = process.env.COUCH_HOST || 'http://127.0.0.1:5984';\nvar HTTP_PORT = "
  },
  {
    "path": "bin/es3ify.js",
    "chars": 124,
    "preview": "#!/usr/bin/env node\n'use strict';\nvar es3ify = require('es3ify');\nreturn process.stdin.pipe(es3ify()).pipe(process.stdou"
  },
  {
    "path": "bin/run-test.sh",
    "chars": 122,
    "preview": "#!/bin/bash\n\n: ${CLIENT:=\"node\"}\n\nif [ \"$CLIENT\" == \"node\" ]; then\n    npm run test-node\nelse\n    npm run test-browser\nf"
  },
  {
    "path": "bin/test-browser.js",
    "chars": 3657,
    "preview": "#!/usr/bin/env node\n'use strict';\n\nvar wd = require('wd');\nvar sauceConnectLauncher = require('sauce-connect-launcher');"
  },
  {
    "path": "bin/test-node.sh",
    "chars": 630,
    "preview": "#!/usr/bin/env bash\n\n: ${TIMEOUT:=50000}\n: ${REPORTER:=\"spec\"}\n\nnode ./bin/dev-server.js &\nexport DEV_SERVER_PID=$!\n\nsle"
  },
  {
    "path": "client/index.js",
    "chars": 57,
    "preview": "'use strict';\n\nmodule.exports = require('../lib/client');"
  },
  {
    "path": "dist/socket-pouch.client.js",
    "chars": 182091,
    "preview": "(function(f){if(typeof exports===\"object\"&&typeof module!==\"undefined\"){module.exports=f()}else if(typeof define===\"func"
  },
  {
    "path": "lib/client/arrayBufferToBinaryString.js",
    "chars": 410,
    "preview": "'use strict';\n\n//Can't find original post, but this is close\n//http://stackoverflow.com/questions/6965107/ (continues on"
  },
  {
    "path": "lib/client/base64.js",
    "chars": 784,
    "preview": "'use strict';\n\nvar buffer = require('../shared/buffer');\n\n/* istanbul ignore if */\nif (typeof atob === 'function') {\n  e"
  },
  {
    "path": "lib/client/base64StringToBlobOrBuffer-browser.js",
    "chars": 186,
    "preview": "'use strict';\n\nvar binaryStringToBlobOrBuffer = require('./binaryStringToBlobOrBuffer');\n\nmodule.exports = function (b64"
  },
  {
    "path": "lib/client/base64StringToBlobOrBuffer.js",
    "chars": 145,
    "preview": "'use strict';\n\nvar typedBuffer = require('./typedBuffer');\n\nmodule.exports = function (b64, type) {\n  return typedBuffer"
  },
  {
    "path": "lib/client/binaryStringToArrayBuffer.js",
    "chars": 374,
    "preview": "'use strict';\n\n// From http://stackoverflow.com/questions/14967647/ (continues on next line)\n// encode-decode-image-with"
  },
  {
    "path": "lib/client/binaryStringToBlobOrBuffer-browser.js",
    "chars": 247,
    "preview": "'use strict';\n\nvar createBlob = require('./blob');\nvar binaryStringToArrayBuffer = require('./binaryStringToArrayBuffer'"
  },
  {
    "path": "lib/client/binaryStringToBlobOrBuffer.js",
    "chars": 157,
    "preview": "'use strict';\n\nvar typedBuffer = require('./typedBuffer');\n\nmodule.exports = function (binString, type) {\n  return typed"
  },
  {
    "path": "lib/client/blob.js",
    "chars": 934,
    "preview": "\"use strict\";\n\n// Abstracts constructing a Blob object, so it also works in older\n// browsers that don't support the nat"
  },
  {
    "path": "lib/client/index.js",
    "chars": 18334,
    "preview": "'use strict';\n\nvar utils = require('../shared/utils');\nvar clientUtils = require('./utils');\nvar uuid = require('./../sh"
  },
  {
    "path": "lib/client/readAsArrayBuffer.js",
    "chars": 304,
    "preview": "'use strict';\n\n// simplified API. universal browser support is assumed\nmodule.exports = function (blob, callback) {\n  va"
  },
  {
    "path": "lib/client/readAsBinaryString-browser.js",
    "chars": 591,
    "preview": "'use strict';\n\nvar arrayBufferToBinaryString = require('./arrayBufferToBinaryString');\n\n// shim for browsers that don't "
  },
  {
    "path": "lib/client/readAsBinaryString.js",
    "chars": 144,
    "preview": "'use strict';\n\nmodule.exports = function (buffer, callback) {\n  process.nextTick(function () {\n    callback(buffer.toStr"
  },
  {
    "path": "lib/client/typedBuffer.js",
    "chars": 325,
    "preview": "'use strict';\n\nvar buffer = require('../shared/buffer');\n\nfunction typedBuffer(binString, buffType, type) {\n  // buffTyp"
  },
  {
    "path": "lib/client/utils.js",
    "chars": 3199,
    "preview": "'use strict';\n\nvar utils = require('../shared/utils');\nvar log = require('debug')('pouchdb:socket:client');\nvar isBrowse"
  },
  {
    "path": "lib/server/index.js",
    "chars": 9193,
    "preview": "'use strict';\n\nvar engine = require('engine.io');\nvar Promise = require('bluebird');\nvar uuid = require('../shared/uuid'"
  },
  {
    "path": "lib/server/make-pouch-creator.js",
    "chars": 1258,
    "preview": "'use strict';\n\nvar PouchDB = require('pouchdb');\nvar Promise = require('bluebird');\n\nfunction createLocalPouch(args) {\n\n"
  },
  {
    "path": "lib/server/safe-eval.js",
    "chars": 305,
    "preview": "'use strict';\n\nvar log = require('debug')('pouchdb:socket:server');\n\n// TODO: this is evil and insecure\nmodule.exports ="
  },
  {
    "path": "lib/server/utils.js",
    "chars": 669,
    "preview": "'use strict';\n\n// mostly borrowed from express-pouchb's utils.sendError()\nexports.createError = function (err) {\n  var s"
  },
  {
    "path": "lib/shared/buffer-browser.js",
    "chars": 73,
    "preview": "// hey guess what, we don't need this in the browser\nmodule.exports = {};"
  },
  {
    "path": "lib/shared/buffer.js",
    "chars": 80,
    "preview": "//this solely exists so we can exclude it in browserify\nmodule.exports = Buffer;"
  },
  {
    "path": "lib/shared/cloneBinaryObject-browser.js",
    "chars": 704,
    "preview": "'use strict';\n\nfunction cloneArrayBuffer(buff) {\n  if (typeof buff.slice === 'function') {\n    return buff.slice(0);\n  }"
  },
  {
    "path": "lib/shared/cloneBinaryObject.js",
    "chars": 147,
    "preview": "'use strict';\n\nmodule.exports = function cloneBinaryObject(object) {\n  var copy = new Buffer(object.length);\n  object.co"
  },
  {
    "path": "lib/shared/errors.js",
    "chars": 6141,
    "preview": "\"use strict\";\n\nvar inherits = require('inherits');\ninherits(PouchError, Error);\n\nfunction PouchError(opts) {\n  Error.cal"
  },
  {
    "path": "lib/shared/isBinaryObject-browser.js",
    "chars": 171,
    "preview": "'use strict';\n\nmodule.exports = function isBinaryObject(object) {\n  return object instanceof ArrayBuffer ||\n    (typeof "
  },
  {
    "path": "lib/shared/isBinaryObject.js",
    "chars": 103,
    "preview": "'use strict';\n\nmodule.exports = function isBinaryObject(object) {\n  return object instanceof Buffer;\n};"
  },
  {
    "path": "lib/shared/parse-message.js",
    "chars": 282,
    "preview": "'use strict';\n\nfunction parseMessage(msg, numArgs) {\n  var res = [];\n  for (var i = 0; i < numArgs - 1; i++) {\n    var i"
  },
  {
    "path": "lib/shared/pouchdb-clone.js",
    "chars": 962,
    "preview": "'use strict';\n\nvar isBinaryObject = require('./isBinaryObject');\nvar cloneBinaryObject = require('./cloneBinaryObject');"
  },
  {
    "path": "lib/shared/utils.js",
    "chars": 3365,
    "preview": "'use strict';\n\nvar Promise = require('pouchdb-promise');\nvar buffer = require('./buffer');\n\nexports.lastIndexOf = functi"
  },
  {
    "path": "lib/shared/uuid.js",
    "chars": 1805,
    "preview": "\"use strict\";\n\n// BEGIN Math.uuid.js\n\n/*!\n Math.uuid.js (v1.4)\n http://www.broofa.com\n mailto:robert@broofa.com\n\n Copyri"
  },
  {
    "path": "package.json",
    "chars": 2768,
    "preview": "{\n  \"name\": \"socket-pouch\",\n  \"version\": \"2.0.0\",\n  \"description\": \"PouchDB over websockets\",\n  \"main\": \"server/index.js"
  },
  {
    "path": "server/index.js",
    "chars": 57,
    "preview": "'use strict';\n\nmodule.exports = require('../lib/server');"
  },
  {
    "path": "test/bind-polyfill.js",
    "chars": 921,
    "preview": "(function () {\n  'use strict';\n  // minimal polyfill for phantomjs; in the future, we should do ES5_SHIM=true like pouch"
  },
  {
    "path": "test/deps/bigimage.js",
    "chars": 904217,
    "preview": "(function () {\n  'use strict';\n\n  var bigimage = \"iVBORw0KGgoAAAANSUhEUgAABZEAAAugCAYAAAB/rnaTAAAABmJLR0QA/wD/AP+gvaeTAA"
  },
  {
    "path": "test/index.html",
    "chars": 2848,
    "preview": "<!doctype html>\n<html>\n<head>\n  <meta charset=\"utf-8\">\n  <title>Mocha</title>\n  <link rel=\"stylesheet\" type=\"text/css\" h"
  },
  {
    "path": "test/node.setup.js",
    "chars": 526,
    "preview": "/*jshint expr:true */\n'use strict';\n\nvar SocketPouch = require('../lib/client');\n\nglobal.PouchDB = require('pouchdb')\n  "
  },
  {
    "path": "test/pouchdb/integration/deps/bigimage.js",
    "chars": 904217,
    "preview": "(function () {\n  'use strict';\n\n  var bigimage = \"iVBORw0KGgoAAAANSUhEUgAABZEAAAugCAYAAAB/rnaTAAAABmJLR0QA/wD/AP+gvaeTAA"
  },
  {
    "path": "test/pouchdb/integration/pouchdb-for-coverage.js",
    "chars": 254549,
    "preview": "'use strict';\n\nfunction _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'"
  },
  {
    "path": "test/pouchdb/integration/test.aa.setup.js",
    "chars": 827,
    "preview": "'use strict';\ndescribe('DB Setup', function () {\n  it('we can find CouchDB with admin credentials', function (done) {\n  "
  },
  {
    "path": "test/pouchdb/integration/test.all_docs.js",
    "chars": 24344,
    "preview": "'use strict';\n\nvar adapters = ['http', 'local'];\n\nadapters.forEach(function (adapter) {\n  describe('test.all_docs.js-' +"
  },
  {
    "path": "test/pouchdb/integration/test.attachments.js",
    "chars": 137120,
    "preview": "'use strict';\n\nvar adapters = ['local', 'http'];\nvar repl_adapters = [\n  ['local', 'http'],\n  ['http', 'http'],\n  ['http"
  },
  {
    "path": "test/pouchdb/integration/test.basics.js",
    "chars": 32911,
    "preview": "'use strict';\n\nvar adapters = ['http', 'local'];\n\nadapters.forEach(function (adapter) {\n\n  describe('test.basics.js-' + "
  },
  {
    "path": "test/pouchdb/integration/test.bulk_docs.js",
    "chars": 31206,
    "preview": "'use strict';\n\nvar adapters = ['local', 'http'];\n\nfunction makeDocs(start, end, templateDoc) {\n  var templateDocSrc = te"
  },
  {
    "path": "test/pouchdb/integration/test.bulk_get.js",
    "chars": 5068,
    "preview": "'use strict';\n\nvar adapters = ['http', 'local'];\n\nadapters.forEach(function (adapter) {\n  describe('test.bulk_get.js-' +"
  },
  {
    "path": "test/pouchdb/integration/test.changes.js",
    "chars": 75846,
    "preview": "\n'use strict';\n\nvar adapters = ['http', 'local'];\n\nadapters.forEach(function (adapter) {\n\n  describe('test.changes.js-' "
  },
  {
    "path": "test/pouchdb/integration/test.compaction.js",
    "chars": 64478,
    "preview": "'use strict';\n\nvar adapters = ['http', 'local'];\nvar autoCompactionAdapters = ['local'];\n\nadapters.forEach(function (ada"
  },
  {
    "path": "test/pouchdb/integration/test.conflicts.js",
    "chars": 15412,
    "preview": "'use strict';\n\nvar adapters = ['http', 'local'];\n\nadapters.forEach(function (adapter) {\n  describe('test.conflicts.js-' "
  },
  {
    "path": "test/pouchdb/integration/test.constructor.js",
    "chars": 957,
    "preview": "'use strict';\n\ndescribe('constructor errors', function () {\n\n  it('should error on an undefined name', function (done) {"
  },
  {
    "path": "test/pouchdb/integration/test.design_docs.js",
    "chars": 3465,
    "preview": "'use strict';\n\nvar adapters = ['http', 'local'];\n\nadapters.forEach(function (adapter) {\n  describe('test.design_docs.js-"
  },
  {
    "path": "test/pouchdb/integration/test.events.js",
    "chars": 3177,
    "preview": "'use strict';\n\nvar adapters = ['local', 'http'];\n\nadapters.forEach(function (adapter) {\n  describe('test.events.js-' + a"
  },
  {
    "path": "test/pouchdb/integration/test.get.js",
    "chars": 22752,
    "preview": "'use strict';\n\nvar adapters = ['http', 'local'];\n\nadapters.forEach(function (adapter) {\n  describe('test.get.js-' + adap"
  },
  {
    "path": "test/pouchdb/integration/test.http.js",
    "chars": 5151,
    "preview": "'use strict';\n\ndescribe('test.http.js', function () {\n\n  var dbs = {};\n\n  beforeEach(function (done) {\n    dbs.name = te"
  },
  {
    "path": "test/pouchdb/integration/test.issue1175.js",
    "chars": 3381,
    "preview": "'use strict';\nfunction MockDatabase(statusCodeToReturn, dataToReturn) {\n  this.once = this.removeListener = function () "
  },
  {
    "path": "test/pouchdb/integration/test.issue221.js",
    "chars": 2477,
    "preview": "'use strict';\n\nvar adapters = [\n  ['local', 'http'],\n  ['http', 'http'],\n  ['http', 'local'],\n  ['local', 'local']\n];\n\na"
  },
  {
    "path": "test/pouchdb/integration/test.issue3179.js",
    "chars": 10070,
    "preview": "'use strict';\n\nvar adapters = [\n  ['http', 'http'],\n  ['http', 'local'],\n  ['local', 'http'],\n  ['local', 'local']\n];\n\ni"
  },
  {
    "path": "test/pouchdb/integration/test.issue3646.js",
    "chars": 7688,
    "preview": "'use strict';\n\nvar adapters = ['local', 'http'];\n\nadapters.forEach(function (adapter) {\n  describe('test.issue3646.js- '"
  },
  {
    "path": "test/pouchdb/integration/test.local_docs.js",
    "chars": 6327,
    "preview": "'use strict';\n\nvar adapters = ['http', 'local'];\n\nadapters.forEach(function (adapter) {\n  describe('test.local_docs.js-'"
  },
  {
    "path": "test/pouchdb/integration/test.replication.js",
    "chars": 141265,
    "preview": "'use strict';\n\nvar adapters = [\n  ['local', 'http'],\n  ['http', 'http'],\n  ['http', 'local'],\n  ['local', 'local']\n];\n\ni"
  },
  {
    "path": "test/pouchdb/integration/test.replication_events.js",
    "chars": 11114,
    "preview": "'use strict';\n\nvar adapters = [\n  ['local', 'http'],\n  ['http', 'http'],\n  ['http', 'local'],\n  ['local', 'local']\n];\n\ni"
  },
  {
    "path": "test/pouchdb/integration/test.reserved.js",
    "chars": 2351,
    "preview": "'use strict';\n\nvar adapters = [\n  ['local', 'http'],\n  ['http', 'http'],\n  ['http', 'local'],\n  ['local', 'local']\n];\n\na"
  },
  {
    "path": "test/pouchdb/integration/test.retry.js",
    "chars": 17597,
    "preview": "'use strict';\n\nvar adapters = [\n  ['local', 'http'],\n  ['http', 'http'],\n  ['http', 'local'],\n  ['local', 'local']\n];\n\ni"
  },
  {
    "path": "test/pouchdb/integration/test.revs_diff.js",
    "chars": 4993,
    "preview": "'use strict';\n\nvar adapters = ['http', 'local'];\n\nadapters.forEach(function (adapter) {\n  describe('test.revs_diff.js-' "
  },
  {
    "path": "test/pouchdb/integration/test.slash_id.js",
    "chars": 4410,
    "preview": "'use strict';\n\nvar adapters = ['local', 'http'];\nvar repl_adapters = [\n  ['local', 'http'],\n  ['http', 'http'],\n  ['http"
  },
  {
    "path": "test/pouchdb/integration/test.sync.js",
    "chars": 24658,
    "preview": "'use strict';\n\nvar adapters = [\n  ['local', 'http'],\n  ['http', 'http'],\n  ['http', 'local'],\n  ['local', 'local']\n];\n\ni"
  },
  {
    "path": "test/pouchdb/integration/test.sync_events.js",
    "chars": 1769,
    "preview": "'use strict';\n\nvar adapters = [\n  ['local', 'http'],\n  ['http', 'http'],\n  ['http', 'local'],\n  ['local', 'local']\n];\n\ni"
  },
  {
    "path": "test/pouchdb/integration/test.taskqueue.js",
    "chars": 1762,
    "preview": "'use strict';\n\nvar adapters = ['http', 'local'];\n\nadapters.forEach(function (adapter) {\n  describe('test.taskqueue.js-' "
  },
  {
    "path": "test/pouchdb/integration/test.uuids.js",
    "chars": 2072,
    "preview": "'use strict';\n/* jshint maxlen: false */\nvar rfcRegexp = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-["
  },
  {
    "path": "test/pouchdb/integration/utils-bundle.js",
    "chars": 754283,
    "preview": "(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)"
  },
  {
    "path": "test/pouchdb/integration/utils.js",
    "chars": 8831,
    "preview": "/* global PouchDB */\n/* jshint -W079 */\n'use strict';\n\nvar path = require('path');\nvar testUtils = {};\n\nfunction uniq(li"
  },
  {
    "path": "test/pouchdb/mapreduce/test.mapreduce.js",
    "chars": 113639,
    "preview": "/* global sum */\n'use strict';\n\nvar adapters = ['local', 'http'];\n\nadapters.forEach(function (adapter) {\n\n  var viewType"
  },
  {
    "path": "test/pouchdb/mapreduce/test.persisted.js",
    "chars": 22492,
    "preview": "'use strict';\n\nvar adapters = ['local', 'http'];\n\nadapters.forEach(function (adapter) {\n\n  var suiteName = 'test.persist"
  },
  {
    "path": "test/pouchdb/mapreduce/test.views.js",
    "chars": 18955,
    "preview": "/*jshint expr:true */\n'use strict';\n\nvar adapters = [\n  ['local', 'http']\n];\n\nadapters.forEach(function (adapters) {\n  d"
  },
  {
    "path": "test/test.js",
    "chars": 333,
    "preview": "/*jshint expr:true */\n'use strict';\n\nvar SocketPouch = require('../lib/client');\n\nwindow.PouchDB = require('pouchdb')\n  "
  },
  {
    "path": "test/webrunner.js",
    "chars": 629,
    "preview": "/* global mocha: true */\n\n(function () {\n  'use strict';\n  var runner = mocha.run();\n  window.results = {\n    browser: n"
  }
]

About this extraction

This page contains the full source code of the nolanlawson/socket-pouch GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 86 files (3.7 MB), approximately 982.7k tokens, and a symbol index with 1174 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!