master 9b5fe1a9caff cached
77 files
1.4 MB
436.3k tokens
1173 symbols
1 requests
Download .txt
Showing preview only (1,494K chars total). Download the full file or copy to clipboard to get everything.
Repository: ionic-team/rollup-plugin-node-polyfills
Branch: master
Commit: 9b5fe1a9caff
Files: 77
Total size: 1.4 MB

Directory structure:
gitextract_csbhc0ta/

├── .gitignore
├── LICENSE.md
├── browser-test/
│   ├── index.js
│   └── main.js
├── package.json
├── polyfills/
│   ├── LICENSE-browserify-fs.txt
│   ├── LICENSE-buffer-es6.txt
│   ├── LICENSE-crypto-browserify.txt
│   ├── LICENSE-process-es6.txt
│   ├── assert.js
│   ├── browserify-fs.js
│   ├── buffer-es6.js
│   ├── console.js
│   ├── constants.js
│   ├── crypto-browserify.js
│   ├── domain.js
│   ├── empty.js
│   ├── events.js
│   ├── global.js
│   ├── http-lib/
│   │   ├── capability.js
│   │   ├── request.js
│   │   ├── response.js
│   │   └── to-arraybuffer.js
│   ├── http.js
│   ├── inherits.js
│   ├── os.js
│   ├── path.js
│   ├── process-es6.js
│   ├── punycode.js
│   ├── qs.js
│   ├── readable-stream/
│   │   ├── buffer-list.js
│   │   ├── duplex.js
│   │   ├── passthrough.js
│   │   ├── readable.js
│   │   ├── transform.js
│   │   └── writable.js
│   ├── setimmediate.js
│   ├── stream.js
│   ├── string-decoder.js
│   ├── timers.js
│   ├── tty.js
│   ├── url.js
│   ├── util.js
│   ├── vm.js
│   ├── zlib-lib/
│   │   ├── LICENSE
│   │   ├── adler32.js
│   │   ├── binding.js
│   │   ├── crc32.js
│   │   ├── deflate.js
│   │   ├── inffast.js
│   │   ├── inflate.js
│   │   ├── inftrees.js
│   │   ├── messages.js
│   │   ├── trees.js
│   │   ├── utils.js
│   │   └── zstream.js
│   └── zlib.js
├── readme.md
├── rollup.config.js
├── scripts/
│   ├── build-constants.js
│   └── build-polyfills.js
├── src/
│   ├── index.ts
│   └── modules.ts
├── test/
│   ├── examples/
│   │   ├── assert.js
│   │   ├── constants.js
│   │   ├── crypto.js
│   │   ├── domain.js
│   │   ├── events.js
│   │   ├── os.js
│   │   ├── path.js
│   │   ├── stream.js
│   │   ├── string-decoder.js
│   │   ├── url-format.js
│   │   ├── url-parse.js
│   │   └── zlib.js
│   └── index.js
└── tsconfig.json

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

================================================
FILE: .gitignore
================================================
dist
dist-transpiled
node_modules


================================================
FILE: LICENSE.md
================================================
The MIT License (MIT)

Copyright (c) 2019 these people

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

================================================
FILE: browser-test/index.js
================================================
var rollup = require( 'rollup' );
var nodePolyfills = require('..');
rollup.rollup({
  input: 'browser-test/main.js',
  plugins: [
    nodePolyfills(),
  ]
}).then( function ( bundle ) {
  return bundle.write({
    format: 'iife',
    file: 'browser-test/dist/bundle.js'
  });
}).then(function () {
  console.log('done');
  process.exit();
}).catch(function (e) {
  console.log('oh noes!');
  console.log(e);
  process.exit(1);
});


================================================
FILE: browser-test/main.js
================================================
import {get} from 'http';
import {createContext, runInContext} from 'vm';
import {equal, deepEqual} from 'assert';

get('foo.json', function (res) {
  console.log('status', res.statusCode);
  var data = '';
  res.on('data', function (d) {
    data += d.toString();
  }).on('error', function (e) {
    console.log('error', e);
  }).on('end', function () {
    console.log(data);
    if (global.document) {
      afterMain();
    } else {
      afterWorker();
    }
  });
})
function afterMain() {
  var context = createContext();

  runInContext('var x = 1', context);
  deepEqual(context, { x: 1 });

  runInContext('var y = 2;', context);
  var x = runInContext('++x', context);
  equal(x, 2);
  equal(context.x, 2);
  equal(context.x, context.y);
  console.log('ok main');
}
function afterWorker() {
  var context = createContext({x: 0});

  runInContext('x++', context);
  deepEqual(context, { x: 1 });

  var x = runInContext('++x', context);
  equal(x, 2);
  equal(context.x, 2);
  console.log('ok worker');
}


================================================
FILE: package.json
================================================
{
  "name": "rollup-plugin-node-polyfills",
  "version": "0.2.1",
  "main": "dist/index.js",
  "module": "dist/index.mjs",
  "types": "dist/types/index.d.ts",
  "scripts": {
    "pretest": "npm run build",
    "test": "mocha",
    "prebuild": "rm -rf dist && mkdir dist",
    "build": "npm run build:constants && npm run build:deps && npm run build:bundlers",
    "build:bundlers": "tsc -p . && rollup -c",
    "build:deps": "node scripts/build-polyfills.js",
    "build:constants": "node scripts/build-constants.js",
    "release": "np --no-yarn --no-release-draft",
    "browser-test": "serve browser-test/dist",
    "prebrowser-test": "npm run build && node ./browser-test/index.js"
  },
  "files": [
    "dist",
    "polyfills"
  ],
  "keywords": [
    "rollup-plugin"
  ],
  "author": "",
  "license": "MIT",
  "dependencies": {
    "rollup-plugin-inject": "^3.0.0"
  },
  "devDependencies": {
    "browserify-fs": "^1.0.0",
    "buffer-es6": "^4.9.2",
    "crypto-browserify": "^3.11.0",
    "debug": "^4.1.1",
    "mocha": "^6.1.4",
    "np": "^5.0.3",
    "process-es6": "^0.11.2",
    "rollup": "^1.15.4",
    "rollup-plugin-commonjs": "^10.0.0",
    "rollup-plugin-json": "^4.0.0",
    "rollup-plugin-license": "^0.9.0",
    "rollup-plugin-node-resolve": "^5.0.2",
    "serve": "^11.0.1",
    "typescript": "^3.5.2"
  },
  "repository": {
    "type": "git",
    "url": "git@github.com:ionic-team/rollup-plugin-node-polyfills.git"
  }
}


================================================
FILE: polyfills/LICENSE-browserify-fs.txt
================================================
Name: browserify-fs
Version: 1.0.0
License: undefined
Private: false
Description: fs for the browser using level-filesystem and browserify
Repository: undefined

---

Name: level-js
Version: 2.2.4
License: BSD-2-Clause
Private: false
Description: leveldown/leveldb library for browsers using IndexedDB
Repository: git@github.com:maxogden/level.js.git
Author: max ogden

---

Name: levelup
Version: 0.18.6
License: MIT
Private: false
Description: Fast & simple storage - a Node.js-style LevelDB wrapper
Repository: https://github.com/rvagg/node-levelup.git
Homepage: https://github.com/rvagg/node-levelup
Contributors:
  Rod Vagg <r@va.gg> (https://github.com/rvagg)
  John Chesley <john@chesl.es> (https://github.com/chesles/)
  Jake Verbaten <raynos2@gmail.com> (https://github.com/raynos)
  Dominic Tarr <dominic.tarr@gmail.com> (https://github.com/dominictarr)
  Max Ogden <max@maxogden.com> (https://github.com/maxogden)
  Lars-Magnus Skog <lars.magnus.skog@gmail.com> (https://github.com/ralphtheninja)
  David Björklund <david.bjorklund@gmail.com> (https://github.com/kesla)
  Julian Gruber <julian@juliangruber.com> (https://github.com/juliangruber)
  Paolo Fragomeni <paolo@async.ly> (https://github.com/hij1nx)
  Anton Whalley <anton.whalley@nearform.com> (https://github.com/No9)
  Matteo Collina <matteo.collina@gmail.com> (https://github.com/mcollina)
  Pedro Teixeira <pedro.teixeira@gmail.com> (https://github.com/pgte)
  James Halliday <mail@substack.net> (https://github.com/substack)

---

Name: level-filesystem
Version: 1.2.0
License: undefined
Private: false
Description: Full implementation of the fs module on top of leveldb
Repository: undefined

---

Name: rollup-plugin-node-resolve
Version: 5.0.1
License: MIT
Private: false
Description: Bundle third-party dependencies in node_modules
Repository: undefined
Homepage: https://github.com/rollup/rollup-plugin-node-resolve#readme
Author: Rich Harris <richard.a.harris@gmail.com>

---

Name: prr
Version: 0.0.0
License: MIT
Private: false
Description: A better Object.defineProperty()
Repository: https://github.com/rvagg/prr.git
Homepage: https://github.com/rvagg/prr

---

Name: xtend
Version: 2.1.2
License: (MIT)
Private: false
Description: extend like a boss
Repository: undefined
Homepage: https://github.com/Raynos/xtend
Author: Raynos <raynos2@gmail.com>
Contributors:
  Jake Verbaten
  Matt Esch

---

Name: once
Version: 1.4.0
License: ISC
Private: false
Description: Run a function exactly one time
Repository: git://github.com/isaacs/once
Author: Isaac Z. Schlueter <i@izs.me> (http://blog.izs.me/)

---

Name: octal
Version: 1.0.0
License: MIT
Private: false
Description: Interpret a number as base 8
Repository: https://github.com/mafintosh/octal.git
Homepage: https://github.com/mafintosh/octal
Author: Mathias Buus (@mafintosh)

---

Name: readable-stream
Version: 1.0.34
License: MIT
Private: false
Description: Streams2, a user-land copy of the stream library from Node.js v0.10.x
Repository: git://github.com/isaacs/readable-stream
Author: Isaac Z. Schlueter <i@izs.me> (http://blog.izs.me/)

---

Name: level-blobs
Version: 0.1.7
License: undefined
Private: false
Description: Save binary blobs in level and stream then back
Repository: undefined

---

Name: level-sublevel
Version: 5.2.3
License: MIT
Private: false
Description: partition levelup databases
Repository: git://github.com/dominictarr/level-sublevel.git
Homepage: https://github.com/dominictarr/level-sublevel
Author: Dominic Tarr <dominic.tarr@gmail.com> (http://dominictarr.com)

---

Name: fwd-stream
Version: 1.0.4
License: undefined
Private: false
Description: Forward a readable stream to another readable stream or a writable stream to another writable stream
Repository: undefined

---

Name: level-peek
Version: 1.0.6
License: MIT
Private: false
Repository: git://github.com/dominictarr/level-peek.git
Homepage: https://github.com/dominictarr/level-peek
Author: Dominic Tarr <dominic.tarr@gmail.com> (http://dominictarr.com)

---

Name: errno
Version: 0.1.7
License: MIT
Private: false
Description: libuv errno details exposed
Repository: https://github.com/rvagg/node-errno.git

---

Name: concat-stream
Version: 1.6.2
License: MIT
Private: false
Description: writable stream that concatenates strings or binary data and calls a callback with the result
Repository: http://github.com/maxogden/concat-stream.git
Author: Max Ogden <max@maxogden.com>

---

Name: inherits
Version: 2.0.3
License: ISC
Private: false
Description: Browser-friendly inheritance fully compatible with standard node.js inherits()
Repository: undefined

---

Name: idb-wrapper
Version: 1.7.2
License: MIT
Private: false
Description: A cross-browser wrapper for IndexedDB
Repository: undefined
Homepage: https://github.com/jensarps/IDBWrapper
Author: jensarps <mail@jensarps.de> (http://jensarps.de/)
Contributors:
  Github Contributors (https://github.com/jensarps/IDBWrapper/graphs/contributors)

---

Name: typedarray-to-buffer
Version: 1.0.4
License: MIT
Private: false
Description: Convert a typed array to a Buffer without a copy
Repository: git://github.com/feross/typedarray-to-buffer.git
Homepage: http://feross.org
Author: Feross Aboukhadijeh <feross@feross.org> (http://feross.org/)

---

Name: abstract-leveldown
Version: 0.12.4
License: MIT
Private: false
Description: An abstract prototype matching the LevelDOWN API
Repository: https://github.com/rvagg/node-abstract-leveldown.git
Homepage: https://github.com/rvagg/node-abstract-leveldown
Contributors:
  Rod Vagg <r@va.gg> (https://github.com/rvagg)
  John Chesley <john@chesl.es> (https://github.com/chesles/)
  Jake Verbaten <raynos2@gmail.com> (https://github.com/raynos)
  Dominic Tarr <dominic.tarr@gmail.com> (https://github.com/dominictarr)
  Max Ogden <max@maxogden.com> (https://github.com/maxogden)
  Lars-Magnus Skog <lars.magnus.skog@gmail.com> (https://github.com/ralphtheninja)
  David Björklund <david.bjorklund@gmail.com> (https://github.com/kesla)
  Julian Gruber <julian@juliangruber.com> (https://github.com/juliangruber)
  Paolo Fragomeni <paolo@async.ly> (https://github.com/hij1nx)
  Anton Whalley <anton.whalley@nearform.com> (https://github.com/No9)
  Matteo Collina <matteo.collina@gmail.com> (https://github.com/mcollina)
  Pedro Teixeira <pedro.teixeira@gmail.com> (https://github.com/pgte)
  James Halliday <mail@substack.net> (https://github.com/substack)

---

Name: isbuffer
Version: 0.0.0
License: MIT
Private: false
Description: isBuffer for node and browser (supports typed arrays)
Repository: git://github.com/juliangruber/isbuffer.git
Homepage: https://github.com/juliangruber/isbuffer
Author: Julian Gruber <mail@juliangruber.com> (http://juliangruber.com)

---

Name: deferred-leveldown
Version: 0.2.0
License: MIT
Private: false
Description: For handling delayed-open on LevelDOWN compatible libraries
Repository: https://github.com/Level/deferred-leveldown.git
Homepage: https://github.com/Level/deferred-leveldown
Contributors:
  Rod Vagg <r@va.gg> (https://github.com/rvagg)
  John Chesley <john@chesl.es> (https://github.com/chesles/)
  Jake Verbaten <raynos2@gmail.com> (https://github.com/raynos)
  Dominic Tarr <dominic.tarr@gmail.com> (https://github.com/dominictarr)
  Max Ogden <max@maxogden.com> (https://github.com/maxogden)
  Lars-Magnus Skog <lars.magnus.skog@gmail.com> (https://github.com/ralphtheninja)
  David Björklund <david.bjorklund@gmail.com> (https://github.com/kesla)
  Julian Gruber <julian@juliangruber.com> (https://github.com/juliangruber)
  Paolo Fragomeni <paolo@async.ly> (https://github.com/hij1nx)
  Anton Whalley <anton.whalley@nearform.com> (https://github.com/No9)
  Matteo Collina <matteo.collina@gmail.com> (https://github.com/mcollina)
  Pedro Teixeira <pedro.teixeira@gmail.com> (https://github.com/pgte)
  James Halliday <mail@substack.net> (https://github.com/substack)

---

Name: wrappy
Version: 1.0.2
License: ISC
Private: false
Description: Callback wrapping utility
Repository: https://github.com/npm/wrappy
Homepage: https://github.com/npm/wrappy
Author: Isaac Z. Schlueter <i@izs.me> (http://blog.izs.me/)

---

Name: bl
Version: 0.8.2
License: MIT
Private: false
Description: Buffer List: collect buffers and access with a standard readable Buffer interface, streamable too!
Repository: https://github.com/rvagg/bl.git
Homepage: https://github.com/rvagg/bl

---

Name: object-keys
Version: 0.4.0
License: MIT
Private: false
Description: An Object.keys replacement, in case Object.keys is not available. From https://github.com/kriskowal/es5-shim
Repository: git://github.com/ljharb/object-keys.git
Author: Jordan Harband

---

Name: ltgt
Version: 2.2.1
License: MIT
Private: false
Repository: git://github.com/dominictarr/ltgt.git
Homepage: https://github.com/dominictarr/ltgt
Author: Dominic Tarr <dominic.tarr@gmail.com> (http://dominictarr.com)

---

Name: typedarray
Version: 0.0.6
License: MIT
Private: false
Description: TypedArray polyfill for old browsers
Repository: git://github.com/substack/typedarray.git
Homepage: https://github.com/substack/typedarray
Author: James Halliday <mail@substack.net> (http://substack.net)

---

Name: level-fix-range
Version: 2.0.0
License: MIT
Private: false
Description: make using levelup reverse ranges easy
Repository: git://github.com/dominictarr/level-fix-range.git
Homepage: https://github.com/dominictarr/level-fix-range
Author: Dominic Tarr <dominic.tarr@gmail.com> (http://dominictarr.com)

---

Name: buffer-from
Version: 1.1.1
License: MIT
Private: false
Repository: undefined

---

Name: isarray
Version: 0.0.1
License: MIT
Private: false
Description: Array#isArray for older browsers
Repository: git://github.com/juliangruber/isarray.git
Homepage: https://github.com/juliangruber/isarray
Author: Julian Gruber <mail@juliangruber.com> (http://juliangruber.com)

---

Name: string_decoder
Version: 0.10.31
License: MIT
Private: false
Description: The string_decoder module from Node core
Repository: git://github.com/rvagg/string_decoder.git
Homepage: https://github.com/rvagg/string_decoder

---

Name: safe-buffer
Version: 5.1.2
License: MIT
Private: false
Description: Safer Node.js Buffer API
Repository: git://github.com/feross/safe-buffer.git
Homepage: https://github.com/feross/safe-buffer
Author: Feross Aboukhadijeh <feross@feross.org> (http://feross.org)

---

Name: level-hooks
Version: 4.5.0
License: undefined
Private: false
Description: pre/post hooks for leveldb
Repository: git://github.com/dominictarr/level-hooks.git
Homepage: https://github.com/dominictarr/level-hooks
Author: Dominic Tarr <dominic.tarr@gmail.com> (http://bit.ly/dominictarr)

---

Name: core-util-is
Version: 1.0.2
License: MIT
Private: false
Description: The `util.is*` functions introduced in Node v0.12.
Repository: git://github.com/isaacs/core-util-is
Author: Isaac Z. Schlueter <i@izs.me> (http://blog.izs.me/)

---

Name: string-range
Version: 1.2.2
License: MIT
Private: false
Description: check if a string is within a range
Repository: git://github.com/dominictarr/string-range.git
Homepage: https://github.com/dominictarr/string-range
Author: Dominic Tarr <dominic.tarr@gmail.com> (http://dominictarr.com)

---

Name: process-nextick-args
Version: 2.0.0
License: MIT
Private: false
Description: process.nextTick but always with args
Repository: https://github.com/calvinmetcalf/process-nextick-args.git
Homepage: https://github.com/calvinmetcalf/process-nextick-args

---

Name: util-deprecate
Version: 1.0.2
License: MIT
Private: false
Description: The Node.js `util.deprecate()` function with browser support
Repository: git://github.com/TooTallNate/util-deprecate.git
Homepage: https://github.com/TooTallNate/util-deprecate
Author: Nathan Rajlich <nathan@tootallnate.net> (http://n8.io/)

---

Name: clone
Version: 0.1.19
License: MIT
Private: false
Description: deep cloning of objects and arrays
Repository: git://github.com/pvorb/node-clone.git
Author: Paul Vorbach <paul@vorba.ch> (http://paul.vorba.ch/)
Contributors:
  Blake Miner <miner.blake@gmail.com> (http://www.blakeminer.com/)
  Tian You <axqd001@gmail.com> (http://blog.axqd.net/)
  George Stagas <gstagas@gmail.com> (http://stagas.com/)
  Tobiasz Cudnik <tobiasz.cudnik@gmail.com> (https://github.com/TobiaszCudnik)
  Pavel Lang <langpavel@phpskelet.org> (https://github.com/langpavel)
  Dan MacTough (http://yabfog.com/)
  w1nk (https://github.com/w1nk)
  Hugh Kennedy (http://twitter.com/hughskennedy)
  Dustin Diaz (http://dustindiaz.com)
  Ilya Shaisultanov (https://github.com/diversario)
  Nathan MacInnes <nathan@macinn.es> (http://macinn.es/)
  Benjamin E. Coe <ben@npmjs.com> (https://twitter.com/benjamincoe)
  Nathan Zadoks (https://github.com/nathan7)
  Róbert Oroszi <robert+gh@oroszi.net> (https://github.com/oroce)

---

Name: is
Version: 0.2.7
License: undefined
Private: false
Description: the definitive JavaScript type testing library
Repository: git://github.com/enricomarino/is.git
Homepage: https://github.com/enricomarino/is
Author: Enrico Marino (http://onirame.com)
Contributors:
  Jordan Harband (https://github.com/ljharb)

---

Name: foreach
Version: 2.0.5
License: MIT
Private: false
Description: foreach component + npm package
Repository: git://github.com/manuelstofer/foreach
Author: Manuel Stofer <manuel@takimata.ch>
Contributors:
  Manuel Stofer
  Jordan Harband (https://github.com/ljharb)

================================================
FILE: polyfills/LICENSE-buffer-es6.txt
================================================
Name: buffer-es6
Version: 4.9.3
License: MIT
Private: false
Description: Node.js Buffer API, for the browser
Repository: git://github.com/calvinmetcalf/buffer-es6.git
Author: Feross Aboukhadijeh <feross@feross.org> (http://feross.org)
Contributors:
  Romain Beauxis <toots@rastageeks.org>
  James Halliday <mail@substack.net>

================================================
FILE: polyfills/LICENSE-crypto-browserify.txt
================================================
Name: crypto-browserify
Version: 3.12.0
License: MIT
Private: false
Description: implementation of crypto for the browser
Repository: git://github.com/crypto-browserify/crypto-browserify.git
Homepage: https://github.com/crypto-browserify/crypto-browserify
Author: Dominic Tarr <dominic.tarr@gmail.com> (dominictarr.com)

---

Name: browserify-sign
Version: 4.0.4
License: ISC
Private: false
Description: adds node crypto signing for browsers
Repository: https://github.com/crypto-browserify/browserify-sign.git

---

Name: randombytes
Version: 2.1.0
License: MIT
Private: false
Description: random bytes from browserify stand alone
Repository: git@github.com:crypto-browserify/randombytes.git
Homepage: https://github.com/crypto-browserify/randombytes

---

Name: create-hash
Version: 1.2.0
License: MIT
Private: false
Description: create hashes for browserify
Repository: git@github.com:crypto-browserify/createHash.git
Homepage: https://github.com/crypto-browserify/createHash

---

Name: browserify-cipher
Version: 1.0.1
License: MIT
Private: false
Description: ciphers for the browser
Repository: git@github.com:crypto-browserify/browserify-cipher.git
Author: Calvin Metcalf <calvin.metcalf@gmail.com>

---

Name: pbkdf2
Version: 3.0.17
License: MIT
Private: false
Description: This library provides the functionality of PBKDF2 with the ability to use any supported hashing algorithm returned from crypto.getHashes()
Repository: https://github.com/crypto-browserify/pbkdf2.git
Homepage: https://github.com/crypto-browserify/pbkdf2
Author: Daniel Cousens

---

Name: diffie-hellman
Version: 5.0.3
License: MIT
Private: false
Description: pure js diffie-hellman
Repository: https://github.com/crypto-browserify/diffie-hellman.git
Homepage: https://github.com/crypto-browserify/diffie-hellman
Author: Calvin Metcalf

---

Name: create-hmac
Version: 1.1.7
License: MIT
Private: false
Description: node style hmacs in the browser
Repository: https://github.com/crypto-browserify/createHmac.git
Homepage: https://github.com/crypto-browserify/createHmac

---

Name: create-ecdh
Version: 4.0.3
License: MIT
Private: false
Description: createECDH but browserifiable
Repository: https://github.com/crypto-browserify/createECDH.git
Homepage: https://github.com/crypto-browserify/createECDH
Author: Calvin Metcalf

---

Name: public-encrypt
Version: 4.0.3
License: MIT
Private: false
Description: browserify version of publicEncrypt & privateDecrypt
Repository: https://github.com/crypto-browserify/publicEncrypt.git
Homepage: https://github.com/crypto-browserify/publicEncrypt
Author: Calvin Metcalf

---

Name: randomfill
Version: 1.0.4
License: MIT
Private: false
Description: random fill from browserify stand alone
Repository: https://github.com/crypto-browserify/randomfill.git
Homepage: https://github.com/crypto-browserify/randomfill

---

Name: browserify-des
Version: 1.0.2
License: MIT
Private: false
Repository: git+https://github.com/crypto-browserify/browserify-des.git
Homepage: https://github.com/crypto-browserify/browserify-des#readme
Author: Calvin Metcalf <calvin.metcalf@gmail.com>

---

Name: browserify-aes
Version: 1.2.0
License: MIT
Private: false
Description: aes, for browserify
Repository: git://github.com/crypto-browserify/browserify-aes.git
Homepage: https://github.com/crypto-browserify/browserify-aes

---

Name: safe-buffer
Version: 5.1.2
License: MIT
Private: false
Description: Safer Node.js Buffer API
Repository: git://github.com/feross/safe-buffer.git
Homepage: https://github.com/feross/safe-buffer
Author: Feross Aboukhadijeh <feross@feross.org> (http://feross.org)

---

Name: md5.js
Version: 1.3.5
License: MIT
Private: false
Description: node style md5 on pure JavaScript
Repository: https://github.com/crypto-browserify/md5.js.git
Homepage: https://github.com/crypto-browserify/md5.js
Author: Kirill Fomichev <fanatid@ya.ru> (https://github.com/fanatid)

---

Name: inherits
Version: 2.0.3
License: ISC
Private: false
Description: Browser-friendly inheritance fully compatible with standard node.js inherits()
Repository: undefined

---

Name: cipher-base
Version: 1.0.4
License: MIT
Private: false
Description: abstract base class for crypto-streams
Repository: git+https://github.com/crypto-browserify/cipher-base.git
Homepage: https://github.com/crypto-browserify/cipher-base#readme
Author: Calvin Metcalf <calvin.metcalf@gmail.com>

---

Name: evp_bytestokey
Version: 1.0.3
License: MIT
Private: false
Description: The insecure key derivation algorithm from OpenSSL
Repository: https://github.com/crypto-browserify/EVP_BytesToKey.git
Homepage: https://github.com/crypto-browserify/EVP_BytesToKey
Author: Calvin Metcalf <calvin.metcalf@gmail.com>
Contributors:
  Kirill Fomichev <fanatid@ya.ru>

---

Name: elliptic
Version: 6.4.1
License: MIT
Private: false
Description: EC cryptography
Repository: git@github.com:indutny/elliptic
Homepage: https://github.com/indutny/elliptic
Author: Fedor Indutny <fedor@indutny.com>

---

Name: bn.js
Version: 4.11.8
License: MIT
Private: false
Description: Big number implementation in pure javascript
Repository: git@github.com:indutny/bn.js
Homepage: https://github.com/indutny/bn.js
Author: Fedor Indutny <fedor@indutny.com>

---

Name: browserify-rsa
Version: 4.0.1
License: MIT
Private: false
Description: RSA for browserify
Repository: git@github.com:crypto-browserify/browserify-rsa.git

---

Name: parse-asn1
Version: 5.1.4
License: ISC
Private: false
Description: utility library for parsing asn1 files for use with browserify-sign.
Repository: git://github.com/crypto-browserify/parse-asn1.git

---

Name: ripemd160
Version: 2.0.2
License: MIT
Private: false
Description: Compute ripemd160 of bytes or strings.
Repository: https://github.com/crypto-browserify/ripemd160

---

Name: sha.js
Version: 2.4.11
License: (MIT AND BSD-3-Clause)
Private: false
Description: Streamable SHA hashes in pure javascript
Repository: git://github.com/crypto-browserify/sha.js.git
Homepage: https://github.com/crypto-browserify/sha.js
Author: Dominic Tarr <dominic.tarr@gmail.com> (dominictarr.com)

---

Name: miller-rabin
Version: 4.0.1
License: MIT
Private: false
Description: Miller Rabin algorithm for primality test
Repository: git@github.com:indutny/miller-rabin
Homepage: https://github.com/indutny/miller-rabin
Author: Fedor Indutny <fedor@indutny.com>

---

Name: des.js
Version: 1.0.0
License: MIT
Private: false
Description: DES implementation
Repository: git+ssh://git@github.com/indutny/des.js.git
Homepage: https://github.com/indutny/des.js#readme
Author: Fedor Indutny <fedor@indutny.com>

---

Name: hash-base
Version: 3.0.4
License: MIT
Private: false
Description: abstract base class for hash-streams
Repository: https://github.com/crypto-browserify/hash-base.git
Homepage: https://github.com/crypto-browserify/hash-base
Author: Kirill Fomichev <fanatid@ya.ru> (https://github.com/fanatid)

---

Name: brorand
Version: 1.1.0
License: MIT
Private: false
Description: Random number generator for browsers and node.js
Repository: git@github.com:indutny/brorand
Homepage: https://github.com/indutny/brorand
Author: Fedor Indutny <fedor@indutny.com>

---

Name: buffer-xor
Version: 1.0.3
License: MIT
Private: false
Description: A simple module for bitwise-xor on buffers
Repository: https://github.com/crypto-browserify/buffer-xor.git
Homepage: https://github.com/crypto-browserify/buffer-xor
Author: Daniel Cousens

---

Name: asn1.js
Version: 4.10.1
License: MIT
Private: false
Description: ASN.1 encoder and decoder
Repository: git@github.com:indutny/asn1.js
Homepage: https://github.com/indutny/asn1.js
Author: Fedor Indutny

---

Name: minimalistic-assert
Version: 1.0.1
License: ISC
Private: false
Description: minimalistic-assert ===
Repository: https://github.com/calvinmetcalf/minimalistic-assert.git
Homepage: https://github.com/calvinmetcalf/minimalistic-assert

---

Name: hash.js
Version: 1.1.7
License: MIT
Private: false
Description: Various hash functions that could be run by both browser and node
Repository: git@github.com:indutny/hash.js
Homepage: https://github.com/indutny/hash.js
Author: Fedor Indutny <fedor@indutny.com>

---

Name: minimalistic-crypto-utils
Version: 1.0.1
License: MIT
Private: false
Description: Minimalistic tools for JS crypto modules
Repository: git+ssh://git@github.com/indutny/minimalistic-crypto-utils.git
Homepage: https://github.com/indutny/minimalistic-crypto-utils#readme
Author: Fedor Indutny <fedor@indutny.com>

---

Name: hmac-drbg
Version: 1.0.1
License: MIT
Private: false
Description: Deterministic random bit generator (hmac)
Repository: git+ssh://git@github.com/indutny/hmac-drbg.git
Homepage: https://github.com/indutny/hmac-drbg#readme
Author: Fedor Indutny <fedor@indutny.com>

================================================
FILE: polyfills/LICENSE-process-es6.txt
================================================
Name: process-es6
Version: 0.11.6
License: MIT
Private: false
Description: process information for node.js and browsers, but in es6
Repository: git://github.com/calvinmetcalf/node-process-es6.git
Author: Roman Shtylman <shtylman@gmail.com>

================================================
FILE: polyfills/assert.js
================================================

function compare(a, b) {
  if (a === b) {
    return 0;
  }

  var x = a.length;
  var y = b.length;

  for (var i = 0, len = Math.min(x, y); i < len; ++i) {
    if (a[i] !== b[i]) {
      x = a[i];
      y = b[i];
      break;
    }
  }

  if (x < y) {
    return -1;
  }
  if (y < x) {
    return 1;
  }
  return 0;
}
var hasOwn = Object.prototype.hasOwnProperty;

var objectKeys = Object.keys || function (obj) {
  var keys = [];
  for (var key in obj) {
    if (hasOwn.call(obj, key)) keys.push(key);
  }
  return keys;
};
// based on node assert, original notice:

// http://wiki.commonjs.org/wiki/Unit_Testing/1.0
//
// THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8!
//
// Originally from narwhal.js (http://narwhaljs.org)
// Copyright (c) 2009 Thomas Robinson <280north.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the 'Software'), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import {isBuffer} from 'buffer';
import {isPrimitive, inherits, isError, isFunction, isRegExp, isDate, inspect as utilInspect} from 'util';
var pSlice = Array.prototype.slice;
var _functionsHaveNames;
function functionsHaveNames() {
  if (typeof _functionsHaveNames !== 'undefined') {
    return _functionsHaveNames;
  }
  return _functionsHaveNames = (function () {
    return function foo() {}.name === 'foo';
  }());
}
function pToString (obj) {
  return Object.prototype.toString.call(obj);
}
function isView(arrbuf) {
  if (isBuffer(arrbuf)) {
    return false;
  }
  if (typeof global.ArrayBuffer !== 'function') {
    return false;
  }
  if (typeof ArrayBuffer.isView === 'function') {
    return ArrayBuffer.isView(arrbuf);
  }
  if (!arrbuf) {
    return false;
  }
  if (arrbuf instanceof DataView) {
    return true;
  }
  if (arrbuf.buffer && arrbuf.buffer instanceof ArrayBuffer) {
    return true;
  }
  return false;
}
// 1. The assert module provides functions that throw
// AssertionError's when particular conditions are not met. The
// assert module must conform to the following interface.

function assert(value, message) {
  if (!value) fail(value, true, message, '==', ok);
}
export default assert;

// 2. The AssertionError is defined in assert.
// new assert.AssertionError({ message: message,
//                             actual: actual,
//                             expected: expected })

var regex = /\s*function\s+([^\(\s]*)\s*/;
// based on https://github.com/ljharb/function.prototype.name/blob/adeeeec8bfcc6068b187d7d9fb3d5bb1d3a30899/implementation.js
function getName(func) {
  if (!isFunction(func)) {
    return;
  }
  if (functionsHaveNames()) {
    return func.name;
  }
  var str = func.toString();
  var match = str.match(regex);
  return match && match[1];
}
assert.AssertionError = AssertionError;
export function AssertionError(options) {
  this.name = 'AssertionError';
  this.actual = options.actual;
  this.expected = options.expected;
  this.operator = options.operator;
  if (options.message) {
    this.message = options.message;
    this.generatedMessage = false;
  } else {
    this.message = getMessage(this);
    this.generatedMessage = true;
  }
  var stackStartFunction = options.stackStartFunction || fail;
  if (Error.captureStackTrace) {
    Error.captureStackTrace(this, stackStartFunction);
  } else {
    // non v8 browsers so we can have a stacktrace
    var err = new Error();
    if (err.stack) {
      var out = err.stack;

      // try to strip useless frames
      var fn_name = getName(stackStartFunction);
      var idx = out.indexOf('\n' + fn_name);
      if (idx >= 0) {
        // once we have located the function frame
        // we need to strip out everything before it (and its line)
        var next_line = out.indexOf('\n', idx + 1);
        out = out.substring(next_line + 1);
      }

      this.stack = out;
    }
  }
}

// assert.AssertionError instanceof Error
inherits(AssertionError, Error);

function truncate(s, n) {
  if (typeof s === 'string') {
    return s.length < n ? s : s.slice(0, n);
  } else {
    return s;
  }
}
function inspect(something) {
  if (functionsHaveNames() || !isFunction(something)) {
    return utilInspect(something);
  }
  var rawname = getName(something);
  var name = rawname ? ': ' + rawname : '';
  return '[Function' +  name + ']';
}
function getMessage(self) {
  return truncate(inspect(self.actual), 128) + ' ' +
         self.operator + ' ' +
         truncate(inspect(self.expected), 128);
}

// At present only the three keys mentioned above are used and
// understood by the spec. Implementations or sub modules can pass
// other keys to the AssertionError's constructor - they will be
// ignored.

// 3. All of the following functions must throw an AssertionError
// when a corresponding condition is not met, with a message that
// may be undefined if not provided.  All assertion methods provide
// both the actual and expected values to the assertion error for
// display purposes.

export function fail(actual, expected, message, operator, stackStartFunction) {
  throw new AssertionError({
    message: message,
    actual: actual,
    expected: expected,
    operator: operator,
    stackStartFunction: stackStartFunction
  });
}

// EXTENSION! allows for well behaved errors defined elsewhere.
assert.fail = fail;

// 4. Pure assertion tests whether a value is truthy, as determined
// by !!guard.
// assert.ok(guard, message_opt);
// This statement is equivalent to assert.equal(true, !!guard,
// message_opt);. To test strictly for the value true, use
// assert.strictEqual(true, guard, message_opt);.

export function ok(value, message) {
  if (!value) fail(value, true, message, '==', ok);
}
assert.ok = ok;
export {ok as assert};

// 5. The equality assertion tests shallow, coercive equality with
// ==.
// assert.equal(actual, expected, message_opt);
assert.equal = equal;
export function equal(actual, expected, message) {
  if (actual != expected) fail(actual, expected, message, '==', equal);
}

// 6. The non-equality assertion tests for whether two objects are not equal
// with != assert.notEqual(actual, expected, message_opt);
assert.notEqual = notEqual;
export function notEqual(actual, expected, message) {
  if (actual == expected) {
    fail(actual, expected, message, '!=', notEqual);
  }
}

// 7. The equivalence assertion tests a deep equality relation.
// assert.deepEqual(actual, expected, message_opt);
assert.deepEqual = deepEqual;
export function deepEqual(actual, expected, message) {
  if (!_deepEqual(actual, expected, false)) {
    fail(actual, expected, message, 'deepEqual', deepEqual);
  }
}
assert.deepStrictEqual = deepStrictEqual;
export function deepStrictEqual(actual, expected, message) {
  if (!_deepEqual(actual, expected, true)) {
    fail(actual, expected, message, 'deepStrictEqual', deepStrictEqual);
  }
}

function _deepEqual(actual, expected, strict, memos) {
  // 7.1. All identical values are equivalent, as determined by ===.
  if (actual === expected) {
    return true;
  } else if (isBuffer(actual) && isBuffer(expected)) {
    return compare(actual, expected) === 0;

  // 7.2. If the expected value is a Date object, the actual value is
  // equivalent if it is also a Date object that refers to the same time.
  } else if (isDate(actual) && isDate(expected)) {
    return actual.getTime() === expected.getTime();

  // 7.3 If the expected value is a RegExp object, the actual value is
  // equivalent if it is also a RegExp object with the same source and
  // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`).
  } else if (isRegExp(actual) && isRegExp(expected)) {
    return actual.source === expected.source &&
           actual.global === expected.global &&
           actual.multiline === expected.multiline &&
           actual.lastIndex === expected.lastIndex &&
           actual.ignoreCase === expected.ignoreCase;

  // 7.4. Other pairs that do not both pass typeof value == 'object',
  // equivalence is determined by ==.
  } else if ((actual === null || typeof actual !== 'object') &&
             (expected === null || typeof expected !== 'object')) {
    return strict ? actual === expected : actual == expected;

  // If both values are instances of typed arrays, wrap their underlying
  // ArrayBuffers in a Buffer each to increase performance
  // This optimization requires the arrays to have the same type as checked by
  // Object.prototype.toString (aka pToString). Never perform binary
  // comparisons for Float*Arrays, though, since e.g. +0 === -0 but their
  // bit patterns are not identical.
  } else if (isView(actual) && isView(expected) &&
             pToString(actual) === pToString(expected) &&
             !(actual instanceof Float32Array ||
               actual instanceof Float64Array)) {
    return compare(new Uint8Array(actual.buffer),
                   new Uint8Array(expected.buffer)) === 0;

  // 7.5 For all other Object pairs, including Array objects, equivalence is
  // determined by having the same number of owned properties (as verified
  // with Object.prototype.hasOwnProperty.call), the same set of keys
  // (although not necessarily the same order), equivalent values for every
  // corresponding key, and an identical 'prototype' property. Note: this
  // accounts for both named and indexed properties on Arrays.
  } else if (isBuffer(actual) !== isBuffer(expected)) {
    return false;
  } else {
    memos = memos || {actual: [], expected: []};

    var actualIndex = memos.actual.indexOf(actual);
    if (actualIndex !== -1) {
      if (actualIndex === memos.expected.indexOf(expected)) {
        return true;
      }
    }

    memos.actual.push(actual);
    memos.expected.push(expected);

    return objEquiv(actual, expected, strict, memos);
  }
}

function isArguments(object) {
  return Object.prototype.toString.call(object) == '[object Arguments]';
}

function objEquiv(a, b, strict, actualVisitedObjects) {
  if (a === null || a === undefined || b === null || b === undefined)
    return false;
  // if one is a primitive, the other must be same
  if (isPrimitive(a) || isPrimitive(b))
    return a === b;
  if (strict && Object.getPrototypeOf(a) !== Object.getPrototypeOf(b))
    return false;
  var aIsArgs = isArguments(a);
  var bIsArgs = isArguments(b);
  if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs))
    return false;
  if (aIsArgs) {
    a = pSlice.call(a);
    b = pSlice.call(b);
    return _deepEqual(a, b, strict);
  }
  var ka = objectKeys(a);
  var kb = objectKeys(b);
  var key, i;
  // having the same number of owned properties (keys incorporates
  // hasOwnProperty)
  if (ka.length !== kb.length)
    return false;
  //the same set of keys (although not necessarily the same order),
  ka.sort();
  kb.sort();
  //~~~cheap key test
  for (i = ka.length - 1; i >= 0; i--) {
    if (ka[i] !== kb[i])
      return false;
  }
  //equivalent values for every corresponding key, and
  //~~~possibly expensive deep test
  for (i = ka.length - 1; i >= 0; i--) {
    key = ka[i];
    if (!_deepEqual(a[key], b[key], strict, actualVisitedObjects))
      return false;
  }
  return true;
}

// 8. The non-equivalence assertion tests for any deep inequality.
// assert.notDeepEqual(actual, expected, message_opt);
assert.notDeepEqual = notDeepEqual;
export function notDeepEqual(actual, expected, message) {
  if (_deepEqual(actual, expected, false)) {
    fail(actual, expected, message, 'notDeepEqual', notDeepEqual);
  }
}

assert.notDeepStrictEqual = notDeepStrictEqual;
export function notDeepStrictEqual(actual, expected, message) {
  if (_deepEqual(actual, expected, true)) {
    fail(actual, expected, message, 'notDeepStrictEqual', notDeepStrictEqual);
  }
}


// 9. The strict equality assertion tests strict equality, as determined by ===.
// assert.strictEqual(actual, expected, message_opt);
assert.strictEqual = strictEqual;
export function strictEqual(actual, expected, message) {
  if (actual !== expected) {
    fail(actual, expected, message, '===', strictEqual);
  }
}

// 10. The strict non-equality assertion tests for strict inequality, as
// determined by !==.  assert.notStrictEqual(actual, expected, message_opt);
assert.notStrictEqual = notStrictEqual;
export function notStrictEqual(actual, expected, message) {
  if (actual === expected) {
    fail(actual, expected, message, '!==', notStrictEqual);
  }
}

function expectedException(actual, expected) {
  if (!actual || !expected) {
    return false;
  }

  if (Object.prototype.toString.call(expected) == '[object RegExp]') {
    return expected.test(actual);
  }

  try {
    if (actual instanceof expected) {
      return true;
    }
  } catch (e) {
    // Ignore.  The instanceof check doesn't work for arrow functions.
  }

  if (Error.isPrototypeOf(expected)) {
    return false;
  }

  return expected.call({}, actual) === true;
}

function _tryBlock(block) {
  var error;
  try {
    block();
  } catch (e) {
    error = e;
  }
  return error;
}

function _throws(shouldThrow, block, expected, message) {
  var actual;

  if (typeof block !== 'function') {
    throw new TypeError('"block" argument must be a function');
  }

  if (typeof expected === 'string') {
    message = expected;
    expected = null;
  }

  actual = _tryBlock(block);

  message = (expected && expected.name ? ' (' + expected.name + ').' : '.') +
            (message ? ' ' + message : '.');

  if (shouldThrow && !actual) {
    fail(actual, expected, 'Missing expected exception' + message);
  }

  var userProvidedMessage = typeof message === 'string';
  var isUnwantedException = !shouldThrow && isError(actual);
  var isUnexpectedException = !shouldThrow && actual && !expected;

  if ((isUnwantedException &&
      userProvidedMessage &&
      expectedException(actual, expected)) ||
      isUnexpectedException) {
    fail(actual, expected, 'Got unwanted exception' + message);
  }

  if ((shouldThrow && actual && expected &&
      !expectedException(actual, expected)) || (!shouldThrow && actual)) {
    throw actual;
  }
}

// 11. Expected to throw an error:
// assert.throws(block, Error_opt, message_opt);
assert.throws = throws;
export function throws(block, /*optional*/error, /*optional*/message) {
  _throws(true, block, error, message);
}

// EXTENSION! This is annoying to write outside this module.
assert.doesNotThrow = doesNotThrow;
export function doesNotThrow(block, /*optional*/error, /*optional*/message) {
  _throws(false, block, error, message);
}

assert.ifError = ifError;
export function ifError(err) {
  if (err) throw err;
}


================================================
FILE: polyfills/browserify-fs.js
================================================
import util$2 from 'util';
import buffer from 'buffer';
import events from 'events';
import stream from 'stream';
import path from 'path';

var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};

function createCommonjsModule(fn, module) {
	return module = { exports: {} }, fn(module, module.exports), module.exports;
}

function getCjsExportFromNamespace (n) {
	return n && n['default'] || n;
}

var idbstore = createCommonjsModule(function (module) {
/*global window:false, self:false, define:false, module:false */

/**
 * @license IDBWrapper - A cross-browser wrapper for IndexedDB
 * Version 1.7.2
 * Copyright (c) 2011 - 2017 Jens Arps
 * http://jensarps.de/
 *
 * Licensed under the MIT license
 */

(function (name, definition, global) {

    if (module.exports) {
        module.exports = definition();
    } else {
        global[name] = definition();
    }
})('IDBStore', function () {

    var defaultErrorHandler = function (error) {
        throw error;
    };
    var defaultSuccessHandler = function () {
    };

    var defaults = {
        storeName: 'Store',
        storePrefix: 'IDBWrapper-',
        dbVersion: 1,
        keyPath: 'id',
        autoIncrement: true,
        onStoreReady: function () {
        },
        onError: defaultErrorHandler,
        indexes: [],
        implementationPreference: [
            'indexedDB',
            'webkitIndexedDB',
            'mozIndexedDB',
            'shimIndexedDB'
        ]
    };

    /**
     *
     * The IDBStore constructor
     *
     * @constructor
     * @name IDBStore
     * @version 1.7.2
     *
     * @param {Object} [kwArgs] An options object used to configure the store and
     *  set callbacks
     * @param {String} [kwArgs.storeName='Store'] The name of the store
     * @param {String} [kwArgs.storePrefix='IDBWrapper-'] A prefix that is
     *  internally used to construct the name of the database, which will be
     *  kwArgs.storePrefix + kwArgs.storeName
     * @param {Number} [kwArgs.dbVersion=1] The version of the store
     * @param {String} [kwArgs.keyPath='id'] The key path to use. If you want to
     *  setup IDBWrapper to work with out-of-line keys, you need to set this to
     *  `null`
     * @param {Boolean} [kwArgs.autoIncrement=true] If set to true, IDBStore will
     *  automatically make sure a unique keyPath value is present on each object
     *  that is stored.
     * @param {Function} [kwArgs.onStoreReady] A callback to be called when the
     *  store is ready to be used.
     * @param {Function} [kwArgs.onError=throw] A callback to be called when an
     *  error occurred during instantiation of the store.
     * @param {Array} [kwArgs.indexes=[]] An array of indexData objects
     *  defining the indexes to use with the store. For every index to be used
     *  one indexData object needs to be passed in the array.
     *  An indexData object is defined as follows:
     * @param {Object} [kwArgs.indexes.indexData] An object defining the index to
     *  use
     * @param {String} kwArgs.indexes.indexData.name The name of the index
     * @param {String} [kwArgs.indexes.indexData.keyPath] The key path of the index
     * @param {Boolean} [kwArgs.indexes.indexData.unique] Whether the index is unique
     * @param {Boolean} [kwArgs.indexes.indexData.multiEntry] Whether the index is multi entry
     * @param {Array} [kwArgs.implementationPreference=['indexedDB','webkitIndexedDB','mozIndexedDB','shimIndexedDB']] An array of strings naming implementations to be used, in order or preference
     * @param {Function} [onStoreReady] A callback to be called when the store
     * is ready to be used.
     * @example
     // create a store for customers with an additional index over the
     // `lastname` property.
     var myCustomerStore = new IDBStore({
         dbVersion: 1,
         storeName: 'customer-index',
         keyPath: 'customerid',
         autoIncrement: true,
         onStoreReady: populateTable,
         indexes: [
             { name: 'lastname', keyPath: 'lastname', unique: false, multiEntry: false }
         ]
     });
     * @example
     // create a generic store
     var myCustomerStore = new IDBStore({
         storeName: 'my-data-store',
         onStoreReady: function(){
             // start working with the store.
         }
     });
     */
    var IDBStore = function (kwArgs, onStoreReady) {

        if (typeof onStoreReady == 'undefined' && typeof kwArgs == 'function') {
            onStoreReady = kwArgs;
        }
        if (Object.prototype.toString.call(kwArgs) != '[object Object]') {
            kwArgs = {};
        }

        for (var key in defaults) {
            this[key] = typeof kwArgs[key] != 'undefined' ? kwArgs[key] : defaults[key];
        }

        this.dbName = this.storePrefix + this.storeName;
        this.dbVersion = parseInt(this.dbVersion, 10) || 1;

        onStoreReady && (this.onStoreReady = onStoreReady);

        var env = typeof window == 'object' ? window : self;
        var availableImplementations = this.implementationPreference.filter(function (implName) {
            return implName in env;
        });
        this.implementation = availableImplementations[0];
        this.idb = env[this.implementation];
        this.keyRange = env.IDBKeyRange || env.webkitIDBKeyRange || env.mozIDBKeyRange;

        this.consts = {
            'READ_ONLY': 'readonly',
            'READ_WRITE': 'readwrite',
            'VERSION_CHANGE': 'versionchange',
            'NEXT': 'next',
            'NEXT_NO_DUPLICATE': 'nextunique',
            'PREV': 'prev',
            'PREV_NO_DUPLICATE': 'prevunique'
        };

        this.openDB();
    };

    /** @lends IDBStore.prototype */
    var proto = {

        /**
         * A pointer to the IDBStore ctor
         *
         * @private
         * @type {Function}
         * @constructs
         */
        constructor: IDBStore,

        /**
         * The version of IDBStore
         *
         * @type {String}
         */
        version: '1.7.2',

        /**
         * A reference to the IndexedDB object
         *
         * @type {IDBDatabase}
         */
        db: null,

        /**
         * The full name of the IndexedDB used by IDBStore, composed of
         * this.storePrefix + this.storeName
         *
         * @type {String}
         */
        dbName: null,

        /**
         * The version of the IndexedDB used by IDBStore
         *
         * @type {Number}
         */
        dbVersion: null,

        /**
         * A reference to the objectStore used by IDBStore
         *
         * @type {IDBObjectStore}
         */
        store: null,

        /**
         * The store name
         *
         * @type {String}
         */
        storeName: null,

        /**
         * The prefix to prepend to the store name
         *
         * @type {String}
         */
        storePrefix: null,

        /**
         * The key path
         *
         * @type {String}
         */
        keyPath: null,

        /**
         * Whether IDBStore uses autoIncrement
         *
         * @type {Boolean}
         */
        autoIncrement: null,

        /**
         * The indexes used by IDBStore
         *
         * @type {Array}
         */
        indexes: null,

        /**
         * The implemantations to try to use, in order of preference
         *
         * @type {Array}
         */
        implementationPreference: null,

        /**
         * The actual implementation being used
         *
         * @type {String}
         */
        implementation: '',

        /**
         * The callback to be called when the store is ready to be used
         *
         * @type {Function}
         */
        onStoreReady: null,

        /**
         * The callback to be called if an error occurred during instantiation
         * of the store
         *
         * @type {Function}
         */
        onError: null,

        /**
         * The internal insertID counter
         *
         * @type {Number}
         * @private
         */
        _insertIdCount: 0,

        /**
         * Opens an IndexedDB; called by the constructor.
         *
         * Will check if versions match and compare provided index configuration
         * with existing ones, and update indexes if necessary.
         *
         * Will call this.onStoreReady() if everything went well and the store
         * is ready to use, and this.onError() is something went wrong.
         *
         * @private
         *
         */
        openDB: function () {

            var openRequest = this.idb.open(this.dbName, this.dbVersion);
            var preventSuccessCallback = false;

            openRequest.onerror = function (errorEvent) {

                if (hasVersionError(errorEvent)) {
                    this.onError(new Error('The version number provided is lower than the existing one.'));
                } else {
                    var error;

                    if (errorEvent.target.error) {
                        error = errorEvent.target.error;
                    } else {
                        var errorMessage = 'IndexedDB unknown error occurred when opening DB ' + this.dbName + ' version ' + this.dbVersion;
                        if ('errorCode' in errorEvent.target) {
                            errorMessage += ' with error code ' + errorEvent.target.errorCode;
                        }
                        error = new Error(errorMessage);
                    }

                    this.onError(error);
                }
            }.bind(this);

            openRequest.onsuccess = function (event) {

                if (preventSuccessCallback) {
                    return;
                }

                if (this.db) {
                    this.onStoreReady();
                    return;
                }

                this.db = event.target.result;

                if (typeof this.db.version == 'string') {
                    this.onError(new Error('The IndexedDB implementation in this browser is outdated. Please upgrade your browser.'));
                    return;
                }

                if (!this.db.objectStoreNames.contains(this.storeName)) {
                    // We should never ever get here.
                    // Lets notify the user anyway.
                    this.onError(new Error('Object store couldn\'t be created.'));
                    return;
                }

                var emptyTransaction = this.db.transaction([this.storeName], this.consts.READ_ONLY);
                this.store = emptyTransaction.objectStore(this.storeName);

                // check indexes
                var existingIndexes = Array.prototype.slice.call(this.getIndexList());
                this.indexes.forEach(function (indexData) {
                    var indexName = indexData.name;

                    if (!indexName) {
                        preventSuccessCallback = true;
                        this.onError(new Error('Cannot create index: No index name given.'));
                        return;
                    }

                    this.normalizeIndexData(indexData);

                    if (this.hasIndex(indexName)) {
                        // check if it complies
                        var actualIndex = this.store.index(indexName);
                        var complies = this.indexComplies(actualIndex, indexData);
                        if (!complies) {
                            preventSuccessCallback = true;
                            this.onError(new Error('Cannot modify index "' + indexName + '" for current version. Please bump version number to ' + ( this.dbVersion + 1 ) + '.'));
                        }

                        existingIndexes.splice(existingIndexes.indexOf(indexName), 1);
                    } else {
                        preventSuccessCallback = true;
                        this.onError(new Error('Cannot create new index "' + indexName + '" for current version. Please bump version number to ' + ( this.dbVersion + 1 ) + '.'));
                    }

                }, this);

                if (existingIndexes.length) {
                    preventSuccessCallback = true;
                    this.onError(new Error('Cannot delete index(es) "' + existingIndexes.toString() + '" for current version. Please bump version number to ' + ( this.dbVersion + 1 ) + '.'));
                }

                preventSuccessCallback || this.onStoreReady();
            }.bind(this);

            openRequest.onupgradeneeded = function (/* IDBVersionChangeEvent */ event) {

                this.db = event.target.result;

                if (this.db.objectStoreNames.contains(this.storeName)) {
                    this.store = event.target.transaction.objectStore(this.storeName);
                } else {
                    var optionalParameters = {autoIncrement: this.autoIncrement};
                    if (this.keyPath !== null) {
                        optionalParameters.keyPath = this.keyPath;
                    }
                    this.store = this.db.createObjectStore(this.storeName, optionalParameters);
                }

                var existingIndexes = Array.prototype.slice.call(this.getIndexList());
                this.indexes.forEach(function (indexData) {
                    var indexName = indexData.name;

                    if (!indexName) {
                        preventSuccessCallback = true;
                        this.onError(new Error('Cannot create index: No index name given.'));
                    }

                    this.normalizeIndexData(indexData);

                    if (this.hasIndex(indexName)) {
                        // check if it complies
                        var actualIndex = this.store.index(indexName);
                        var complies = this.indexComplies(actualIndex, indexData);
                        if (!complies) {
                            // index differs, need to delete and re-create
                            this.store.deleteIndex(indexName);
                            this.store.createIndex(indexName, indexData.keyPath, {
                                unique: indexData.unique,
                                multiEntry: indexData.multiEntry
                            });
                        }

                        existingIndexes.splice(existingIndexes.indexOf(indexName), 1);
                    } else {
                        this.store.createIndex(indexName, indexData.keyPath, {
                            unique: indexData.unique,
                            multiEntry: indexData.multiEntry
                        });
                    }

                }, this);

                if (existingIndexes.length) {
                    existingIndexes.forEach(function (_indexName) {
                        this.store.deleteIndex(_indexName);
                    }, this);
                }

            }.bind(this);
        },

        /**
         * Deletes the database used for this store if the IDB implementations
         * provides that functionality.
         *
         * @param {Function} [onSuccess] A callback that is called if deletion
         *  was successful.
         * @param {Function} [onError] A callback that is called if deletion
         *  failed.
         */
        deleteDatabase: function (onSuccess, onError) {
            if (this.idb.deleteDatabase) {
                this.db.close();
                var deleteRequest = this.idb.deleteDatabase(this.dbName);
                deleteRequest.onsuccess = onSuccess;
                deleteRequest.onerror = onError;
            } else {
                onError(new Error('Browser does not support IndexedDB deleteDatabase!'));
            }
        },

        /*********************
         * data manipulation *
         *********************/

        /**
         * Puts an object into the store. If an entry with the given id exists,
         * it will be overwritten. This method has a different signature for inline
         * keys and out-of-line keys; please see the examples below.
         *
         * @param {*} [key] The key to store. This is only needed if IDBWrapper
         *  is set to use out-of-line keys. For inline keys - the default scenario -
         *  this can be omitted.
         * @param {Object} value The data object to store.
         * @param {Function} [onSuccess] A callback that is called if insertion
         *  was successful.
         * @param {Function} [onError] A callback that is called if insertion
         *  failed.
         * @returns {IDBTransaction} The transaction used for this operation.
         * @example
         // Storing an object, using inline keys (the default scenario):
         var myCustomer = {
             customerid: 2346223,
             lastname: 'Doe',
             firstname: 'John'
         };
         myCustomerStore.put(myCustomer, mySuccessHandler, myErrorHandler);
         // Note that passing success- and error-handlers is optional.
         * @example
         // Storing an object, using out-of-line keys:
         var myCustomer = {
             lastname: 'Doe',
             firstname: 'John'
         };
         myCustomerStore.put(2346223, myCustomer, mySuccessHandler, myErrorHandler);
         // Note that passing success- and error-handlers is optional.
         */
        put: function (key, value, onSuccess, onError) {
            if (this.keyPath !== null) {
                onError = onSuccess;
                onSuccess = value;
                value = key;
            }
            onError || (onError = defaultErrorHandler);
            onSuccess || (onSuccess = defaultSuccessHandler);

            var hasSuccess = false,
                result = null,
                putRequest;

            var putTransaction = this.db.transaction([this.storeName], this.consts.READ_WRITE);
            putTransaction.oncomplete = function () {
                var callback = hasSuccess ? onSuccess : onError;
                callback(result);
            };
            putTransaction.onabort = onError;
            putTransaction.onerror = onError;

            if (this.keyPath !== null) { // in-line keys
                this._addIdPropertyIfNeeded(value);
                putRequest = putTransaction.objectStore(this.storeName).put(value);
            } else { // out-of-line keys
                putRequest = putTransaction.objectStore(this.storeName).put(value, key);
            }
            putRequest.onsuccess = function (event) {
                hasSuccess = true;
                result = event.target.result;
            };
            putRequest.onerror = onError;

            return putTransaction;
        },

        /**
         * Retrieves an object from the store. If no entry exists with the given id,
         * the success handler will be called with null as first and only argument.
         *
         * @param {*} key The id of the object to fetch.
         * @param {Function} [onSuccess] A callback that is called if fetching
         *  was successful. Will receive the object as only argument.
         * @param {Function} [onError] A callback that will be called if an error
         *  occurred during the operation.
         * @returns {IDBTransaction} The transaction used for this operation.
         */
        get: function (key, onSuccess, onError) {
            onError || (onError = defaultErrorHandler);
            onSuccess || (onSuccess = defaultSuccessHandler);

            var hasSuccess = false,
                result = null;

            var getTransaction = this.db.transaction([this.storeName], this.consts.READ_ONLY);
            getTransaction.oncomplete = function () {
                var callback = hasSuccess ? onSuccess : onError;
                callback(result);
            };
            getTransaction.onabort = onError;
            getTransaction.onerror = onError;
            var getRequest = getTransaction.objectStore(this.storeName).get(key);
            getRequest.onsuccess = function (event) {
                hasSuccess = true;
                result = event.target.result;
            };
            getRequest.onerror = onError;

            return getTransaction;
        },

        /**
         * Removes an object from the store.
         *
         * @param {*} key The id of the object to remove.
         * @param {Function} [onSuccess] A callback that is called if the removal
         *  was successful.
         * @param {Function} [onError] A callback that will be called if an error
         *  occurred during the operation.
         * @returns {IDBTransaction} The transaction used for this operation.
         */
        remove: function (key, onSuccess, onError) {
            onError || (onError = defaultErrorHandler);
            onSuccess || (onSuccess = defaultSuccessHandler);

            var hasSuccess = false,
                result = null;

            var removeTransaction = this.db.transaction([this.storeName], this.consts.READ_WRITE);
            removeTransaction.oncomplete = function () {
                var callback = hasSuccess ? onSuccess : onError;
                callback(result);
            };
            removeTransaction.onabort = onError;
            removeTransaction.onerror = onError;

            var deleteRequest = removeTransaction.objectStore(this.storeName)['delete'](key);
            deleteRequest.onsuccess = function (event) {
                hasSuccess = true;
                result = event.target.result;
            };
            deleteRequest.onerror = onError;

            return removeTransaction;
        },

        /**
         * Runs a batch of put and/or remove operations on the store.
         *
         * @param {Array} dataArray An array of objects containing the operation to run
         *  and the data object (for put operations).
         * @param {Function} [onSuccess] A callback that is called if all operations
         *  were successful.
         * @param {Function} [onError] A callback that is called if an error
         *  occurred during one of the operations.
         * @returns {IDBTransaction} The transaction used for this operation.
         */
        batch: function (dataArray, onSuccess, onError) {
            onError || (onError = defaultErrorHandler);
            onSuccess || (onSuccess = defaultSuccessHandler);

            if (Object.prototype.toString.call(dataArray) != '[object Array]') {
                onError(new Error('dataArray argument must be of type Array.'));
            } else if (dataArray.length === 0) {
                return onSuccess(true);
            }

            var count = dataArray.length;
            var called = false;
            var hasSuccess = false;

            var batchTransaction = this.db.transaction([this.storeName], this.consts.READ_WRITE);
            batchTransaction.oncomplete = function () {
                var callback = hasSuccess ? onSuccess : onError;
                callback(hasSuccess);
            };
            batchTransaction.onabort = onError;
            batchTransaction.onerror = onError;


            var onItemSuccess = function () {
                count--;
                if (count === 0 && !called) {
                    called = true;
                    hasSuccess = true;
                }
            };

            dataArray.forEach(function (operation) {
                var type = operation.type;
                var key = operation.key;
                var value = operation.value;

                var onItemError = function (err) {
                    batchTransaction.abort();
                    if (!called) {
                        called = true;
                        onError(err, type, key);
                    }
                };

                if (type == 'remove') {
                    var deleteRequest = batchTransaction.objectStore(this.storeName)['delete'](key);
                    deleteRequest.onsuccess = onItemSuccess;
                    deleteRequest.onerror = onItemError;
                } else if (type == 'put') {
                    var putRequest;
                    if (this.keyPath !== null) { // in-line keys
                        this._addIdPropertyIfNeeded(value);
                        putRequest = batchTransaction.objectStore(this.storeName).put(value);
                    } else { // out-of-line keys
                        putRequest = batchTransaction.objectStore(this.storeName).put(value, key);
                    }
                    putRequest.onsuccess = onItemSuccess;
                    putRequest.onerror = onItemError;
                }
            }, this);

            return batchTransaction;
        },

        /**
         * Takes an array of objects and stores them in a single transaction.
         *
         * @param {Array} dataArray An array of objects to store
         * @param {Function} [onSuccess] A callback that is called if all operations
         *  were successful.
         * @param {Function} [onError] A callback that is called if an error
         *  occurred during one of the operations.
         * @returns {IDBTransaction} The transaction used for this operation.
         */
        putBatch: function (dataArray, onSuccess, onError) {
            var batchData = dataArray.map(function (item) {
                return {type: 'put', value: item};
            });

            return this.batch(batchData, onSuccess, onError);
        },

        /**
         * Like putBatch, takes an array of objects and stores them in a single
         * transaction, but allows processing of the result values.  Returns the
         * processed records containing the key for newly created records to the
         * onSuccess calllback instead of only returning true or false for success.
         * In addition, added the option for the caller to specify a key field that
         * should be set to the newly created key.
         *
         * @param {Array} dataArray An array of objects to store
         * @param {Object} [options] An object containing optional options
         * @param {String} [options.keyField=this.keyPath] Specifies a field in the record to update
         *  with the auto-incrementing key. Defaults to the store's keyPath.
         * @param {Function} [onSuccess] A callback that is called if all operations
         *  were successful.
         * @param {Function} [onError] A callback that is called if an error
         *  occurred during one of the operations.
         * @returns {IDBTransaction} The transaction used for this operation.
         *
         */
        upsertBatch: function (dataArray, options, onSuccess, onError) {
            // handle `dataArray, onSuccess, onError` signature
            if (typeof options == 'function') {
                onSuccess = options;
                onError = onSuccess;
                options = {};
            }

            onError || (onError = defaultErrorHandler);
            onSuccess || (onSuccess = defaultSuccessHandler);
            options || (options = {});

            if (Object.prototype.toString.call(dataArray) != '[object Array]') {
                onError(new Error('dataArray argument must be of type Array.'));
            }

            var keyField = options.keyField || this.keyPath;
            var count = dataArray.length;
            var called = false;
            var hasSuccess = false;
            var index = 0; // assume success callbacks are executed in order

            var batchTransaction = this.db.transaction([this.storeName], this.consts.READ_WRITE);
            batchTransaction.oncomplete = function () {
                if (hasSuccess) {
                    onSuccess(dataArray);
                } else {
                    onError(false);
                }
            };
            batchTransaction.onabort = onError;
            batchTransaction.onerror = onError;

            var onItemSuccess = function (event) {
                var record = dataArray[index++];
                record[keyField] = event.target.result;

                count--;
                if (count === 0 && !called) {
                    called = true;
                    hasSuccess = true;
                }
            };

            dataArray.forEach(function (record) {
                var key = record.key;

                var onItemError = function (err) {
                    batchTransaction.abort();
                    if (!called) {
                        called = true;
                        onError(err);
                    }
                };

                var putRequest;
                if (this.keyPath !== null) { // in-line keys
                    this._addIdPropertyIfNeeded(record);
                    putRequest = batchTransaction.objectStore(this.storeName).put(record);
                } else { // out-of-line keys
                    putRequest = batchTransaction.objectStore(this.storeName).put(record, key);
                }
                putRequest.onsuccess = onItemSuccess;
                putRequest.onerror = onItemError;
            }, this);

            return batchTransaction;
        },

        /**
         * Takes an array of keys and removes matching objects in a single
         * transaction.
         *
         * @param {Array} keyArray An array of keys to remove
         * @param {Function} [onSuccess] A callback that is called if all operations
         *  were successful.
         * @param {Function} [onError] A callback that is called if an error
         *  occurred during one of the operations.
         * @returns {IDBTransaction} The transaction used for this operation.
         */
        removeBatch: function (keyArray, onSuccess, onError) {
            var batchData = keyArray.map(function (key) {
                return {type: 'remove', key: key};
            });

            return this.batch(batchData, onSuccess, onError);
        },

        /**
         * Takes an array of keys and fetches matching objects
         *
         * @param {Array} keyArray An array of keys identifying the objects to fetch
         * @param {Function} [onSuccess] A callback that is called if all operations
         *  were successful.
         * @param {Function} [onError] A callback that is called if an error
         *  occurred during one of the operations.
         * @param {String} [arrayType='sparse'] The type of array to pass to the
         *  success handler. May be one of 'sparse', 'dense' or 'skip'. Defaults to
         *  'sparse'. This parameter specifies how to handle the situation if a get
         *  operation did not throw an error, but there was no matching object in
         *  the database. In most cases, 'sparse' provides the most desired
         *  behavior. See the examples for details.
         * @returns {IDBTransaction} The transaction used for this operation.
         * @example
         // given that there are two objects in the database with the keypath
         // values 1 and 2, and the call looks like this:
         myStore.getBatch([1, 5, 2], onError, function (data) { … }, arrayType);

         // this is what the `data` array will be like:

         // arrayType == 'sparse':
         // data is a sparse array containing two entries and having a length of 3:
         [Object, 2: Object]
         0: Object
         2: Object
         length: 3
         // calling forEach on data will result in the callback being called two
         // times, with the index parameter matching the index of the key in the
         // keyArray.

         // arrayType == 'dense':
         // data is a dense array containing three entries and having a length of 3,
         // where data[1] is of type undefined:
         [Object, undefined, Object]
         0: Object
         1: undefined
         2: Object
         length: 3
         // calling forEach on data will result in the callback being called three
         // times, with the index parameter matching the index of the key in the
         // keyArray, but the second call will have undefined as first argument.

         // arrayType == 'skip':
         // data is a dense array containing two entries and having a length of 2:
         [Object, Object]
         0: Object
         1: Object
         length: 2
         // calling forEach on data will result in the callback being called two
         // times, with the index parameter not matching the index of the key in the
         // keyArray.
         */
        getBatch: function (keyArray, onSuccess, onError, arrayType) {
            onError || (onError = defaultErrorHandler);
            onSuccess || (onSuccess = defaultSuccessHandler);
            arrayType || (arrayType = 'sparse');

            if (Object.prototype.toString.call(keyArray) != '[object Array]') {
                onError(new Error('keyArray argument must be of type Array.'));
            } else if (keyArray.length === 0) {
                return onSuccess([]);
            }

            var data = [];
            var count = keyArray.length;
            var hasSuccess = false;
            var result = null;

            var batchTransaction = this.db.transaction([this.storeName], this.consts.READ_ONLY);
            batchTransaction.oncomplete = function () {
                var callback = hasSuccess ? onSuccess : onError;
                callback(result);
            };
            batchTransaction.onabort = onError;
            batchTransaction.onerror = onError;

            var onItemSuccess = function (event) {
                if (event.target.result || arrayType == 'dense') {
                    data.push(event.target.result);
                } else if (arrayType == 'sparse') {
                    data.length++;
                }
                count--;
                if (count === 0) {
                    hasSuccess = true;
                    result = data;
                }
            };

            keyArray.forEach(function (key) {

                var onItemError = function (err) {
                    result = err;
                    onError(err);
                    batchTransaction.abort();
                };

                var getRequest = batchTransaction.objectStore(this.storeName).get(key);
                getRequest.onsuccess = onItemSuccess;
                getRequest.onerror = onItemError;

            }, this);

            return batchTransaction;
        },

        /**
         * Fetches all entries in the store.
         *
         * @param {Function} [onSuccess] A callback that is called if the operation
         *  was successful. Will receive an array of objects.
         * @param {Function} [onError] A callback that will be called if an error
         *  occurred during the operation.
         * @returns {IDBTransaction} The transaction used for this operation.
         */
        getAll: function (onSuccess, onError) {
            onError || (onError = defaultErrorHandler);
            onSuccess || (onSuccess = defaultSuccessHandler);
            var getAllTransaction = this.db.transaction([this.storeName], this.consts.READ_ONLY);
            var store = getAllTransaction.objectStore(this.storeName);
            if (store.getAll) {
                this._getAllNative(getAllTransaction, store, onSuccess, onError);
            } else {
                this._getAllCursor(getAllTransaction, store, onSuccess, onError);
            }

            return getAllTransaction;
        },

        /**
         * Implements getAll for IDB implementations that have a non-standard
         * getAll() method.
         *
         * @param {IDBTransaction} getAllTransaction An open READ transaction.
         * @param {IDBObjectStore} store A reference to the store.
         * @param {Function} onSuccess A callback that will be called if the
         *  operation was successful.
         * @param {Function} onError A callback that will be called if an
         *  error occurred during the operation.
         * @private
         */
        _getAllNative: function (getAllTransaction, store, onSuccess, onError) {
            var hasSuccess = false,
                result = null;

            getAllTransaction.oncomplete = function () {
                var callback = hasSuccess ? onSuccess : onError;
                callback(result);
            };
            getAllTransaction.onabort = onError;
            getAllTransaction.onerror = onError;

            var getAllRequest = store.getAll();
            getAllRequest.onsuccess = function (event) {
                hasSuccess = true;
                result = event.target.result;
            };
            getAllRequest.onerror = onError;
        },

        /**
         * Implements getAll for IDB implementations that do not have a getAll()
         * method.
         *
         * @param {IDBTransaction} getAllTransaction An open READ transaction.
         * @param {IDBObjectStore} store A reference to the store.
         * @param {Function} onSuccess A callback that will be called if the
         *  operation was successful.
         * @param {Function} onError A callback that will be called if an
         *  error occurred during the operation.
         * @private
         */
        _getAllCursor: function (getAllTransaction, store, onSuccess, onError) {
            var all = [],
                hasSuccess = false,
                result = null;

            getAllTransaction.oncomplete = function () {
                var callback = hasSuccess ? onSuccess : onError;
                callback(result);
            };
            getAllTransaction.onabort = onError;
            getAllTransaction.onerror = onError;

            var cursorRequest = store.openCursor();
            cursorRequest.onsuccess = function (event) {
                var cursor = event.target.result;
                if (cursor) {
                    all.push(cursor.value);
                    cursor['continue']();
                }
                else {
                    hasSuccess = true;
                    result = all;
                }
            };
            cursorRequest.onError = onError;
        },

        /**
         * Clears the store, i.e. deletes all entries in the store.
         *
         * @param {Function} [onSuccess] A callback that will be called if the
         *  operation was successful.
         * @param {Function} [onError] A callback that will be called if an
         *  error occurred during the operation.
         * @returns {IDBTransaction} The transaction used for this operation.
         */
        clear: function (onSuccess, onError) {
            onError || (onError = defaultErrorHandler);
            onSuccess || (onSuccess = defaultSuccessHandler);

            var hasSuccess = false,
                result = null;

            var clearTransaction = this.db.transaction([this.storeName], this.consts.READ_WRITE);
            clearTransaction.oncomplete = function () {
                var callback = hasSuccess ? onSuccess : onError;
                callback(result);
            };
            clearTransaction.onabort = onError;
            clearTransaction.onerror = onError;

            var clearRequest = clearTransaction.objectStore(this.storeName).clear();
            clearRequest.onsuccess = function (event) {
                hasSuccess = true;
                result = event.target.result;
            };
            clearRequest.onerror = onError;

            return clearTransaction;
        },

        /**
         * Checks if an id property needs to present on a object and adds one if
         * necessary.
         *
         * @param {Object} dataObj The data object that is about to be stored
         * @private
         */
        _addIdPropertyIfNeeded: function (dataObj) {
            if (typeof dataObj[this.keyPath] == 'undefined') {
                dataObj[this.keyPath] = this._insertIdCount++ + Date.now();
            }
        },

        /************
         * indexing *
         ************/

        /**
         * Returns a DOMStringList of index names of the store.
         *
         * @return {DOMStringList} The list of index names
         */
        getIndexList: function () {
            return this.store.indexNames;
        },

        /**
         * Checks if an index with the given name exists in the store.
         *
         * @param {String} indexName The name of the index to look for
         * @return {Boolean} Whether the store contains an index with the given name
         */
        hasIndex: function (indexName) {
            return this.store.indexNames.contains(indexName);
        },

        /**
         * Normalizes an object containing index data and assures that all
         * properties are set.
         *
         * @param {Object} indexData The index data object to normalize
         * @param {String} indexData.name The name of the index
         * @param {String} [indexData.keyPath] The key path of the index
         * @param {Boolean} [indexData.unique] Whether the index is unique
         * @param {Boolean} [indexData.multiEntry] Whether the index is multi entry
         */
        normalizeIndexData: function (indexData) {
            indexData.keyPath = indexData.keyPath || indexData.name;
            indexData.unique = !!indexData.unique;
            indexData.multiEntry = !!indexData.multiEntry;
        },

        /**
         * Checks if an actual index complies with an expected index.
         *
         * @param {IDBIndex} actual The actual index found in the store
         * @param {Object} expected An Object describing an expected index
         * @return {Boolean} Whether both index definitions are identical
         */
        indexComplies: function (actual, expected) {
            var complies = ['keyPath', 'unique', 'multiEntry'].every(function (key) {
                // IE10 returns undefined for no multiEntry
                if (key == 'multiEntry' && actual[key] === undefined && expected[key] === false) {
                    return true;
                }
                // Compound keys
                if (key == 'keyPath' && Object.prototype.toString.call(expected[key]) == '[object Array]') {
                    var exp = expected.keyPath;
                    var act = actual.keyPath;

                    // IE10 can't handle keyPath sequences and stores them as a string.
                    // The index will be unusable there, but let's still return true if
                    // the keyPath sequence matches.
                    if (typeof act == 'string') {
                        return exp.toString() == act;
                    }

                    // Chrome/Opera stores keyPath squences as DOMStringList, Firefox
                    // as Array
                    if (!(typeof act.contains == 'function' || typeof act.indexOf == 'function')) {
                        return false;
                    }

                    if (act.length !== exp.length) {
                        return false;
                    }

                    for (var i = 0, m = exp.length; i < m; i++) {
                        if (!( (act.contains && act.contains(exp[i])) || act.indexOf(exp[i] !== -1) )) {
                            return false;
                        }
                    }
                    return true;
                }
                return expected[key] == actual[key];
            });
            return complies;
        },

        /**********
         * cursor *
         **********/

        /**
         * Iterates over the store using the given options and calling onItem
         * for each entry matching the options.
         *
         * @param {Function} onItem A callback to be called for each match
         * @param {Object} [options] An object defining specific options
         * @param {String} [options.index=null] A name of an IDBIndex to operate on
         * @param {String} [options.order=ASC] The order in which to provide the
         *  results, can be 'DESC' or 'ASC'
         * @param {Boolean} [options.autoContinue=true] Whether to automatically
         *  iterate the cursor to the next result
         * @param {Boolean} [options.filterDuplicates=false] Whether to exclude
         *  duplicate matches
         * @param {IDBKeyRange} [options.keyRange=null] An IDBKeyRange to use
         * @param {Boolean} [options.writeAccess=false] Whether grant write access
         *  to the store in the onItem callback
         * @param {Function} [options.onEnd=null] A callback to be called after
         *  iteration has ended
         * @param {Function} [options.onError=throw] A callback to be called
         *  if an error occurred during the operation.
         * @param {Number} [options.limit=Infinity] Limit the number of returned
         *  results to this number
         * @param {Number} [options.offset=0] Skip the provided number of results
         *  in the resultset
         * @param {Boolean} [options.allowItemRejection=false] Allows the onItem
         * function to return a Boolean to accept or reject the current item
         * @returns {IDBTransaction} The transaction used for this operation.
         */
        iterate: function (onItem, options) {
            options = mixin({
                index: null,
                order: 'ASC',
                autoContinue: true,
                filterDuplicates: false,
                keyRange: null,
                writeAccess: false,
                onEnd: null,
                onError: defaultErrorHandler,
                limit: Infinity,
                offset: 0,
                allowItemRejection: false
            }, options || {});

            var directionType = options.order.toLowerCase() == 'desc' ? 'PREV' : 'NEXT';
            if (options.filterDuplicates) {
                directionType += '_NO_DUPLICATE';
            }

            var hasSuccess = false;
            var cursorTransaction = this.db.transaction([this.storeName], this.consts[options.writeAccess ? 'READ_WRITE' : 'READ_ONLY']);
            var cursorTarget = cursorTransaction.objectStore(this.storeName);
            if (options.index) {
                cursorTarget = cursorTarget.index(options.index);
            }
            var recordCount = 0;

            cursorTransaction.oncomplete = function () {
                if (!hasSuccess) {
                    options.onError(null);
                    return;
                }
                if (options.onEnd) {
                    options.onEnd();
                } else {
                    onItem(null);
                }
            };
            cursorTransaction.onabort = options.onError;
            cursorTransaction.onerror = options.onError;

            var cursorRequest = cursorTarget.openCursor(options.keyRange, this.consts[directionType]);
            cursorRequest.onerror = options.onError;
            cursorRequest.onsuccess = function (event) {
                var cursor = event.target.result;
                if (cursor) {
                    if (options.offset) {
                        cursor.advance(options.offset);
                        options.offset = 0;
                    } else {
                        var onItemReturn = onItem(cursor.value, cursor, cursorTransaction);
                        if (!options.allowItemRejection || onItemReturn !== false) {
                            recordCount++;
                        }
                        if (options.autoContinue) {
                            if (recordCount + options.offset < options.limit) {
                                cursor['continue']();
                            } else {
                                hasSuccess = true;
                            }
                        }
                    }
                } else {
                    hasSuccess = true;
                }
            };

            return cursorTransaction;
        },

        /**
         * Runs a query against the store and passes an array containing matched
         * objects to the success handler.
         *
         * @param {Function} onSuccess A callback to be called when the operation
         *  was successful.
         * @param {Object} [options] An object defining specific options
         * @param {String} [options.index=null] A name of an IDBIndex to operate on
         * @param {String} [options.order=ASC] The order in which to provide the
         *  results, can be 'DESC' or 'ASC'
         * @param {Boolean} [options.filterDuplicates=false] Whether to exclude
         *  duplicate matches
         * @param {IDBKeyRange} [options.keyRange=null] An IDBKeyRange to use
         * @param {Function} [options.onError=throw] A callback to be called
         *  if an error occurred during the operation.
         * @param {Number} [options.limit=Infinity] Limit the number of returned
         *  results to this number
         * @param {Number} [options.offset=0] Skip the provided number of results
         *  in the resultset
         * @param {Function} [options.filter=null] A custom filter function to
         *  apply to query resuts before returning. Must return `false` to reject
         *  an item. Can be combined with keyRanges.
         * @returns {IDBTransaction} The transaction used for this operation.
         */
        query: function (onSuccess, options) {
            var result = [],
                processedItems = 0;
            options = options || {};
            options.autoContinue = true;
            options.writeAccess = false;
            options.allowItemRejection = !!options.filter;
            options.onEnd = function () {
                onSuccess(result, processedItems);
            };
            return this.iterate(function (item) {
                processedItems++;
                var accept = options.filter ? options.filter(item) : true;
                if (accept !== false) {
                    result.push(item);
                }
                return accept;
            }, options);
        },

        /**
         *
         * Runs a query against the store, but only returns the number of matches
         * instead of the matches itself.
         *
         * @param {Function} onSuccess A callback to be called if the opration
         *  was successful.
         * @param {Object} [options] An object defining specific options
         * @param {String} [options.index=null] A name of an IDBIndex to operate on
         * @param {IDBKeyRange} [options.keyRange=null] An IDBKeyRange to use
         * @param {Function} [options.onError=throw] A callback to be called if an error
         *  occurred during the operation.
         * @returns {IDBTransaction} The transaction used for this operation.
         */
        count: function (onSuccess, options) {

            options = mixin({
                index: null,
                keyRange: null
            }, options || {});

            var onError = options.onError || defaultErrorHandler;

            var hasSuccess = false,
                result = null;

            var cursorTransaction = this.db.transaction([this.storeName], this.consts.READ_ONLY);
            cursorTransaction.oncomplete = function () {
                var callback = hasSuccess ? onSuccess : onError;
                callback(result);
            };
            cursorTransaction.onabort = onError;
            cursorTransaction.onerror = onError;

            var cursorTarget = cursorTransaction.objectStore(this.storeName);
            if (options.index) {
                cursorTarget = cursorTarget.index(options.index);
            }
            var countRequest = cursorTarget.count(options.keyRange);
            countRequest.onsuccess = function (evt) {
                hasSuccess = true;
                result = evt.target.result;
            };
            countRequest.onError = onError;

            return cursorTransaction;
        },

        /**************/
        /* key ranges */
        /**************/

        /**
         * Creates a key range using specified options. This key range can be
         * handed over to the count() and iterate() methods.
         *
         * Note: You must provide at least one or both of "lower" or "upper" value.
         *
         * @param {Object} options The options for the key range to create
         * @param {*} [options.lower] The lower bound
         * @param {Boolean} [options.excludeLower] Whether to exclude the lower
         *  bound passed in options.lower from the key range
         * @param {*} [options.upper] The upper bound
         * @param {Boolean} [options.excludeUpper] Whether to exclude the upper
         *  bound passed in options.upper from the key range
         * @param {*} [options.only] A single key value. Use this if you need a key
         *  range that only includes one value for a key. Providing this
         *  property invalidates all other properties.
         * @return {IDBKeyRange} The IDBKeyRange representing the specified options
         */
        makeKeyRange: function (options) {
            /*jshint onecase:true */
            var keyRange,
                hasLower = typeof options.lower != 'undefined',
                hasUpper = typeof options.upper != 'undefined',
                isOnly = typeof options.only != 'undefined';

            switch (true) {
                case isOnly:
                    keyRange = this.keyRange.only(options.only);
                    break;
                case hasLower && hasUpper:
                    keyRange = this.keyRange.bound(options.lower, options.upper, options.excludeLower, options.excludeUpper);
                    break;
                case hasLower:
                    keyRange = this.keyRange.lowerBound(options.lower, options.excludeLower);
                    break;
                case hasUpper:
                    keyRange = this.keyRange.upperBound(options.upper, options.excludeUpper);
                    break;
                default:
                    throw new Error('Cannot create KeyRange. Provide one or both of "lower" or "upper" value, or an "only" value.');
            }

            return keyRange;

        }

    };

    /** helpers **/
    var empty = {};

    function mixin (target, source) {
        var name, s;
        for (name in source) {
            s = source[name];
            if (s !== empty[name] && s !== target[name]) {
                target[name] = s;
            }
        }
        return target;
    }

    function hasVersionError(errorEvent) {
        if ('error' in errorEvent.target) {
            return errorEvent.target.error.name == 'VersionError';
        } else if ('errorCode' in errorEvent.target) {
            return errorEvent.target.errorCode == 12;
        }
        return false;
    }

    IDBStore.prototype = proto;
    IDBStore.version = proto.version;

    return IDBStore;

}, commonjsGlobal);
});

var xtend = extend;

function extend() {
    var target = {};

    for (var i = 0; i < arguments.length; i++) {
        var source = arguments[i];

        for (var key in source) {
            if (source.hasOwnProperty(key)) {
                target[key] = source[key];
            }
        }
    }

    return target
}

/* Copyright (c) 2013 Rod Vagg, MIT License */

function AbstractIterator (db) {
  this.db = db;
  this._ended = false;
  this._nexting = false;
}

AbstractIterator.prototype.next = function (callback) {
  var self = this;

  if (typeof callback != 'function')
    throw new Error('next() requires a callback argument')

  if (self._ended)
    return callback(new Error('cannot call next() after end()'))
  if (self._nexting)
    return callback(new Error('cannot call next() before previous next() has completed'))

  self._nexting = true;
  if (typeof self._next == 'function') {
    return self._next(function () {
      self._nexting = false;
      callback.apply(null, arguments);
    })
  }

  process.nextTick(function () {
    self._nexting = false;
    callback();
  });
};

AbstractIterator.prototype.end = function (callback) {
  if (typeof callback != 'function')
    throw new Error('end() requires a callback argument')

  if (this._ended)
    return callback(new Error('end() already called on iterator'))

  this._ended = true;

  if (typeof this._end == 'function')
    return this._end(callback)

  process.nextTick(callback);
};

var abstractIterator = AbstractIterator;

/* Copyright (c) 2013 Rod Vagg, MIT License */

function AbstractChainedBatch (db) {
  this._db         = db;
  this._operations = [];
  this._written    = false;
}

AbstractChainedBatch.prototype._checkWritten = function () {
  if (this._written)
    throw new Error('write() already called on this batch')
};

AbstractChainedBatch.prototype.put = function (key, value) {
  this._checkWritten();

  var err = this._db._checkKeyValue(key, 'key', this._db._isBuffer);
  if (err) throw err
  err = this._db._checkKeyValue(value, 'value', this._db._isBuffer);
  if (err) throw err

  if (!this._db._isBuffer(key)) key = String(key);
  if (!this._db._isBuffer(value)) value = String(value);

  if (typeof this._put == 'function' )
    this._put(key, value);
  else
    this._operations.push({ type: 'put', key: key, value: value });

  return this
};

AbstractChainedBatch.prototype.del = function (key) {
  this._checkWritten();

  var err = this._db._checkKeyValue(key, 'key', this._db._isBuffer);
  if (err) throw err

  if (!this._db._isBuffer(key)) key = String(key);

  if (typeof this._del == 'function' )
    this._del(key);
  else
    this._operations.push({ type: 'del', key: key });

  return this
};

AbstractChainedBatch.prototype.clear = function () {
  this._checkWritten();

  this._operations = [];

  if (typeof this._clear == 'function' )
    this._clear();

  return this
};

AbstractChainedBatch.prototype.write = function (options, callback) {
  this._checkWritten();

  if (typeof options == 'function')
    callback = options;
  if (typeof callback != 'function')
    throw new Error('write() requires a callback argument')
  if (typeof options != 'object')
    options = {};

  this._written = true;

  if (typeof this._write == 'function' )
    return this._write(callback)

  if (typeof this._db._batch == 'function')
    return this._db._batch(this._operations, options, callback)

  process.nextTick(callback);
};

var abstractChainedBatch = AbstractChainedBatch;

/* Copyright (c) 2013 Rod Vagg, MIT License */



function AbstractLevelDOWN (location) {
  if (!arguments.length || location === undefined)
    throw new Error('constructor requires at least a location argument')

  if (typeof location != 'string')
    throw new Error('constructor requires a location string argument')

  this.location = location;
}

AbstractLevelDOWN.prototype.open = function (options, callback) {
  if (typeof options == 'function')
    callback = options;

  if (typeof callback != 'function')
    throw new Error('open() requires a callback argument')

  if (typeof options != 'object')
    options = {};

  if (typeof this._open == 'function')
    return this._open(options, callback)

  process.nextTick(callback);
};

AbstractLevelDOWN.prototype.close = function (callback) {
  if (typeof callback != 'function')
    throw new Error('close() requires a callback argument')

  if (typeof this._close == 'function')
    return this._close(callback)

  process.nextTick(callback);
};

AbstractLevelDOWN.prototype.get = function (key, options, callback) {
  var err;

  if (typeof options == 'function')
    callback = options;

  if (typeof callback != 'function')
    throw new Error('get() requires a callback argument')

  if (err = this._checkKeyValue(key, 'key', this._isBuffer))
    return callback(err)

  if (!this._isBuffer(key))
    key = String(key);

  if (typeof options != 'object')
    options = {};

  if (typeof this._get == 'function')
    return this._get(key, options, callback)

  process.nextTick(function () { callback(new Error('NotFound')); });
};

AbstractLevelDOWN.prototype.put = function (key, value, options, callback) {
  var err;

  if (typeof options == 'function')
    callback = options;

  if (typeof callback != 'function')
    throw new Error('put() requires a callback argument')

  if (err = this._checkKeyValue(key, 'key', this._isBuffer))
    return callback(err)

  if (err = this._checkKeyValue(value, 'value', this._isBuffer))
    return callback(err)

  if (!this._isBuffer(key))
    key = String(key);

  // coerce value to string in node, don't touch it in browser
  // (indexeddb can store any JS type)
  if (!this._isBuffer(value) && !process.browser)
    value = String(value);

  if (typeof options != 'object')
    options = {};

  if (typeof this._put == 'function')
    return this._put(key, value, options, callback)

  process.nextTick(callback);
};

AbstractLevelDOWN.prototype.del = function (key, options, callback) {
  var err;

  if (typeof options == 'function')
    callback = options;

  if (typeof callback != 'function')
    throw new Error('del() requires a callback argument')

  if (err = this._checkKeyValue(key, 'key', this._isBuffer))
    return callback(err)

  if (!this._isBuffer(key))
    key = String(key);

  if (typeof options != 'object')
    options = {};

  if (typeof this._del == 'function')
    return this._del(key, options, callback)

  process.nextTick(callback);
};

AbstractLevelDOWN.prototype.batch = function (array, options, callback) {
  if (!arguments.length)
    return this._chainedBatch()

  if (typeof options == 'function')
    callback = options;

  if (typeof callback != 'function')
    throw new Error('batch(array) requires a callback argument')

  if (!Array.isArray(array))
    return callback(new Error('batch(array) requires an array argument'))

  if (typeof options != 'object')
    options = {};

  var i = 0
    , l = array.length
    , e
    , err;

  for (; i < l; i++) {
    e = array[i];
    if (typeof e != 'object')
      continue

    if (err = this._checkKeyValue(e.type, 'type', this._isBuffer))
      return callback(err)

    if (err = this._checkKeyValue(e.key, 'key', this._isBuffer))
      return callback(err)

    if (e.type == 'put') {
      if (err = this._checkKeyValue(e.value, 'value', this._isBuffer))
        return callback(err)
    }
  }

  if (typeof this._batch == 'function')
    return this._batch(array, options, callback)

  process.nextTick(callback);
};

//TODO: remove from here, not a necessary primitive
AbstractLevelDOWN.prototype.approximateSize = function (start, end, callback) {
  if (   start == null
      || end == null
      || typeof start == 'function'
      || typeof end == 'function') {
    throw new Error('approximateSize() requires valid `start`, `end` and `callback` arguments')
  }

  if (typeof callback != 'function')
    throw new Error('approximateSize() requires a callback argument')

  if (!this._isBuffer(start))
    start = String(start);

  if (!this._isBuffer(end))
    end = String(end);

  if (typeof this._approximateSize == 'function')
    return this._approximateSize(start, end, callback)

  process.nextTick(function () {
    callback(null, 0);
  });
};

AbstractLevelDOWN.prototype._setupIteratorOptions = function (options) {
  var self = this;

  options = xtend(options)

  ;[ 'start', 'end', 'gt', 'gte', 'lt', 'lte' ].forEach(function (o) {
    if (options[o] && self._isBuffer(options[o]) && options[o].length === 0)
      delete options[o];
  });

  options.reverse = !!options.reverse;

  // fix `start` so it takes into account gt, gte, lt, lte as appropriate
  if (options.reverse && options.lt)
    options.start = options.lt;
  if (options.reverse && options.lte)
    options.start = options.lte;
  if (!options.reverse && options.gt)
    options.start = options.gt;
  if (!options.reverse && options.gte)
    options.start = options.gte;

  if ((options.reverse && options.lt && !options.lte)
    || (!options.reverse && options.gt && !options.gte))
    options.exclusiveStart = true; // start should *not* include matching key

  return options
};

AbstractLevelDOWN.prototype.iterator = function (options) {
  if (typeof options != 'object')
    options = {};

  options = this._setupIteratorOptions(options);

  if (typeof this._iterator == 'function')
    return this._iterator(options)

  return new abstractIterator(this)
};

AbstractLevelDOWN.prototype._chainedBatch = function () {
  return new abstractChainedBatch(this)
};

AbstractLevelDOWN.prototype._isBuffer = function (obj) {
  return Buffer.isBuffer(obj)
};

AbstractLevelDOWN.prototype._checkKeyValue = function (obj, type) {

  if (obj === null || obj === undefined)
    return new Error(type + ' cannot be `null` or `undefined`')

  if (this._isBuffer(obj)) {
    if (obj.length === 0)
      return new Error(type + ' cannot be an empty Buffer')
  } else if (String(obj) === '')
    return new Error(type + ' cannot be an empty String')
};

var AbstractLevelDOWN_1    = AbstractLevelDOWN;
var AbstractIterator_1     = abstractIterator;
var AbstractChainedBatch_1 = abstractChainedBatch;

var abstractLeveldown = {
	AbstractLevelDOWN: AbstractLevelDOWN_1,
	AbstractIterator: AbstractIterator_1,
	AbstractChainedBatch: AbstractChainedBatch_1
};

var ltgt = createCommonjsModule(function (module, exports) {
exports.compare = function (a, b) {

  if(Buffer.isBuffer(a)) {
    var l = Math.min(a.length, b.length);
    for(var i = 0; i < l; i++) {
      var cmp = a[i] - b[i];
      if(cmp) return cmp
    }
    return a.length - b.length
  }

  return a < b ? -1 : a > b ? 1 : 0
};

// to be compatible with the current abstract-leveldown tests
// nullish or empty strings.
// I could use !!val but I want to permit numbers and booleans,
// if possible.

function isDef (val) {
  return val !== undefined && val !== ''
}

function has (range, name) {
  return Object.hasOwnProperty.call(range, name)
}

function hasKey(range, name) {
  return Object.hasOwnProperty.call(range, name) && name
}

var lowerBoundKey = exports.lowerBoundKey = function (range) {
    return (
       hasKey(range, 'gt')
    || hasKey(range, 'gte')
    || hasKey(range, 'min')
    || (range.reverse ? hasKey(range, 'end') : hasKey(range, 'start'))
    || undefined
    )
};

var lowerBound = exports.lowerBound = function (range, def) {
  var k = lowerBoundKey(range);
  return k ? range[k] : def
};

var lowerBoundInclusive = exports.lowerBoundInclusive = function (range) {
  return has(range, 'gt') ? false : true
};

var upperBoundInclusive = exports.upperBoundInclusive =
  function (range) {
    return (has(range, 'lt') /*&& !range.maxEx*/) ? false : true
  };

var lowerBoundExclusive = exports.lowerBoundExclusive =
  function (range) {
    return !lowerBoundInclusive(range)
  };

var upperBoundExclusive = exports.upperBoundExclusive =
  function (range) {
    return !upperBoundInclusive(range)
  };

var upperBoundKey = exports.upperBoundKey = function (range) {
    return (
       hasKey(range, 'lt')
    || hasKey(range, 'lte')
    || hasKey(range, 'max')
    || (range.reverse ? hasKey(range, 'start') : hasKey(range, 'end'))
    || undefined
    )
};

var upperBound = exports.upperBound = function (range, def) {
  var k = upperBoundKey(range);
  return k ? range[k] : def
};

exports.start = function (range, def) {
  return range.reverse ? upperBound(range, def) : lowerBound(range, def)
};
exports.end = function (range, def) {
  return range.reverse ? lowerBound(range, def) : upperBound(range, def)
};
exports.startInclusive = function (range) {
  return (
    range.reverse
  ? upperBoundInclusive(range)
  : lowerBoundInclusive(range)
  )
};
exports.endInclusive = function (range) {
  return (
    range.reverse
  ? lowerBoundInclusive(range)
  : upperBoundInclusive(range)
  )
};

function id (e) { return e }

exports.toLtgt = function (range, _range, map, lower, upper) {
  _range = _range || {};
  map = map || id;
  var defaults = arguments.length > 3;
  var lb = exports.lowerBoundKey(range);
  var ub = exports.upperBoundKey(range);
  if(lb) {
    if(lb === 'gt') _range.gt = map(range.gt, false);
    else            _range.gte = map(range[lb], false);
  }
  else if(defaults)
    _range.gte = map(lower, false);

  if(ub) {
    if(ub === 'lt') _range.lt = map(range.lt, true);
    else            _range.lte = map(range[ub], true);
  }
  else if(defaults)
    _range.lte = map(upper, true);

  if(range.reverse != null)
    _range.reverse = !!range.reverse;

  //if range was used mutably
  //(in level-sublevel it's part of an options object
  //that has more properties on it.)
  if(has(_range, 'max'))   delete _range.max;
  if(has(_range, 'min'))   delete _range.min;
  if(has(_range, 'start')) delete _range.start;
  if(has(_range, 'end'))   delete _range.end;

  return _range
};

exports.contains = function (range, key, compare) {
  compare = compare || exports.compare;

  var lb = lowerBound(range);
  if(isDef(lb)) {
    var cmp = compare(key, lb);
    if(cmp < 0 || (cmp === 0 && lowerBoundExclusive(range)))
      return false
  }

  var ub = upperBound(range);
  if(isDef(ub)) {
    var cmp = compare(key, ub);
    if(cmp > 0 || (cmp === 0) && upperBoundExclusive(range))
      return false
  }

  return true
};

exports.filter = function (range, compare) {
  return function (key) {
    return exports.contains(range, key, compare)
  }
};
});
var ltgt_1 = ltgt.compare;
var ltgt_2 = ltgt.lowerBoundKey;
var ltgt_3 = ltgt.lowerBound;
var ltgt_4 = ltgt.lowerBoundInclusive;
var ltgt_5 = ltgt.upperBoundInclusive;
var ltgt_6 = ltgt.lowerBoundExclusive;
var ltgt_7 = ltgt.upperBoundExclusive;
var ltgt_8 = ltgt.upperBoundKey;
var ltgt_9 = ltgt.upperBound;
var ltgt_10 = ltgt.start;
var ltgt_11 = ltgt.end;
var ltgt_12 = ltgt.startInclusive;
var ltgt_13 = ltgt.endInclusive;
var ltgt_14 = ltgt.toLtgt;
var ltgt_15 = ltgt.contains;
var ltgt_16 = ltgt.filter;

var AbstractIterator$1  = abstractLeveldown.AbstractIterator;


var iterator = Iterator;

function Iterator (db, options) {
  if (!options) options = {};
  this.options = options;
  AbstractIterator$1.call(this, db);
  this._order = options.reverse ? 'DESC': 'ASC';
  this._limit = options.limit;
  this._count = 0;
  this._done  = false;
  var lower = ltgt.lowerBound(options);
  var upper = ltgt.upperBound(options);
  try {
    this._keyRange = lower || upper ? this.db.makeKeyRange({
      lower: lower,
      upper: upper,
      excludeLower: ltgt.lowerBoundExclusive(options),
      excludeUpper: ltgt.upperBoundExclusive(options)
    }) : null;
  } catch (e) {
    // The lower key is greater than the upper key.
    // IndexedDB throws an error, but we'll just return 0 results.
    this._keyRangeError = true;
  }
  this.callback = null;
}

util$2.inherits(Iterator, AbstractIterator$1);

Iterator.prototype.createIterator = function() {
  var self = this;

  self.iterator = self.db.iterate(function () {
    self.onItem.apply(self, arguments);
  }, {
    keyRange: self._keyRange,
    autoContinue: false,
    order: self._order,
    onError: function(err) { console.log('horrible error', err); },
  });
};

// TODO the limit implementation here just ignores all reads after limit has been reached
// it should cancel the iterator instead but I don't know how
Iterator.prototype.onItem = function (value, cursor, cursorTransaction) {
  if (!cursor && this.callback) {
    this.callback();
    this.callback = false;
    return
  }
  var shouldCall = true;

  if (!!this._limit && this._limit > 0 && this._count++ >= this._limit)
    shouldCall = false;

  if (shouldCall) this.callback(false, cursor.key, cursor.value);
  if (cursor) cursor['continue']();
};

Iterator.prototype._next = function (callback) {
  if (!callback) return new Error('next() requires a callback argument')
  if (this._keyRangeError) return callback()
  if (!this._started) {
    this.createIterator();
    this._started = true;
  }
  this.callback = callback;
};

var Buffer$1 = buffer.Buffer;

var isbuffer = isBuffer;

function isBuffer (o) {
  return Buffer$1.isBuffer(o)
    || /\[object (.+Array|Array.+)\]/.test(Object.prototype.toString.call(o));
}

var hasOwn = Object.prototype.hasOwnProperty;
var toString = Object.prototype.toString;

var isFunction = function (fn) {
	var isFunc = (typeof fn === 'function' && !(fn instanceof RegExp)) || toString.call(fn) === '[object Function]';
	if (!isFunc && typeof window !== 'undefined') {
		isFunc = fn === window.setTimeout || fn === window.alert || fn === window.confirm || fn === window.prompt;
	}
	return isFunc;
};

var foreach = function forEach(obj, fn) {
	if (!isFunction(fn)) {
		throw new TypeError('iterator must be a function');
	}
	var i, k,
		isString = typeof obj === 'string',
		l = obj.length,
		context = arguments.length > 2 ? arguments[2] : null;
	if (l === +l) {
		for (i = 0; i < l; i++) {
			if (context === null) {
				fn(isString ? obj.charAt(i) : obj[i], i, obj);
			} else {
				fn.call(context, isString ? obj.charAt(i) : obj[i], i, obj);
			}
		}
	} else {
		for (k in obj) {
			if (hasOwn.call(obj, k)) {
				if (context === null) {
					fn(obj[k], k, obj);
				} else {
					fn.call(context, obj[k], k, obj);
				}
			}
		}
	}
};

var toString$1 = Object.prototype.toString;

var isArguments = function isArguments(value) {
	var str = toString$1.call(value);
	var isArguments = str === '[object Arguments]';
	if (!isArguments) {
		isArguments = str !== '[object Array]'
			&& value !== null
			&& typeof value === 'object'
			&& typeof value.length === 'number'
			&& value.length >= 0
			&& toString$1.call(value.callee) === '[object Function]';
	}
	return isArguments;
};

var shim = createCommonjsModule(function (module) {
(function () {

	// modified from https://github.com/kriskowal/es5-shim
	var has = Object.prototype.hasOwnProperty,
		toString = Object.prototype.toString,
		forEach = foreach,
		isArgs = isArguments,
		hasDontEnumBug = !({'toString': null}).propertyIsEnumerable('toString'),
		hasProtoEnumBug = (function () {}).propertyIsEnumerable('prototype'),
		dontEnums = [
			"toString",
			"toLocaleString",
			"valueOf",
			"hasOwnProperty",
			"isPrototypeOf",
			"propertyIsEnumerable",
			"constructor"
		],
		keysShim;

	keysShim = function keys(object) {
		var isObject = object !== null && typeof object === 'object',
			isFunction = toString.call(object) === '[object Function]',
			isArguments = isArgs(object),
			theKeys = [];

		if (!isObject && !isFunction && !isArguments) {
			throw new TypeError("Object.keys called on a non-object");
		}

		if (isArguments) {
			forEach(object, function (value) {
				theKeys.push(value);
			});
		} else {
			var name,
				skipProto = hasProtoEnumBug && isFunction;

			for (name in object) {
				if (!(skipProto && name === 'prototype') && has.call(object, name)) {
					theKeys.push(name);
				}
			}
		}

		if (hasDontEnumBug) {
			var ctor = object.constructor,
				skipConstructor = ctor && ctor.prototype === object;

			forEach(dontEnums, function (dontEnum) {
				if (!(skipConstructor && dontEnum === 'constructor') && has.call(object, dontEnum)) {
					theKeys.push(dontEnum);
				}
			});
		}
		return theKeys;
	};

	module.exports = keysShim;
}());
});

var objectKeys = Object.keys || shim;

var hasKeys_1 = hasKeys;

function hasKeys(source) {
    return source !== null &&
        (typeof source === "object" ||
        typeof source === "function")
}

var xtend$1 = extend$1;

function extend$1() {
    var target = {};

    for (var i = 0; i < arguments.length; i++) {
        var source = arguments[i];

        if (!hasKeys_1(source)) {
            continue
        }

        var keys = objectKeys(source);

        for (var j = 0; j < keys.length; j++) {
            var name = keys[j];
            target[name] = source[name];
        }
    }

    return target
}

/**
 * Convert a typed array to a Buffer without a copy
 *
 * Author:   Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
 * License:  MIT
 *
 * `npm install typedarray-to-buffer`
 */

var typedarrayToBuffer = function (arr) {
  if (typeof Buffer._augment === 'function' && Buffer.TYPED_ARRAY_SUPPORT) {
    // If `Buffer` is from the `buffer` module and this browser supports typed arrays,
    // then augment it with all the `Buffer` methods.
    return Buffer._augment(arr)
  } else {
    // Otherwise, fallback to creating a `Buffer` with a copy.
    return new Buffer(arr)
  }
};

var levelJs = Level;


var AbstractLevelDOWN$1 = abstractLeveldown.AbstractLevelDOWN;






function Level(location) {
  if (!(this instanceof Level)) return new Level(location)
  if (!location) throw new Error("constructor requires at least a location argument")
  this.IDBOptions = {};
  this.location = location;
}

util$2.inherits(Level, AbstractLevelDOWN$1);

Level.prototype._open = function(options, callback) {
  var self = this;
    
  var idbOpts = {
    storeName: this.location,
    autoIncrement: false,
    keyPath: null,
    onStoreReady: function () {
      callback && callback(null, self.idb);
    }, 
    onError: function(err) {
      callback && callback(err);
    }
  };
  
  xtend$1(idbOpts, options);
  this.IDBOptions = idbOpts;
  this.idb = new idbstore(idbOpts);
};

Level.prototype._get = function (key, options, callback) {
  this.idb.get(key, function (value) {
    if (value === undefined) {
      // 'NotFound' error, consistent with LevelDOWN API
      return callback(new Error('NotFound'))
    }
    // by default return buffers, unless explicitly told not to
    var asBuffer = true;
    if (options.asBuffer === false) asBuffer = false;
    if (options.raw) asBuffer = false;
    if (asBuffer) {
      if (value instanceof Uint8Array) value = typedarrayToBuffer(value);
      else value = new Buffer(String(value));
    }
    return callback(null, value, key)
  }, callback);
};

Level.prototype._del = function(id, options, callback) {
  this.idb.remove(id, callback, callback);
};

Level.prototype._put = function (key, value, options, callback) {
  if (value instanceof ArrayBuffer) {
    value = typedarrayToBuffer(new Uint8Array(value));
  }
  var obj = this.convertEncoding(key, value, options);
  if (Buffer.isBuffer(obj.value)) {
    if (typeof value.toArrayBuffer === 'function') {
      obj.value = new Uint8Array(value.toArrayBuffer());
    } else {
      obj.value = new Uint8Array(value);
    }
  }
  this.idb.put(obj.key, obj.value, function() { callback(); }, callback);
};

Level.prototype.convertEncoding = function(key, value, options) {
  if (options.raw) return {key: key, value: value}
  if (value) {
    var stringed = value.toString();
    if (stringed === 'NaN') value = 'NaN';
  }
  var valEnc = options.valueEncoding;
  var obj = {key: key, value: value};
  if (value && (!valEnc || valEnc !== 'binary')) {
    if (typeof obj.value !== 'object') {
      obj.value = stringed;
    }
  }
  return obj
};

Level.prototype.iterator = function (options) {
  if (typeof options !== 'object') options = {};
  return new iterator(this.idb, options)
};

Level.prototype._batch = function (array, options, callback) {
  var i;
  var k;
  var copiedOp;
  var currentOp;
  var modified = [];
  
  if (array.length === 0) return setTimeout(callback, 0)
  
  for (i = 0; i < array.length; i++) {
    copiedOp = {};
    currentOp = array[i];
    modified[i] = copiedOp;
    
    var converted = this.convertEncoding(currentOp.key, currentOp.value, options);
    currentOp.key = converted.key;
    currentOp.value = converted.value;

    for (k in currentOp) {
      if (k === 'type' && currentOp[k] == 'del') {
        copiedOp[k] = 'remove';
      } else {
        copiedOp[k] = currentOp[k];
      }
    }
  }

  return this.idb.batch(modified, function(){ callback(); }, callback)
};

Level.prototype._close = function (callback) {
  this.idb.db.close();
  callback();
};

Level.prototype._approximateSize = function (start, end, callback) {
  var err = new Error('Not implemented');
  if (callback)
    return callback(err)

  throw err
};

Level.prototype._isBuffer = function (obj) {
  return Buffer.isBuffer(obj)
};

Level.destroy = function (db, callback) {
  if (typeof db === 'object') {
    var prefix = db.IDBOptions.storePrefix || 'IDBWrapper-';
    var dbname = db.location;
  } else {
    var prefix = 'IDBWrapper-';
    var dbname = db;
  }
  var request = indexedDB.deleteDatabase(prefix + dbname);
  request.onsuccess = function() {
    callback();
  };
  request.onerror = function(err) {
    callback(err);
  };
};

var checkKeyValue = Level.prototype._checkKeyValue = function (obj, type) {
  if (obj === null || obj === undefined)
    return new Error(type + ' cannot be `null` or `undefined`')
  if (obj === null || obj === undefined)
    return new Error(type + ' cannot be `null` or `undefined`')
  if (isbuffer(obj) && obj.byteLength === 0)
    return new Error(type + ' cannot be an empty ArrayBuffer')
  if (String(obj) === '')
    return new Error(type + ' cannot be an empty String')
  if (obj.length === 0)
    return new Error(type + ' cannot be an empty Array')
};

var xtend$2 = extend$2;

function extend$2() {
    var target = {};

    for (var i = 0; i < arguments.length; i++) {
        var source = arguments[i];

        for (var key in source) {
            if (source.hasOwnProperty(key)) {
                target[key] = source[key];
            }
        }
    }

    return target
}

var prr = createCommonjsModule(function (module) {
/*!
  * prr
  * (c) 2013 Rod Vagg <rod@vagg.org>
  * https://github.com/rvagg/prr
  * License: MIT
  */

(function (name, context, definition) {
  if (module.exports)
    module.exports = definition();
  else
    context[name] = definition();
})('prr', commonjsGlobal, function() {

  var setProperty = typeof Object.defineProperty == 'function'
      ? function (obj, key, options) {
          Object.defineProperty(obj, key, options);
          return obj
        }
      : function (obj, key, options) { // < es5
          obj[key] = options.value;
          return obj
        }

    , makeOptions = function (value, options) {
        var oo = typeof options == 'object'
          , os = !oo && typeof options == 'string'
          , op = function (p) {
              return oo
                ? !!options[p]
                : os
                  ? options.indexOf(p[0]) > -1
                  : false
            };

        return {
            enumerable   : op('enumerable')
          , configurable : op('configurable')
          , writable     : op('writable')
          , value        : value
        }
      }

    , prr = function (obj, key, value, options) {
        var k;

        options = makeOptions(value, options);

        if (typeof key == 'object') {
          for (k in key) {
            if (Object.hasOwnProperty.call(key, k)) {
              options.value = key[k];
              setProperty(obj, k, options);
            }
          }
          return obj
        }

        return setProperty(obj, key, options)
      };

  return prr
});
});

var AbstractLevelDOWN$2 = abstractLeveldown.AbstractLevelDOWN;

function DeferredLevelDOWN (location) {
  AbstractLevelDOWN$2.call(this, typeof location == 'string' ? location : ''); // optional location, who cares?
  this._db         = undefined;
  this._operations = [];
}

util$2.inherits(DeferredLevelDOWN, AbstractLevelDOWN$2);

// called by LevelUP when we have a real DB to take its place
DeferredLevelDOWN.prototype.setDb = function (db) {
  this._db = db;
  this._operations.forEach(function (op) {
    db[op.method].apply(db, op.args);
  });
};

DeferredLevelDOWN.prototype._open = function (options, callback) {
  return process.nextTick(callback)
};

// queue a new deferred operation
DeferredLevelDOWN.prototype._operation = function (method, args) {
  if (this._db)
    return this._db[method].apply(this._db, args)
  this._operations.push({ method: method, args: args });
};

// deferrables
'put get del batch approximateSize'.split(' ').forEach(function (m) {
  DeferredLevelDOWN.prototype['_' + m] = function () {
    this._operation(m, arguments);
  };
});

DeferredLevelDOWN.prototype._isBuffer = function (obj) {
  return Buffer.isBuffer(obj)
};

// don't need to implement this as LevelUP's ReadStream checks for 'ready' state
DeferredLevelDOWN.prototype._iterator = function () {
  throw new TypeError('not implemented')
};

var deferredLeveldown = DeferredLevelDOWN;

var prr$1 = createCommonjsModule(function (module) {
/*!
  * prr
  * (c) 2013 Rod Vagg <rod@vagg.org>
  * https://github.com/rvagg/prr
  * License: MIT
  */

(function (name, context, definition) {
  if (module.exports)
    module.exports = definition();
  else
    context[name] = definition();
})('prr', commonjsGlobal, function() {

  var setProperty = typeof Object.defineProperty == 'function'
      ? function (obj, key, options) {
          Object.defineProperty(obj, key, options);
          return obj
        }
      : function (obj, key, options) { // < es5
          obj[key] = options.value;
          return obj
        }

    , makeOptions = function (value, options) {
        var oo = typeof options == 'object'
          , os = !oo && typeof options == 'string'
          , op = function (p) {
              return oo
                ? !!options[p]
                : os
                  ? options.indexOf(p[0]) > -1
                  : false
            };

        return {
            enumerable   : op('enumerable')
          , configurable : op('configurable')
          , writable     : op('writable')
          , value        : value
        }
      }

    , prr = function (obj, key, value, options) {
        var k;

        options = makeOptions(value, options);

        if (typeof key == 'object') {
          for (k in key) {
            if (Object.hasOwnProperty.call(key, k)) {
              options.value = key[k];
              setProperty(obj, k, options);
            }
          }
          return obj
        }

        return setProperty(obj, key, options)
      };

  return prr
});
});

function init (type, message, cause) {
  if (!!message && typeof message != 'string') {
    message = message.message || message.name;
  }
  prr$1(this, {
      type    : type
    , name    : type
      // can be passed just a 'cause'
    , cause   : typeof message != 'string' ? message : cause
    , message : message
  }, 'ewr');
}

// generic prototype, not intended to be actually used - helpful for `instanceof`
function CustomError (message, cause) {
  Error.call(this);
  if (Error.captureStackTrace)
    Error.captureStackTrace(this, this.constructor);
  init.call(this, 'CustomError', message, cause);
}

CustomError.prototype = new Error();

function createError (errno, type, proto) {
  var err = function (message, cause) {
    init.call(this, type, message, cause);
    //TODO: the specificity here is stupid, errno should be available everywhere
    if (type == 'FilesystemError') {
      this.code    = this.cause.code;
      this.path    = this.cause.path;
      this.errno   = this.cause.errno;
      this.message =
        (errno.errno[this.cause.errno]
          ? errno.errno[this.cause.errno].description
          : this.cause.message)
        + (this.cause.path ? ' [' + this.cause.path + ']' : '');
    }
    Error.call(this);
    if (Error.captureStackTrace)
      Error.captureStackTrace(this, err);
  };
  err.prototype = !!proto ? new proto() : new CustomError();
  return err
}

var custom = function (errno) {
  var ce = function (type, proto) {
    return createError(errno, type, proto)
  };
  return {
      CustomError     : CustomError
    , FilesystemError : ce('FilesystemError')
    , createError     : ce
  }
};

var errno = createCommonjsModule(function (module) {
var all = module.exports.all = [
  {
    errno: -2,
    code: 'ENOENT',
    description: 'no such file or directory'
  },
  {
    errno: -1,
    code: 'UNKNOWN',
    description: 'unknown error'
  },
  {
    errno: 0,
    code: 'OK',
    description: 'success'
  },
  {
    errno: 1,
    code: 'EOF',
    description: 'end of file'
  },
  {
    errno: 2,
    code: 'EADDRINFO',
    description: 'getaddrinfo error'
  },
  {
    errno: 3,
    code: 'EACCES',
    description: 'permission denied'
  },
  {
    errno: 4,
    code: 'EAGAIN',
    description: 'resource temporarily unavailable'
  },
  {
    errno: 5,
    code: 'EADDRINUSE',
    description: 'address already in use'
  },
  {
    errno: 6,
    code: 'EADDRNOTAVAIL',
    description: 'address not available'
  },
  {
    errno: 7,
    code: 'EAFNOSUPPORT',
    description: 'address family not supported'
  },
  {
    errno: 8,
    code: 'EALREADY',
    description: 'connection already in progress'
  },
  {
    errno: 9,
    code: 'EBADF',
    description: 'bad file descriptor'
  },
  {
    errno: 10,
    code: 'EBUSY',
    description: 'resource busy or locked'
  },
  {
    errno: 11,
    code: 'ECONNABORTED',
    description: 'software caused connection abort'
  },
  {
    errno: 12,
    code: 'ECONNREFUSED',
    description: 'connection refused'
  },
  {
    errno: 13,
    code: 'ECONNRESET',
    description: 'connection reset by peer'
  },
  {
    errno: 14,
    code: 'EDESTADDRREQ',
    description: 'destination address required'
  },
  {
    errno: 15,
    code: 'EFAULT',
    description: 'bad address in system call argument'
  },
  {
    errno: 16,
    code: 'EHOSTUNREACH',
    description: 'host is unreachable'
  },
  {
    errno: 17,
    code: 'EINTR',
    description: 'interrupted system call'
  },
  {
    errno: 18,
    code: 'EINVAL',
    description: 'invalid argument'
  },
  {
    errno: 19,
    code: 'EISCONN',
    description: 'socket is already connected'
  },
  {
    errno: 20,
    code: 'EMFILE',
    description: 'too many open files'
  },
  {
    errno: 21,
    code: 'EMSGSIZE',
    description: 'message too long'
  },
  {
    errno: 22,
    code: 'ENETDOWN',
    description: 'network is down'
  },
  {
    errno: 23,
    code: 'ENETUNREACH',
    description: 'network is unreachable'
  },
  {
    errno: 24,
    code: 'ENFILE',
    description: 'file table overflow'
  },
  {
    errno: 25,
    code: 'ENOBUFS',
    description: 'no buffer space available'
  },
  {
    errno: 26,
    code: 'ENOMEM',
    description: 'not enough memory'
  },
  {
    errno: 27,
    code: 'ENOTDIR',
    description: 'not a directory'
  },
  {
    errno: 28,
    code: 'EISDIR',
    description: 'illegal operation on a directory'
  },
  {
    errno: 29,
    code: 'ENONET',
    description: 'machine is not on the network'
  },
  {
    errno: 31,
    code: 'ENOTCONN',
    description: 'socket is not connected'
  },
  {
    errno: 32,
    code: 'ENOTSOCK',
    description: 'socket operation on non-socket'
  },
  {
    errno: 33,
    code: 'ENOTSUP',
    description: 'operation not supported on socket'
  },
  {
    errno: 34,
    code: 'ENOENT',
    description: 'no such file or directory'
  },
  {
    errno: 35,
    code: 'ENOSYS',
    description: 'function not implemented'
  },
  {
    errno: 36,
    code: 'EPIPE',
    description: 'broken pipe'
  },
  {
    errno: 37,
    code: 'EPROTO',
    description: 'protocol error'
  },
  {
    errno: 38,
    code: 'EPROTONOSUPPORT',
    description: 'protocol not supported'
  },
  {
    errno: 39,
    code: 'EPROTOTYPE',
    description: 'protocol wrong type for socket'
  },
  {
    errno: 40,
    code: 'ETIMEDOUT',
    description: 'connection timed out'
  },
  {
    errno: 41,
    code: 'ECHARSET',
    description: 'invalid Unicode character'
  },
  {
    errno: 42,
    code: 'EAIFAMNOSUPPORT',
    description: 'address family for hostname not supported'
  },
  {
    errno: 44,
    code: 'EAISERVICE',
    description: 'servname not supported for ai_socktype'
  },
  {
    errno: 45,
    code: 'EAISOCKTYPE',
    description: 'ai_socktype not supported'
  },
  {
    errno: 46,
    code: 'ESHUTDOWN',
    description: 'cannot send after transport endpoint shutdown'
  },
  {
    errno: 47,
    code: 'EEXIST',
    description: 'file already exists'
  },
  {
    errno: 48,
    code: 'ESRCH',
    description: 'no such process'
  },
  {
    errno: 49,
    code: 'ENAMETOOLONG',
    description: 'name too long'
  },
  {
    errno: 50,
    code: 'EPERM',
    description: 'operation not permitted'
  },
  {
    errno: 51,
    code: 'ELOOP',
    description: 'too many symbolic links encountered'
  },
  {
    errno: 52,
    code: 'EXDEV',
    description: 'cross-device link not permitted'
  },
  {
    errno: 53,
    code: 'ENOTEMPTY',
    description: 'directory not empty'
  },
  {
    errno: 54,
    code: 'ENOSPC',
    description: 'no space left on device'
  },
  {
    errno: 55,
    code: 'EIO',
    description: 'i/o error'
  },
  {
    errno: 56,
    code: 'EROFS',
    description: 'read-only file system'
  },
  {
    errno: 57,
    code: 'ENODEV',
    description: 'no such device'
  },
  {
    errno: 58,
    code: 'ESPIPE',
    description: 'invalid seek'
  },
  {
    errno: 59,
    code: 'ECANCELED',
    description: 'operation canceled'
  }
];

module.exports.errno = {};
module.exports.code = {};

all.forEach(function (error) {
  module.exports.errno[error.errno] = error;
  module.exports.code[error.code] = error;
});

module.exports.custom = custom(module.exports);
module.exports.create = module.exports.custom.createError;
});
var errno_1 = errno.all;
var errno_2 = errno.errno;
var errno_3 = errno.code;
var errno_4 = errno.custom;
var errno_5 = errno.create;

/* Copyright (c) 2012-2014 LevelUP contributors
 * See list at <https://github.com/rvagg/node-levelup#contributing>
 * MIT License
 * <https://github.com/rvagg/node-levelup/blob/master/LICENSE.md>
 */

var createError$1   = errno.create
  , LevelUPError  = createError$1('LevelUPError')
  , NotFoundError = createError$1('NotFoundError', LevelUPError);

NotFoundError.prototype.notFound = true;
NotFoundError.prototype.status   = 404;

var errors = {
    LevelUPError        : LevelUPError
  , InitializationError : createError$1('InitializationError', LevelUPError)
  , OpenError           : createError$1('OpenError', LevelUPError)
  , ReadError           : createError$1('ReadError', LevelUPError)
  , WriteError          : createError$1('WriteError', LevelUPError)
  , NotFoundError       : NotFoundError
  , EncodingError       : createError$1('EncodingError', LevelUPError)
};

var isarray = Array.isArray || function (arr) {
  return Object.prototype.toString.call(arr) == '[object Array]';
};

// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.

// NOTE: These type checking functions intentionally don't use `instanceof`
// because it is fragile and can be easily faked with `Object.create()`.

function isArray(arg) {
  if (Array.isArray) {
    return Array.isArray(arg);
  }
  return objectToString(arg) === '[object Array]';
}
var isArray_1 = isArray;

function isBoolean(arg) {
  return typeof arg === 'boolean';
}
var isBoolean_1 = isBoolean;

function isNull(arg) {
  return arg === null;
}
var isNull_1 = isNull;

function isNullOrUndefined(arg) {
  return arg == null;
}
var isNullOrUndefined_1 = isNullOrUndefined;

function isNumber(arg) {
  return typeof arg === 'number';
}
var isNumber_1 = isNumber;

function isString(arg) {
  return typeof arg === 'string';
}
var isString_1 = isString;

function isSymbol(arg) {
  return typeof arg === 'symbol';
}
var isSymbol_1 = isSymbol;

function isUndefined(arg) {
  return arg === void 0;
}
var isUndefined_1 = isUndefined;

function isRegExp(re) {
  return objectToString(re) === '[object RegExp]';
}
var isRegExp_1 = isRegExp;

function isObject(arg) {
  return typeof arg === 'object' && arg !== null;
}
var isObject_1 = isObject;

function isDate(d) {
  return objectToString(d) === '[object Date]';
}
var isDate_1 = isDate;

function isError(e) {
  return (objectToString(e) === '[object Error]' || e instanceof Error);
}
var isError_1 = isError;

function isFunction$1(arg) {
  return typeof arg === 'function';
}
var isFunction_1 = isFunction$1;

function isPrimitive(arg) {
  return arg === null ||
         typeof arg === 'boolean' ||
         typeof arg === 'number' ||
         typeof arg === 'string' ||
         typeof arg === 'symbol' ||  // ES6 symbol
         typeof arg === 'undefined';
}
var isPrimitive_1 = isPrimitive;

var isBuffer$1 = Buffer.isBuffer;

function objectToString(o) {
  return Object.prototype.toString.call(o);
}

var util = {
	isArray: isArray_1,
	isBoolean: isBoolean_1,
	isNull: isNull_1,
	isNullOrUndefined: isNullOrUndefined_1,
	isNumber: isNumber_1,
	isString: isString_1,
	isSymbol: isSymbol_1,
	isUndefined: isUndefined_1,
	isRegExp: isRegExp_1,
	isObject: isObject_1,
	isDate: isDate_1,
	isError: isError_1,
	isFunction: isFunction_1,
	isPrimitive: isPrimitive_1,
	isBuffer: isBuffer$1
};

var inherits_browser = createCommonjsModule(function (module) {
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;
  };
}
});

var string_decoder = createCommonjsModule(function (module, exports) {
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.

var Buffer = buffer.Buffer;

var isBufferEncoding = Buffer.isEncoding
  || function(encoding) {
       switch (encoding && encoding.toLowerCase()) {
         case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': case 'raw': return true;
         default: return false;
       }
     };


function assertEncoding(encoding) {
  if (encoding && !isBufferEncoding(encoding)) {
    throw new Error('Unknown encoding: ' + encoding);
  }
}

// StringDecoder provides an interface for efficiently splitting a series of
// buffers into a series of JS strings without breaking apart multi-byte
// characters. CESU-8 is handled as part of the UTF-8 encoding.
//
// @TODO Handling all encodings inside a single object makes it very difficult
// to reason about this code, so it should be split up in the future.
// @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code
// points as used by CESU-8.
var StringDecoder = exports.StringDecoder = function(encoding) {
  this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, '');
  assertEncoding(encoding);
  switch (this.encoding) {
    case 'utf8':
      // CESU-8 represents each of Surrogate Pair by 3-bytes
      this.surrogateSize = 3;
      break;
    case 'ucs2':
    case 'utf16le':
      // UTF-16 represents each of Surrogate Pair by 2-bytes
      this.surrogateSize = 2;
      this.detectIncompleteChar = utf16DetectIncompleteChar;
      break;
    case 'base64':
      // Base-64 stores 3 bytes in 4 chars, and pads the remainder.
      this.surrogateSize = 3;
      this.detectIncompleteChar = base64DetectIncompleteChar;
      break;
    default:
      this.write = passThroughWrite;
      return;
  }

  // Enough space to store all bytes of a single character. UTF-8 needs 4
  // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate).
  this.charBuffer = new Buffer(6);
  // Number of bytes received for the current incomplete multi-byte character.
  this.charReceived = 0;
  // Number of bytes expected for the current incomplete multi-byte character.
  this.charLength = 0;
};


// write decodes the given buffer and returns it as JS string that is
// guaranteed to not contain any partial multi-byte characters. Any partial
// character found at the end of the buffer is buffered up, and will be
// returned when calling write again with the remaining bytes.
//
// Note: Converting a Buffer containing an orphan surrogate to a String
// currently works, but converting a String to a Buffer (via `new Buffer`, or
// Buffer#write) will replace incomplete surrogates with the unicode
// replacement character. See https://codereview.chromium.org/121173009/ .
StringDecoder.prototype.write = function(buffer) {
  var charStr = '';
  // if our last write ended with an incomplete multibyte character
  while (this.charLength) {
    // determine how many remaining bytes this buffer has to offer for this char
    var available = (buffer.length >= this.charLength - this.charReceived) ?
        this.charLength - this.charReceived :
        buffer.length;

    // add the new bytes to the char buffer
    buffer.copy(this.charBuffer, this.charReceived, 0, available);
    this.charReceived += available;

    if (this.charReceived < this.charLength) {
      // still not enough chars in this buffer? wait for more ...
      return '';
    }

    // remove bytes belonging to the current character from the buffer
    buffer = buffer.slice(available, buffer.length);

    // get the character that was split
    charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding);

    // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character
    var charCode = charStr.charCodeAt(charStr.length - 1);
    if (charCode >= 0xD800 && charCode <= 0xDBFF) {
      this.charLength += this.surrogateSize;
      charStr = '';
      continue;
    }
    this.charReceived = this.charLength = 0;

    // if there are no more bytes in this buffer, just emit our char
    if (buffer.length === 0) {
      return charStr;
    }
    break;
  }

  // determine and set charLength / charReceived
  this.detectIncompleteChar(buffer);

  var end = buffer.length;
  if (this.charLength) {
    // buffer the incomplete character bytes we got
    buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end);
    end -= this.charReceived;
  }

  charStr += buffer.toString(this.encoding, 0, end);

  var end = charStr.length - 1;
  var charCode = charStr.charCodeAt(end);
  // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character
  if (charCode >= 0xD800 && charCode <= 0xDBFF) {
    var size = this.surrogateSize;
    this.charLength += size;
    this.charReceived += size;
    this.charBuffer.copy(this.charBuffer, size, 0, size);
    buffer.copy(this.charBuffer, 0, 0, size);
    return charStr.substring(0, end);
  }

  // or just emit the charStr
  return charStr;
};

// detectIncompleteChar determines if there is an incomplete UTF-8 character at
// the end of the given buffer. If so, it sets this.charLength to the byte
// length that character, and sets this.charReceived to the number of bytes
// that are available for this character.
StringDecoder.prototype.detectIncompleteChar = function(buffer) {
  // determine how many bytes we have to check at the end of this buffer
  var i = (buffer.length >= 3) ? 3 : buffer.length;

  // Figure out if one of the last i bytes of our buffer announces an
  // incomplete char.
  for (; i > 0; i--) {
    var c = buffer[buffer.length - i];

    // See http://en.wikipedia.org/wiki/UTF-8#Description

    // 110XXXXX
    if (i == 1 && c >> 5 == 0x06) {
      this.charLength = 2;
      break;
    }

    // 1110XXXX
    if (i <= 2 && c >> 4 == 0x0E) {
      this.charLength = 3;
      break;
    }

    // 11110XXX
    if (i <= 3 && c >> 3 == 0x1E) {
      this.charLength = 4;
      break;
    }
  }
  this.charReceived = i;
};

StringDecoder.prototype.end = function(buffer) {
  var res = '';
  if (buffer && buffer.length)
    res = this.write(buffer);

  if (this.charReceived) {
    var cr = this.charReceived;
    var buf = this.charBuffer;
    var enc = this.encoding;
    res += buf.slice(0, cr).toString(enc);
  }

  return res;
};

function passThroughWrite(buffer) {
  return buffer.toString(this.encoding);
}

function utf16DetectIncompleteChar(buffer) {
  this.charReceived = buffer.length % 2;
  this.charLength = this.charReceived ? 2 : 0;
}

function base64DetectIncompleteChar(buffer) {
  this.charReceived = buffer.length % 3;
  this.charLength = this.charReceived ? 3 : 0;
}
});
var string_decoder_1 = string_decoder.StringDecoder;

// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.

var _stream_readable = Readable;

/*<replacement>*/

/*</replacement>*/


/*<replacement>*/
var Buffer$2 = buffer.Buffer;
/*</replacement>*/

Readable.ReadableState = ReadableState;

var EE = events.EventEmitter;

/*<replacement>*/
if (!EE.listenerCount) EE.listenerCount = function(emitter, type) {
  return emitter.listeners(type).length;
};
/*</replacement>*/



/*<replacement>*/

util.inherits = inherits_browser;
/*</replacement>*/

var StringDecoder;

util.inherits(Readable, stream);

function ReadableState(options, stream) {
  options = options || {};

  // the point at which it stops calling _read() to fill the buffer
  // Note: 0 is a valid value, means "don't call _read preemptively ever"
  var hwm = options.highWaterMark;
  this.highWaterMark = (hwm || hwm === 0) ? hwm : 16 * 1024;

  // cast to ints.
  this.highWaterMark = ~~this.highWaterMark;

  this.buffer = [];
  this.length = 0;
  this.pipes = null;
  this.pipesCount = 0;
  this.flowing = false;
  this.ended = false;
  this.endEmitted = false;
  this.reading = false;

  // In streams that never have any data, and do push(null) right away,
  // the consumer can miss the 'end' event if they do some I/O before
  // consuming the stream.  So, we don't emit('end') until some reading
  // happens.
  this.calledRead = false;

  // a flag to be able to tell if the onwrite cb is called immediately,
  // or on a later tick.  We set this to true at first, becuase any
  // actions that shouldn't happen until "later" should generally also
  // not happen before the first write call.
  this.sync = true;

  // whenever we return null, then we set a flag to say
  // that we're awaiting a 'readable' event emission.
  this.needReadable = false;
  this.emittedReadable = false;
  this.readableListening = false;


  // object stream flag. Used to make read(n) ignore n and to
  // make all the buffer merging and length checks go away
  this.objectMode = !!options.objectMode;

  // Crypto is kind of old and crusty.  Historically, its default string
  // encoding is 'binary' so we have to make this configurable.
  // Everything else in the universe uses 'utf8', though.
  this.defaultEncoding = options.defaultEncoding || 'utf8';

  // when piping, we only care about 'readable' events that happen
  // after read()ing all the bytes and not getting any pushback.
  this.ranOut = false;

  // the number of writers that are awaiting a drain event in .pipe()s
  this.awaitDrain = 0;

  // if true, a maybeReadMore has been scheduled
  this.readingMore = false;

  this.decoder = null;
  this.encoding = null;
  if (options.encoding) {
    if (!StringDecoder)
      StringDecoder = string_decoder.StringDecoder;
    this.decoder = new StringDecoder(options.encoding);
    this.encoding = options.encoding;
  }
}

function Readable(options) {
  if (!(this instanceof Readable))
    return new Readable(options);

  this._readableState = new ReadableState(options, this);

  // legacy
  this.readable = true;

  stream.call(this);
}

// Manually shove something into the read() buffer.
// This returns true if the highWaterMark has not been hit yet,
// similar to how Writable.write() returns true if you should
// write() some more.
Readable.prototype.push = function(chunk, encoding) {
  var state = this._readableState;

  if (typeof chunk === 'string' && !state.objectMode) {
    encoding = encoding || state.defaultEncoding;
    if (encoding !== state.encoding) {
      chunk = new Buffer$2(chunk, encoding);
      encoding = '';
    }
  }

  return readableAddChunk(this, state, chunk, encoding, false);
};

// Unshift should *always* be something directly out of read()
Readable.prototype.unshift = function(chunk) {
  var state = this._readableState;
  return readableAddChunk(this, state, chunk, '', true);
};

function readableAddChunk(stream, state, chunk, encoding, addToFront) {
  var er = chunkInvalid(state, chunk);
  if (er) {
    stream.emit('error', er);
  } else if (chunk === null || chunk === undefined) {
    state.reading = false;
    if (!state.ended)
      onEofChunk(stream, state);
  } else if (state.objectMode || chunk && chunk.length > 0) {
    if (state.ended && !addToFront) {
      var e = new Error('stream.push() after EOF');
      stream.emit('error', e);
    } else if (state.endEmitted && addToFront) {
      var e = new Error('stream.unshift() after end event');
      stream.emit('error', e);
    } else {
      if (state.decoder && !addToFront && !encoding)
        chunk = state.decoder.write(chunk);

      // update the buffer info.
      state.length += state.objectMode ? 1 : chunk.length;
      if (addToFront) {
        state.buffer.unshift(chunk);
      } else {
        state.reading = false;
        state.buffer.push(chunk);
      }

      if (state.needReadable)
        emitReadable(stream);

      maybeReadMore(stream, state);
    }
  } else if (!addToFront) {
    state.reading = false;
  }

  return needMoreData(state);
}



// if it's past the high water mark, we can push in some more.
// Also, if we have no data yet, we can stand some
// more bytes.  This is to work around cases where hwm=0,
// such as the repl.  Also, if the push() triggered a
// readable event, and the user called read(largeNumber) such that
// needReadable was set, then we ought to push more, so that another
// 'readable' event will be triggered.
function needMoreData(state) {
  return !state.ended &&
         (state.needReadable ||
          state.length < state.highWaterMark ||
          state.length === 0);
}

// backwards compatibility.
Readable.prototype.setEncoding = function(enc) {
  if (!StringDecoder)
    StringDecoder = string_decoder.StringDecoder;
  this._readableState.decoder = new StringDecoder(enc);
  this._readableState.encoding = enc;
};

// Don't raise the hwm > 128MB
var MAX_HWM = 0x800000;
function roundUpToNextPowerOf2(n) {
  if (n >= MAX_HWM) {
    n = MAX_HWM;
  } else {
    // Get the next highest power of 2
    n--;
    for (var p = 1; p < 32; p <<= 1) n |= n >> p;
    n++;
  }
  return n;
}

function howMuchToRead(n, state) {
  if (state.length === 0 && state.ended)
    return 0;

  if (state.objectMode)
    return n === 0 ? 0 : 1;

  if (n === null || isNaN(n)) {
    // only flow one buffer at a time
    if (state.flowing && state.buffer.length)
      return state.buffer[0].length;
    else
      return state.length;
  }

  if (n <= 0)
    return 0;

  // If we're asking for more than the target buffer level,
  // then raise the water mark.  Bump up to the next highest
  // power of 2, to prevent increasing it excessively in tiny
  // amounts.
  if (n > state.highWaterMark)
    state.highWaterMark = roundUpToNextPowerOf2(n);

  // don't have that much.  return null, unless we've ended.
  if (n > state.length) {
    if (!state.ended) {
      state.needReadable = true;
      return 0;
    } else
      return state.length;
  }

  return n;
}

// you can override either this method, or the async _read(n) below.
Readable.prototype.read = function(n) {
  var state = this._readableState;
  state.calledRead = true;
  var nOrig = n;
  var ret;

  if (typeof n !== 'number' || n > 0)
    state.emittedReadable = false;

  // if we're doing read(0) to trigger a readable event, but we
  // already have a bunch of data in the buffer, then just trigger
  // the 'readable' event and move on.
  if (n === 0 &&
      state.needReadable &&
      (state.length >= state.highWaterMark || state.ended)) {
    emitReadable(this);
    return null;
  }

  n = howMuchToRead(n, state);

  // if we've ended, and we're now clear, then finish it up.
  if (n === 0 && state.ended) {
    ret = null;

    // In cases where the decoder did not receive enough data
    // to produce a full chunk, then immediately received an
    // EOF, state.buffer will contain [<Buffer >, <Buffer 00 ...>].
    // howMuchToRead will see this and coerce the amount to
    // read to zero (because it's looking at the length of the
    // first <Buffer > in state.buffer), and we'll end up here.
    //
    // This can only happen via state.decoder -- no other venue
    // exists for pushing a zero-length chunk into state.buffer
    // and triggering this behavior. In this case, we return our
    // remaining data and end the stream, if appropriate.
    if (state.length > 0 && state.decoder) {
      ret = fromList(n, state);
      state.length -= ret.length;
    }

    if (state.length === 0)
      endReadable(this);

    return ret;
  }

  // All the actual chunk generation logic needs to be
  // *below* the call to _read.  The reason is that in certain
  // synthetic stream cases, such as passthrough streams, _read
  // may be a completely synchronous operation which may change
  // the state of the read buffer, providing enough data when
  // before there was *not* enough.
  //
  // So, the steps are:
  // 1. Figure out what the state of things will be after we do
  // a read from the buffer.
  //
  // 2. If that resulting state will trigger a _read, then call _read.
  // Note that this may be asynchronous, or synchronous.  Yes, it is
  // deeply ugly to write APIs this way, but that still doesn't mean
  // that the Readable class should behave improperly, as streams are
  // designed to be sync/async agnostic.
  // Take note if the _read call is sync or async (ie, if the read call
  // has returned yet), so that we know whether or not it's safe to emit
  // 'readable' etc.
  //
  // 3. Actually pull the requested chunks out of the buffer and return.

  // if we need a readable event, then we need to do some reading.
  var doRead = state.needReadable;

  // if we currently have less than the highWaterMark, then also read some
  if (state.length - n <= state.highWaterMark)
    doRead = true;

  // however, if we've ended, then there's no point, and if we're already
  // reading, then it's unnecessary.
  if (state.ended || state.reading)
    doRead = false;

  if (doRead) {
    state.reading = true;
    state.sync = true;
    // if the length is currently zero, then we *need* a readable event.
    if (state.length === 0)
      state.needReadable = true;
    // call internal read method
    this._read(state.highWaterMark);
    state.sync = false;
  }

  // If _read called its callback synchronously, then `reading`
  // will be false, and we need to re-evaluate how much data we
  // can return to the user.
  if (doRead && !state.reading)
    n = howMuchToRead(nOrig, state);

  if (n > 0)
    ret = fromList(n, state);
  else
    ret = null;

  if (ret === null) {
    state.needReadable = true;
    n = 0;
  }

  state.length -= n;

  // If we have nothing in the buffer, then we want to know
  // as soon as we *do* get something into the buffer.
  if (state.length === 0 && !state.ended)
    state.needReadable = true;

  // If we happened to read() exactly the remaining amount in the
  // buffer, and the EOF has been seen at this point, then make sure
  // that we emit 'end' on the very next tick.
  if (state.ended && !state.endEmitted && state.length === 0)
    endReadable(this);

  return ret;
};

function chunkInvalid(state, chunk) {
  var er = null;
  if (!Buffer$2.isBuffer(chunk) &&
      'string' !== typeof chunk &&
      chunk !== null &&
      chunk !== undefined &&
      !state.objectMode) {
    er = new TypeError('Invalid non-string/buffer chunk');
  }
  return er;
}


function onEofChunk(stream, state) {
  if (state.decoder && !state.ended) {
    var chunk = state.decoder.end();
    if (chunk && chunk.length) {
      state.buffer.push(chunk);
      state.length += state.objectMode ? 1 : chunk.length;
    }
  }
  state.ended = true;

  // if we've ended and we have some data left, then emit
  // 'readable' now to make sure it gets picked up.
  if (state.length > 0)
    emitReadable(stream);
  else
    endReadable(stream);
}

// Don't emit readable right away in sync mode, because this can trigger
// another read() call => stack overflow.  This way, it might trigger
// a nextTick recursion warning, but that's not so bad.
function emitReadable(stream) {
  var state = stream._readableState;
  state.needReadable = false;
  if (state.emittedReadable)
    return;

  state.emittedReadable = true;
  if (state.sync)
    process.nextTick(function() {
      emitReadable_(stream);
    });
  else
    emitReadable_(stream);
}

function emitReadable_(stream) {
  stream.emit('readable');
}


// at this point, the user has presumably seen the 'readable' event,
// and called read() to consume some data.  that may have triggered
// in turn another _read(n) call, in which case reading = true if
// it's in progress.
// However, if we're not ended, or reading, and the length < hwm,
// then go ahead and try to read some more preemptively.
function maybeReadMore(stream, state) {
  if (!state.readingMore) {
    state.readingMore = true;
    process.nextTick(function() {
      maybeReadMore_(stream, state);
    });
  }
}

function maybeReadMore_(stream, state) {
  var len = state.length;
  while (!state.reading && !state.flowing && !state.ended &&
         state.length < state.highWaterMark) {
    stream.read(0);
    if (len === state.length)
      // didn't get any data, stop spinning.
      break;
    else
      len = state.length;
  }
  state.readingMore = false;
}

// abstract method.  to be overridden in specific implementation classes.
// call cb(er, data) where data is <= n in length.
// for virtual (non-string, non-buffer) streams, "length" is somewhat
// arbitrary, and perhaps not very meaningful.
Readable.prototype._read = function(n) {
  this.emit('error', new Error('not implemented'));
};

Readable.prototype.pipe = function(dest, pipeOpts) {
  var src = this;
  var state = this._readableState;

  switch (state.pipesCount) {
    case 0:
      state.pipes = dest;
      break;
    case 1:
      state.pipes = [state.pipes, dest];
      break;
    default:
      state.pipes.push(dest);
      break;
  }
  state.pipesCount += 1;

  var doEnd = (!pipeOpts || pipeOpts.end !== false) &&
              dest !== process.stdout &&
              dest !== process.stderr;

  var endFn = doEnd ? onend : cleanup;
  if (state.endEmitted)
    process.nextTick(endFn);
  else
    src.once('end', endFn);

  dest.on('unpipe', onunpipe);
  function onunpipe(readable) {
    if (readable !== src) return;
    cleanup();
  }

  function onend() {
    dest.end();
  }

  // when the dest drains, it reduces the awaitDrain counter
  // on the source.  This would be more elegant with a .once()
  // handler in flow(), but adding and removing repeatedly is
  // too slow.
  var ondrain = pipeOnDrain(src);
  dest.on('drain', ondrain);

  function cleanup() {
    // cleanup event handlers once the pipe is broken
    dest.removeListener('close', onclose);
    dest.removeListener('finish', onfinish);
    dest.removeListener('drain', ondrain);
    dest.removeListener('error', onerror);
    dest.removeListener('unpipe', onunpipe);
    src.removeListener('end', onend);
    src.removeListener('end', cleanup);

    // if the reader is waiting for a drain event from this
    // specific writer, then it would cause it to never start
    // flowing again.
    // So, if this is awaiting a drain, then we just call it now.
    // If we don't know, then assume that we are waiting for one.
    if (!dest._writableState || dest._writableState.needDrain)
      ondrain();
  }

  // if the dest has an error, then stop piping into it.
  // however, don't suppress the throwing behavior for this.
  function onerror(er) {
    unpipe();
    dest.removeListener('error', onerror);
    if (EE.listenerCount(dest, 'error') === 0)
      dest.emit('error', er);
  }
  // This is a brutally ugly hack to make sure that our error handler
  // is attached before any userland ones.  NEVER DO THIS.
  if (!dest._events || !dest._events.error)
    dest.on('error', onerror);
  else if (isarray(dest._events.error))
    dest._events.error.unshift(onerror);
  else
    dest._events.error = [onerror, dest._events.error];



  // Both close and finish should trigger unpipe, but only once.
  function onclose() {
    dest.removeListener('finish', onfinish);
    unpipe();
  }
  dest.once('close', onclose);
  function onfinish() {
    dest.removeListener('close', onclose);
    unpipe();
  }
  dest.once('finish', onfinish);

  function unpipe() {
    src.unpipe(dest);
  }

  // tell the dest that it's being piped to
  dest.emit('pipe', src);

  // start the flow if it hasn't been started already.
  if (!state.flowing) {
    // the handler that waits for readable events after all
    // the data gets sucked out in flow.
    // This would be easier to follow with a .once() handler
    // in flow(), but that is too slow.
    this.on('readable', pipeOnReadable);

    state.flowing = true;
    process.nextTick(function() {
      flow(src);
    });
  }

  return dest;
};

function pipeOnDrain(src) {
  return function() {
    var state = src._readableState;
    state.awaitDrain--;
    if (state.awaitDrain === 0)
      flow(src);
  };
}

function flow(src) {
  var state = src._readableState;
  var chunk;
  state.awaitDrain = 0;

  function write(dest, i, list) {
    var written = dest.write(chunk);
    if (false === written) {
      state.awaitDrain++;
    }
  }

  while (state.pipesCount && null !== (chunk = src.read())) {

    if (state.pipesCount === 1)
      write(state.pipes);
    else
      forEach(state.pipes, write);

    src.emit('data', chunk);

    // if anyone needs a drain, then we have to wait for that.
    if (state.awaitDrain > 0)
      return;
  }

  // if every destination was unpiped, either before entering this
  // function, or in the while loop, then stop flowing.
  //
  // NB: This is a pretty rare edge case.
  if (state.pipesCount === 0) {
    state.flowing = false;

    // if there were data event listeners added, then switch to old mode.
    if (EE.listenerCount(src, 'data') > 0)
      emitDataEvents(src);
    return;
  }

  // at this point, no one needed a drain, so we just ran out of data
  // on the next readable event, start it over again.
  state.ranOut = true;
}

function pipeOnReadable() {
  if (this._readableState.ranOut) {
    this._readableState.ranOut = false;
    flow(this);
  }
}


Readable.prototype.unpipe = function(dest) {
  var state = this._readableState;

  // if we're not piping anywhere, then do nothing.
  if (state.pipesCount === 0)
    return this;

  // just one destination.  most common case.
  if (state.pipesCount === 1) {
    // passed in one, but it's not the right one.
    if (dest && dest !== state.pipes)
      return this;

    if (!dest)
      dest = state.pipes;

    // got a match.
    state.pipes = null;
    state.pipesCount = 0;
    this.removeListener('readable', pipeOnReadable);
    state.flowing = false;
    if (dest)
      dest.emit('unpipe', this);
    return this;
  }

  // slow case. multiple pipe destinations.

  if (!dest) {
    // remove all.
    var dests = state.pipes;
    var len = state.pipesCount;
    state.pipes = null;
    state.pipesCount = 0;
    this.removeListener('readable', pipeOnReadable);
    state.flowing = false;

    for (var i = 0; i < len; i++)
      dests[i].emit('unpipe', this);
    return this;
  }

  // try to find the right one.
  var i = indexOf(state.pipes, dest);
  if (i === -1)
    return this;

  state.pipes.splice(i, 1);
  state.pipesCount -= 1;
  if (state.pipesCount === 1)
    state.pipes = state.pipes[0];

  dest.emit('unpipe', this);

  return this;
};

// set up data events if they are asked for
// Ensure readable listeners eventually get something
Readable.prototype.on = function(ev, fn) {
  var res = stream.prototype.on.call(this, ev, fn);

  if (ev === 'data' && !this._readableState.flowing)
    emitDataEvents(this);

  if (ev === 'readable' && this.readable) {
    var state = this._readableState;
    if (!state.readableListening) {
      state.readableListening = true;
      state.emittedReadable = false;
      state.needReadable = true;
      if (!state.reading) {
        this.read(0);
      } else if (state.length) {
        emitReadable(this);
      }
    }
  }

  return res;
};
Readable.prototype.addListener = Readable.prototype.on;

// pause() and resume() are remnants of the legacy readable stream API
// If the user uses them, then switch into old mode.
Readable.prototype.resume = function() {
  emitDataEvents(this);
  this.read(0);
  this.emit('resume');
};

Readable.prototype.pause = function() {
  emitDataEvents(this, true);
  this.emit('pause');
};

function emitDataEvents(stream$1, startPaused) {
  var state = stream$1._readableState;

  if (state.flowing) {
    // https://github.com/isaacs/readable-stream/issues/16
    throw new Error('Cannot switch to old mode now.');
  }

  var paused = startPaused || false;
  var readable = false;

  // convert to an old-style stream.
  stream$1.readable = true;
  stream$1.pipe = stream.prototype.pipe;
  stream$1.on = stream$1.addListener = stream.prototype.on;

  stream$1.on('readable', function() {
    readable = true;

    var c;
    while (!paused && (null !== (c = stream$1.read())))
      stream$1.emit('data', c);

    if (c === null) {
      readable = false;
      stream$1._readableState.needReadable = true;
    }
  });

  stream$1.pause = function() {
    paused = true;
    this.emit('pause');
  };

  stream$1.resume = function() {
    paused = false;
    if (readable)
      process.nextTick(function() {
        stream$1.emit('readable');
      });
    else
      this.read(0);
    this.emit('resume');
  };

  // now make it start, just in case it hadn't already.
  stream$1.emit('readable');
}

// wrap an old-style stream as the async data source.
// This is *not* part of the readable stream interface.
// It is an ugly unfortunate mess of history.
Readable.prototype.wrap = function(stream) {
  var state = this._readableState;
  var paused = false;

  var self = this;
  stream.on('end', function() {
    if (state.decoder && !state.ended) {
      var chunk = state.decoder.end();
      if (chunk && chunk.length)
        self.push(chunk);
    }

    self.push(null);
  });

  stream.on('data', function(chunk) {
    if (state.decoder)
      chunk = state.decoder.write(chunk);

    // don't skip over falsy values in objectMode
    //if (state.objectMode && util.isNullOrUndefined(chunk))
    if (state.objectMode && (chunk === null || chunk === undefined))
      return;
    else if (!state.objectMode && (!chunk || !chunk.length))
      return;

    var ret = self.push(chunk);
    if (!ret) {
      paused = true;
      stream.pause();
    }
  });

  // proxy all the other methods.
  // important when wrapping filters and duplexes.
  for (var i in stream) {
    if (typeof stream[i] === 'function' &&
        typeof this[i] === 'undefined') {
      this[i] = function(method) { return function() {
        return stream[method].apply(stream, arguments);
      }}(i);
    }
  }

  // proxy certain important events.
  var events = ['error', 'close', 'destroy', 'pause', 'resume'];
  forEach(events, function(ev) {
    stream.on(ev, self.emit.bind(self, ev));
  });

  // when we try to consume some more bytes, simply unpause the
  // underlying stream.
  self._read = function(n) {
    if (paused) {
      paused = false;
      stream.resume();
    }
  };

  return self;
};



// exposed for testing purposes only.
Readable._fromList = fromList;

// Pluck off n bytes from an array of buffers.
// Length is the combined lengths of all the buffers in the list.
function fromList(n, state) {
  var list = state.buffer;
  var length = state.length;
  var stringMode = !!state.decoder;
  var objectMode = !!state.objectMode;
  var ret;

  // nothing in the list, definitely empty.
  if (list.length === 0)
    return null;

  if (length === 0)
    ret = null;
  else if (objectMode)
    ret = list.shift();
  else if (!n || n >= length) {
    // read it all, truncate the array.
    if (stringMode)
      ret = list.join('');
    else
      ret = Buffer$2.concat(list, length);
    list.length = 0;
  } else {
    // read just some of it.
    if (n < list[0].length) {
      // just take a part of the first list item.
      // slice is the same for buffers and strings.
      var buf = list[0];
      ret = buf.slice(0, n);
      list[0] = buf.slice(n);
    } else if (n === list[0].length) {
      // first list is a perfect match
      ret = list.shift();
    } else {
      // complex case.
      // we have enough to cover it, but it spans past the first buffer.
      if (stringMode)
        ret = '';
      else
        ret = new Buffer$2(n);

      var c = 0;
      for (var i = 0, l = list.length; i < l && c < n; i++) {
        var buf = list[0];
        var cpy = Math.min(n - c, buf.length);

        if (stringMode)
          ret += buf.slice(0, cpy);
        else
          buf.copy(ret, c, 0, cpy);

        if (cpy < buf.length)
          list[0] = buf.slice(cpy);
        else
          list.shift();

        c += cpy;
      }
    }
  }

  return ret;
}

function endReadable(stream) {
  var state = stream._readableState;

  // If we get here before consuming all the bytes, then that is a
  // bug in node.  Should never happen.
  if (state.length > 0)
    throw new Error('endReadable called on non-empty stream');

  if (!state.endEmitted && state.calledRead) {
    state.ended = true;
    process.nextTick(function() {
      // Check that we didn't get one last unshift.
      if (!state.endEmitted && state.length === 0) {
        state.endEmitted = true;
        stream.readable = false;
        stream.emit('end');
      }
    });
  }
}

function forEach (xs, f) {
  for (var i = 0, l = xs.length; i < l; i++) {
    f(xs[i], i);
  }
}

function indexOf (xs, x) {
  for (var i = 0, l = xs.length; i < l; i++) {
    if (xs[i] === x) return i;
  }
  return -1;
}

// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.

// a duplex stream is just a stream that is both readable and writable.
// Since JS doesn't have multiple prototypal inheritance, this class
// prototypally inherits from Readable, and then parasitically from
// Writable.

var _stream_duplex = Duplex;

/*<replacement>*/
var objectKeys$1 = Object.keys || function (obj) {
  var keys = [];
  for (var key in obj) keys.push(key);
  return keys;
};
/*</replacement>*/


/*<replacement>*/

util.inherits = inherits_browser;
/*</replacement>*/




util.inherits(Duplex, _stream_readable);

forEach$1(objectKeys$1(_stream_writable.prototype), function(method) {
  if (!Duplex.prototype[method])
    Duplex.prototype[method] = _stream_writable.prototype[method];
});

function Duplex(options) {
  if (!(this instanceof Duplex))
    return new Duplex(options);

  _stream_readable.call(this, options);
  _stream_writable.call(this, options);

  if (options && options.readable === false)
    this.readable = false;

  if (options && options.writable === false)
    this.writable = false;

  this.allowHalfOpen = true;
  if (options && options.allowHalfOpen === false)
    this.allowHalfOpen = false;

  this.once('end', onend);
}

// the no-half-open enforcer
function onend() {
  // if we allow half-open state, or if the writable side ended,
  // then we're ok.
  if (this.allowHalfOpen || this._writableState.ended)
    return;

  // no more data can be written.
  // But allow more writes to happen in this tick.
  process.nextTick(this.end.bind(this));
}

function forEach$1 (xs, f) {
  for (var i = 0, l = xs.length; i < l; i++) {
    f(xs[i], i);
  }
}

// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.

// A bit simpler than readable streams.
// Implement an async ._write(chunk, cb), and it'll handle all
// the drain event emission and buffering.

var _stream_writable = Writable;

/*<replacement>*/
var Buffer$3 = buffer.Buffer;
/*</replacement>*/

Writable.WritableState = WritableState;


/*<replacement>*/

util.inherits = inherits_browser;
/*</replacement>*/



util.inherits(Writable, stream);

function WriteReq(chunk, encoding, cb) {
  this.chunk = chunk;
  this.encoding = encoding;
  this.callback = cb;
}

function WritableState(options, stream) {
  options = options || {};

  // the point at which write() starts returning false
  // Note: 0 is a valid value, means that we always return false if
  // the entire buffer is not flushed immediately on write()
  var hwm = options.highWaterMark;
  this.highWaterMark = (hwm || hwm === 0) ? hwm : 16 * 1024;

  // object stream flag to indicate whether or not this stream
  // contains buffers or objects.
  this.objectMode = !!options.objectMode;

  // cast to ints.
  this.highWaterMark = ~~this.highWaterMark;

  this.needDrain = false;
  // at the start of calling end()
  this.ending = false;
  // when end() has been called, and returned
  this.ended = false;
  // when 'finish' is emitted
  this.finished = false;

  // should we decode strings into buffers before passing to _write?
  // this is here so that some node-core streams can optimize string
  // handling at a lower level.
  var noDecode = options.decodeStrings === false;
  this.decodeStrings = !noDecode;

  // Crypto is kind of old and crusty.  Historically, its default string
  // encoding is 'binary' so we have to make this configurable.
  // Everything else in the universe uses 'utf8', though.
  this.defaultEncoding = options.defaultEncoding || 'utf8';

  // not an actual buffer we keep track of, but a measurement
  // of how much we're waiting to get pushed to some underlying
  // socket or file.
  this.length = 0;

  // a flag to see when we're in the middle of a write.
  this.writing = false;

  // a flag to be able to tell if the onwrite cb is called immediately,
  // or on a later tick.  We set this to true at first, becuase any
  // actions that shouldn't happen until "later" should generally also
  // not happen before the first write call.
  this.sync = true;

  // a flag to know if we're processing previously buffered items, which
  // may call the _write() callback in the same tick, so that we don't
  // end up in an overlapped onwrite situation.
  this.bufferProcessing = false;

  // the callback that's passed to _write(chunk,cb)
  this.onwrite = function(er) {
    onwrite(stream, er);
  };

  // the callback that the user supplies to write(chunk,encoding,cb)
  this.writecb = null;

  // the amount that is being written when _write is called.
  this.writelen = 0;

  this.buffer = [];

  // True if the error was already emitted and should not be thrown again
  this.errorEmitted = false;
}

function Writable(options) {
  var Duplex = _stream_duplex;

  // Writable ctor is applied to Duplexes, though they're not
  // instanceof Writable, they're instanceof Readable.
  if (!(this instanceof Writable) && !(this instanceof Duplex))
    return new Writable(options);

  this._writableState = new WritableState(options, this);

  // legacy.
  this.writable = true;

  stream.call(this);
}

// Otherwise people can pipe Writable streams, which is just wrong.
Writable.prototype.pipe = function() {
  this.emit('error', new Error('Cannot pipe. Not readable.'));
};


function writeAfterEnd(stream, state, cb) {
  var er = new Error('write after end');
  // TODO: defer error events consistently everywhere, not just the cb
  stream.emit('error', er);
  process.nextTick(function() {
    cb(er);
  });
}

// If we get something that is not a buffer, string, null, or undefined,
// and we're not in objectMode, then that's an error.
// Otherwise stream chunks are all considered to be of length=1, and the
// watermarks determine how many objects to keep in the buffer, rather than
// how many bytes or characters.
function validChunk(stream, state, chunk, cb) {
  var valid = true;
  if (!Buffer$3.isBuffer(chunk) &&
      'string' !== typeof chunk &&
      chunk !== null &&
      chunk !== undefined &&
      !state.objectMode) {
    var er = new TypeError('Invalid non-string/buffer chunk');
    stream.emit('error', er);
    process.nextTick(function() {
      cb(er);
    });
    valid = false;
  }
  return valid;
}

Writable.prototype.write = function(chunk, encoding, cb) {
  var state = this._writableState;
  var ret = false;

  if (typeof encoding === 'function') {
    cb = encoding;
    encoding = null;
  }

  if (Buffer$3.isBuffer(chunk))
    encoding = 'buffer';
  else if (!encoding)
    encoding = state.defaultEncoding;

  if (typeof cb !== 'function')
    cb = function() {};

  if (state.ended)
    writeAfterEnd(this, state, cb);
  else if (validChunk(this, state, chunk, cb))
    ret = writeOrBuffer(this, state, chunk, encoding, cb);

  return ret;
};

function decodeChunk(state, chunk, encoding) {
  if (!state.objectMode &&
      state.decodeStrings !== false &&
      typeof chunk === 'string') {
    chunk = new Buffer$3(chunk, encoding);
  }
  return chunk;
}

// if we're already writing something, then just put this
// in the queue, and wait our turn.  Otherwise, call _write
// If we return false, then we need a drain event, so set that flag.
function writeOrBuffer(stream, state, chunk, encoding, cb) {
  chunk = decodeChunk(state, chunk, encoding);
  if (Buffer$3.isBuffer(chunk))
    encoding = 'buffer';
  var len = state.objectMode ? 1 : chunk.length;

  state.length += len;

  var ret = state.length < state.highWaterMark;
  // we must ensure that previous needDrain will not be reset to false.
  if (!ret)
    state.needDrain = true;

  if (state.writing)
    state.buffer.push(new WriteReq(chunk, encoding, cb));
  else
    doWrite(stream, state, len, chunk, encoding, cb);

  return ret;
}

function doWrite(stream, state, len, chunk, encoding, cb) {
  state.writelen = len;
  state.writecb = cb;
  state.writing = true;
  state.sync = true;
  stream._write(chunk, encoding, state.onwrite);
  state.sync = false;
}

function onwriteError(stream, state, sync, er, cb) {
  if (sync)
    process.nextTick(function() {
      cb(er);
    });
  else
    cb(er);

  stream._writableState.errorEmitted = true;
  stream.emit('error', er);
}

function onwriteStateUpdate(state) {
  state.writing = false;
  state.writecb = null;
  state.length -= state.writelen;
  state.writelen = 0;
}

function onwrite(stream, er) {
  var state = stream._writableState;
  var sync = state.sync;
  var cb = state.writecb;

  onwriteStateUpdate(state);

  if (er)
    onwriteError(stream, state, sync, er, cb);
  else {
    // Check if we're actually ready to finish, but don't emit yet
    var finished = needFinish(stream, state);

    if (!finished && !state.bufferProcessing && state.buffer.length)
      clearBuffer(stream, state);

    if (sync) {
      process.nextTick(function() {
        afterWrite(stream, state, finished, cb);
      });
    } else {
      afterWrite(stream, state, finished, cb);
    }
  }
}

function afterWrite(stream, state, finished, cb) {
  if (!finished)
    onwriteDrain(stream, state);
  cb();
  if (finished)
    finishMaybe(stream, state);
}

// Must force callback to be called on nextTick, so that we don't
// emit 'drain' before the write() consumer gets the 'false' return
// value, and has a chance to attach a 'drain' listener.
function onwriteDrain(stream, state) {
  if (state.length === 0 && state.needDrain) {
    state.needDrain = false;
    stream.emit('drain');
  }
}


// if there's something in the buffer waiting, then process it
function clearBuffer(stream, state) {
  state.bufferProcessing = true;

  for (var c = 0; c < state.buffer.length; c++) {
    var entry = state.buffer[c];
    var chunk = entry.chunk;
    var encoding = entry.encoding;
    var cb = entry.callback;
    var len = state.objectMode ? 1 : chunk.length;

    doWrite(stream, state, len, chunk, encoding, cb);

    // if we didn't call the onwrite immediately, then
    // it means that we need to wait until it does.
    // also, that means that the chunk and cb are currently
    // being processed, so move the buffer counter past them.
    if (state.writing) {
      c++;
      break;
    }
  }

  state.bufferProcessing = false;
  if (c < state.buffer.length)
    state.buffer = state.buffer.slice(c);
  else
    state.buffer.length = 0;
}

Writable.prototype._write = function(chunk, encoding, cb) {
  cb(new Error('not implemented'));
};

Writable.prototype.end = function(chunk, encoding, cb) {
  var state = this._writableState;

  if (typeof chunk === 'function') {
    cb = chunk;
    chunk = null;
    encoding = null;
  } else if (typeof encoding === 'function') {
    cb = encoding;
    encoding = null;
  }

  if (typeof chunk !== 'undefined' && chunk !== null)
    this.write(chunk, encoding);

  // ignore unnecessary end() calls.
  if (!state.ending && !state.finished)
    endWritable(this, state, cb);
};


function needFinish(stream, state) {
  return (state.ending &&
          state.length === 0 &&
          !state.finished &&
          !state.writing);
}

function finishMaybe(stream, state) {
  var need = needFinish(stream, state);
  if (need) {
    state.finished = true;
    stream.emit('finish');
  }
  return need;
}

function endWritable(stream, state, cb) {
  state.ending = true;
  finishMaybe(stream, state);
  if (cb) {
    if (state.finished)
      process.nextTick(cb);
    else
      stream.once('finish', cb);
  }
  state.ended = true;
}

// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.


// a transform stream is a readable/writable stream where you do
// something with the data.  Sometimes it's called a "filter",
// but that's not a great name for it, since that implies a thing where
// some bits pass through, and others are simply ignored.  (That would
// be a valid example of a transform, of course.)
//
// While the output is causally related to the input, it's not a
// necessarily symmetric or synchronous transformation.  For example,
// a zlib stream might take multiple plain-text writes(), and then
// emit a single compressed chunk some time in the future.
//
// Here's how this works:
//
// The Transform stream has all the aspects of the readable and writable
// stream classes.  When you write(chunk), that calls _write(chunk,cb)
// internally, and returns false if there's a lot of pending writes
// buffered up.  When you call read(), that calls _read(n) until
// there's enough pending readable data buffered up.
//
// In a transform stream, the written data is placed in a buffer.  When
// _read(n) is called, it transforms the queued up data, calling the
// buffered _write cb's as it consumes chunks.  If consuming a single
// written chunk would result in multiple output chunks, then the first
// outputted bit calls the readcb, and subsequent chunks just go into
// the read buffer, and will cause it to emit 'readable' if necessary.
//
// This way, back-pressure is actually determined by the reading side,
// since _read has to be called to start processing a new chunk.  However,
// a pathological inflate type of transform can cause excessive buffering
// here.  For example, imagine a stream where every byte of input is
// interpreted as an integer from 0-255, and then results in that many
// bytes of output.  Writing the 4 bytes {ff,ff,ff,ff} would result in
// 1kb of data being output.  In this case, you could write a very small
// amount of input, and end up with a very large amount of output.  In
// such a pathological inflating mechanism, there'd be no way to tell
// the system to stop doing the transform.  A single 4MB write could
// cause the system to run out of memory.
//
// However, even in such a pathological case, only a single written chunk
// would be consumed, and then the rest would wait (un-transformed) until
// the results of the previous transformed chunk were consumed.

var _stream_transform = Transform;



/*<replacement>*/

util.inherits = inherits_browser;
/*</replacement>*/

util.inherits(Transform, _stream_duplex);


function TransformState(options, stream) {
  this.afterTransform = function(er, data) {
    return afterTransform(stream, er, data);
  };

  this.needTransform = false;
  this.transforming = false;
  this.writecb = null;
  this.writechunk = null;
}

function afterTransform(stream, er, data) {
  var ts = stream._transformState;
  ts.transforming = false;

  var cb = ts.writecb;

  if (!cb)
    return stream.emit('error', new Error('no writecb in Transform class'));

  ts.writechunk = null;
  ts.writecb = null;

  if (data !== null && data !== undefined)
    stream.push(data);

  if (cb)
    cb(er);

  var rs = stream._readableState;
  rs.reading = false;
  if (rs.needReadable || rs.length < rs.highWaterMark) {
    stream._read(rs.highWaterMark);
  }
}


function Transform(options) {
  if (!(this instanceof Transform))
    return new Transform(options);

  _stream_duplex.call(this, options);

  var ts = this._transformState = new TransformState(options, this);

  // when the writable side finishes, then flush out anything remaining.
  var stream = this;

  // start out asking for a readable event once data is transformed.
  this._readableState.needReadable = true;

  // we have implemented the _read method, and done the other things
  // that Readable wants before the first _read call, so unset the
  // sync guard flag.
  this._readableState.sync = false;

  this.once('finish', function() {
    if ('function' === typeof this._flush)
      this._flush(function(er) {
        done(stream, er);
      });
    else
      done(stream);
  });
}

Transform.prototype.push = function(chunk, encoding) {
  this._transformState.needTransform = false;
  return _stream_duplex.prototype.push.call(this, chunk, encoding);
};

// This is the part where you do stuff!
// override this function in implementation classes.
// 'chunk' is an input chunk.
//
// Call `push(newChunk)` to pass along transformed output
// to the readable side.  You may call 'push' zero or more times.
//
// Call `cb(err)` when you are done with this chunk.  If you pass
// an error, then that'll put the hurt on the whole operation.  If you
// never call cb(), then you'll never get another chunk.
Transform.prototype._transform = function(chunk, encoding, cb) {
  throw new Error('not implemented');
};

Transform.prototype._write = function(chunk, encoding, cb) {
  var ts = this._transformState;
  ts.writecb = cb;
  ts.writechunk = chunk;
  ts.writeencoding = encoding;
  if (!ts.transforming) {
    var rs = this._readableState;
    if (ts.needTransform ||
        rs.needReadable ||
        rs.length < rs.highWaterMark)
      this._read(rs.highWaterMark);
  }
};

// Doesn't matter what the args are here.
// _transform does all the work.
// That we got here means that the readable side wants more data.
Transform.prototype._read = function(n) {
  var ts = this._transformState;

  if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
    ts.transforming = true;
    this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
  } else {
    // mark that we need a transform, so that any data that comes in
    // will get processed, now that we've asked for it.
    ts.needTransform = true;
  }
};


function done(stream, er) {
  if (er)
    return stream.emit('error', er);

  // if there's nothing in the write buffer, then that means
  // that nothing more will ever be provided
  var ws = stream._writableState;
  var rs = stream._readableState;
  var ts = stream._transformState;

  if (ws.length)
    throw new Error('calling transform done when ws.length != 0');

  if (ts.transforming)
    throw new Error('calling transform done when still transforming');

  return stream.push(null);
}

// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.

// a passthrough stream.
// basically just the most minimal sort of Transform stream.
// Every written chunk gets output as-is.

var _stream_passthrough = PassThrough;



/*<replacement>*/

util.inherits = inherits_browser;
/*</replacement>*/

util.inherits(PassThrough, _stream_transform);

function PassThrough(options) {
  if (!(this instanceof PassThrough))
    return new PassThrough(options);

  _stream_transform.call(this, options);
}

PassThrough.prototype._transform = function(chunk, encoding, cb) {
  cb(null, chunk);
};

var readable = createCommonjsModule(function 
Download .txt
gitextract_csbhc0ta/

├── .gitignore
├── LICENSE.md
├── browser-test/
│   ├── index.js
│   └── main.js
├── package.json
├── polyfills/
│   ├── LICENSE-browserify-fs.txt
│   ├── LICENSE-buffer-es6.txt
│   ├── LICENSE-crypto-browserify.txt
│   ├── LICENSE-process-es6.txt
│   ├── assert.js
│   ├── browserify-fs.js
│   ├── buffer-es6.js
│   ├── console.js
│   ├── constants.js
│   ├── crypto-browserify.js
│   ├── domain.js
│   ├── empty.js
│   ├── events.js
│   ├── global.js
│   ├── http-lib/
│   │   ├── capability.js
│   │   ├── request.js
│   │   ├── response.js
│   │   └── to-arraybuffer.js
│   ├── http.js
│   ├── inherits.js
│   ├── os.js
│   ├── path.js
│   ├── process-es6.js
│   ├── punycode.js
│   ├── qs.js
│   ├── readable-stream/
│   │   ├── buffer-list.js
│   │   ├── duplex.js
│   │   ├── passthrough.js
│   │   ├── readable.js
│   │   ├── transform.js
│   │   └── writable.js
│   ├── setimmediate.js
│   ├── stream.js
│   ├── string-decoder.js
│   ├── timers.js
│   ├── tty.js
│   ├── url.js
│   ├── util.js
│   ├── vm.js
│   ├── zlib-lib/
│   │   ├── LICENSE
│   │   ├── adler32.js
│   │   ├── binding.js
│   │   ├── crc32.js
│   │   ├── deflate.js
│   │   ├── inffast.js
│   │   ├── inflate.js
│   │   ├── inftrees.js
│   │   ├── messages.js
│   │   ├── trees.js
│   │   ├── utils.js
│   │   └── zstream.js
│   └── zlib.js
├── readme.md
├── rollup.config.js
├── scripts/
│   ├── build-constants.js
│   └── build-polyfills.js
├── src/
│   ├── index.ts
│   └── modules.ts
├── test/
│   ├── examples/
│   │   ├── assert.js
│   │   ├── constants.js
│   │   ├── crypto.js
│   │   ├── domain.js
│   │   ├── events.js
│   │   ├── os.js
│   │   ├── path.js
│   │   ├── stream.js
│   │   ├── string-decoder.js
│   │   ├── url-format.js
│   │   ├── url-parse.js
│   │   └── zlib.js
│   └── index.js
└── tsconfig.json
Download .txt
SYMBOL INDEX (1173 symbols across 47 files)

FILE: browser-test/main.js
  function afterMain (line 21) | function afterMain() {
  function afterWorker (line 34) | function afterWorker() {

FILE: polyfills/assert.js
  function compare (line 2) | function compare(a, b) {
  function functionsHaveNames (line 64) | function functionsHaveNames() {
  function pToString (line 72) | function pToString (obj) {
  function isView (line 75) | function isView(arrbuf) {
  function assert (line 100) | function assert(value, message) {
  function getName (line 112) | function getName(func) {
  function AssertionError (line 124) | function AssertionError(options) {
  function truncate (line 163) | function truncate(s, n) {
  function inspect (line 170) | function inspect(something) {
  function getMessage (line 178) | function getMessage(self) {
  function fail (line 195) | function fail(actual, expected, message, operator, stackStartFunction) {
  function ok (line 215) | function ok(value, message) {
  function equal (line 225) | function equal(actual, expected, message) {
  function notEqual (line 232) | function notEqual(actual, expected, message) {
  function deepEqual (line 241) | function deepEqual(actual, expected, message) {
  function deepStrictEqual (line 247) | function deepStrictEqual(actual, expected, message) {
  function _deepEqual (line 253) | function _deepEqual(actual, expected, strict, memos) {
  function isArguments (line 319) | function isArguments(object) {
  function objEquiv (line 323) | function objEquiv(a, b, strict, actualVisitedObjects) {
  function notDeepEqual (line 368) | function notDeepEqual(actual, expected, message) {
  function notDeepStrictEqual (line 375) | function notDeepStrictEqual(actual, expected, message) {
  function strictEqual (line 385) | function strictEqual(actual, expected, message) {
  function notStrictEqual (line 394) | function notStrictEqual(actual, expected, message) {
  function expectedException (line 400) | function expectedException(actual, expected) {
  function _tryBlock (line 424) | function _tryBlock(block) {
  function _throws (line 434) | function _throws(shouldThrow, block, expected, message) {
  function throws (line 475) | function throws(block, /*optional*/error, /*optional*/message) {
  function doesNotThrow (line 481) | function doesNotThrow(block, /*optional*/error, /*optional*/message) {
  function ifError (line 486) | function ifError(err) {

FILE: polyfills/browserify-fs.js
  function createCommonjsModule (line 9) | function createCommonjsModule(fn, module) {
  function getCjsExportFromNamespace (line 13) | function getCjsExportFromNamespace (n) {
  function mixin (line 1388) | function mixin (target, source) {
  function hasVersionError (line 1399) | function hasVersionError(errorEvent) {
  function extend (line 1418) | function extend() {
  function AbstractIterator (line 1436) | function AbstractIterator (db) {
  function AbstractChainedBatch (line 1486) | function AbstractChainedBatch (db) {
  function AbstractLevelDOWN (line 1570) | function AbstractLevelDOWN (location) {
  function isDef (line 1847) | function isDef (val) {
  function has (line 1851) | function has (range, name) {
  function hasKey (line 1855) | function hasKey(range, name) {
  function id (line 1929) | function id (e) { return e }
  function Iterator (line 2013) | function Iterator (db, options) {
  function isBuffer (line 2084) | function isBuffer (o) {
  function hasKeys (line 2212) | function hasKeys(source) {
  function extend$1 (line 2220) | function extend$1() {
  function Level (line 2271) | function Level(location) {
  function extend$2 (line 2437) | function extend$2() {
  function DeferredLevelDOWN (line 2521) | function DeferredLevelDOWN (location) {
  function init (line 2632) | function init (type, message, cause) {
  function CustomError (line 2646) | function CustomError (message, cause) {
  function createError (line 2655) | function createError (errno, type, proto) {
  function isArray (line 3060) | function isArray(arg) {
  function isBoolean (line 3068) | function isBoolean(arg) {
  function isNull (line 3073) | function isNull(arg) {
  function isNullOrUndefined (line 3078) | function isNullOrUndefined(arg) {
  function isNumber (line 3083) | function isNumber(arg) {
  function isString (line 3088) | function isString(arg) {
  function isSymbol (line 3093) | function isSymbol(arg) {
  function isUndefined (line 3098) | function isUndefined(arg) {
  function isRegExp (line 3103) | function isRegExp(re) {
  function isObject (line 3108) | function isObject(arg) {
  function isDate (line 3113) | function isDate(d) {
  function isError (line 3118) | function isError(e) {
  function isFunction$1 (line 3123) | function isFunction$1(arg) {
  function isPrimitive (line 3128) | function isPrimitive(arg) {
  function objectToString (line 3140) | function objectToString(o) {
  function assertEncoding (line 3221) | function assertEncoding(encoding) {
  function passThroughWrite (line 3397) | function passThroughWrite(buffer) {
  function utf16DetectIncompleteChar (line 3401) | function utf16DetectIncompleteChar(buffer) {
  function base64DetectIncompleteChar (line 3406) | function base64DetectIncompleteChar(buffer) {
  function ReadableState (line 3466) | function ReadableState(options, stream) {
  function Readable (line 3534) | function Readable(options) {
  function readableAddChunk (line 3570) | function readableAddChunk(stream, state, chunk, encoding, addToFront) {
  function needMoreData (line 3619) | function needMoreData(state) {
  function roundUpToNextPowerOf2 (line 3636) | function roundUpToNextPowerOf2(n) {
  function howMuchToRead (line 3648) | function howMuchToRead(n, state) {
  function chunkInvalid (line 3810) | function chunkInvalid(state, chunk) {
  function onEofChunk (line 3823) | function onEofChunk(stream, state) {
  function emitReadable (line 3844) | function emitReadable(stream) {
  function emitReadable_ (line 3859) | function emitReadable_(stream) {
  function maybeReadMore (line 3870) | function maybeReadMore(stream, state) {
  function maybeReadMore_ (line 3879) | function maybeReadMore_(stream, state) {
  function onunpipe (line 3929) | function onunpipe(readable) {
  function onend (line 3934) | function onend() {
  function cleanup (line 3945) | function cleanup() {
  function onerror (line 3966) | function onerror(er) {
  function onclose (line 3984) | function onclose() {
  function onfinish (line 3989) | function onfinish() {
  function unpipe (line 3995) | function unpipe() {
  function pipeOnDrain (line 4019) | function pipeOnDrain(src) {
  function flow (line 4028) | function flow(src) {
  function pipeOnReadable (line 4072) | function pipeOnReadable() {
  function emitDataEvents (line 4176) | function emitDataEvents(stream$1, startPaused) {
  function fromList (line 4297) | function fromList(n, state) {
  function endReadable (line 4361) | function endReadable(stream) {
  function forEach (line 4382) | function forEach (xs, f) {
  function indexOf (line 4388) | function indexOf (xs, x) {
  function Duplex (line 4447) | function Duplex(options) {
  function onend (line 4468) | function onend() {
  function forEach$1 (line 4479) | function forEach$1 (xs, f) {
  function WriteReq (line 4528) | function WriteReq(chunk, encoding, cb) {
  function WritableState (line 4534) | function WritableState(options, stream) {
  function Writable (line 4605) | function Writable(options) {
  function writeAfterEnd (line 4627) | function writeAfterEnd(stream, state, cb) {
  function validChunk (line 4641) | function validChunk(stream, state, chunk, cb) {
  function decodeChunk (line 4683) | function decodeChunk(state, chunk, encoding) {
  function writeOrBuffer (line 4695) | function writeOrBuffer(stream, state, chunk, encoding, cb) {
  function doWrite (line 4716) | function doWrite(stream, state, len, chunk, encoding, cb) {
  function onwriteError (line 4725) | function onwriteError(stream, state, sync, er, cb) {
  function onwriteStateUpdate (line 4737) | function onwriteStateUpdate(state) {
  function onwrite (line 4744) | function onwrite(stream, er) {
  function afterWrite (line 4770) | function afterWrite(stream, state, finished, cb) {
  function onwriteDrain (line 4781) | function onwriteDrain(stream, state) {
  function clearBuffer (line 4790) | function clearBuffer(stream, state) {
  function needFinish (line 4844) | function needFinish(stream, state) {
  function finishMaybe (line 4851) | function finishMaybe(stream, state) {
  function endWritable (line 4860) | function endWritable(stream, state, cb) {
  function TransformState (line 4948) | function TransformState(options, stream) {
  function afterTransform (line 4959) | function afterTransform(stream, er, data) {
  function Transform (line 4985) | function Transform(options) {
  function done (line 5064) | function done(stream, er) {
  function PassThrough (line 5119) | function PassThrough(options) {
  function isBinary (line 5299) | function isBinary (data) {
  function copy (line 5345) | function copy (srcdb, dstdb, callback) {
  function getOptions (line 5352) | function getOptions (levelup, options) {
  function getLevelDOWN (line 5363) | function getLevelDOWN () {
  function dispatchError (line 5394) | function dispatchError (levelup, error, callback) {
  function getKeyEncoder (line 5400) | function getKeyEncoder (options, op) {
  function getValueEncoder (line 5405) | function getValueEncoder (options, op) {
  function encodeKey (line 5411) | function encodeKey (key, options, op) {
  function encodeValue (line 5415) | function encodeValue (value, options, op) {
  function decodeKey (line 5419) | function decodeKey (key, options) {
  function decodeValue (line 5423) | function decodeValue (value, options) {
  function isValueAsBuffer (line 5427) | function isValueAsBuffer (options, op) {
  function isKeyAsBuffer (line 5431) | function isKeyAsBuffer (options, op) {
  function ReadStream (line 5476) | function ReadStream (options, db, iteratorFactory) {
  function assertEncoding (line 5611) | function assertEncoding(encoding) {
  function passThroughWrite (line 5787) | function passThroughWrite(buffer) {
  function utf16DetectIncompleteChar (line 5791) | function utf16DetectIncompleteChar(buffer) {
  function base64DetectIncompleteChar (line 5796) | function base64DetectIncompleteChar(buffer) {
  function ReadableState$1 (line 5856) | function ReadableState$1(options, stream) {
  function Readable$2 (line 5924) | function Readable$2(options) {
  function readableAddChunk$1 (line 5960) | function readableAddChunk$1(stream, state, chunk, encoding, addToFront) {
  function needMoreData$1 (line 6009) | function needMoreData$1(state) {
  function roundUpToNextPowerOf2$1 (line 6026) | function roundUpToNextPowerOf2$1(n) {
  function howMuchToRead$1 (line 6038) | function howMuchToRead$1(n, state) {
  function chunkInvalid$1 (line 6200) | function chunkInvalid$1(state, chunk) {
  function onEofChunk$1 (line 6213) | function onEofChunk$1(stream, state) {
  function emitReadable$1 (line 6234) | function emitReadable$1(stream) {
  function emitReadable_$1 (line 6249) | function emitReadable_$1(stream) {
  function maybeReadMore$1 (line 6260) | function maybeReadMore$1(stream, state) {
  function maybeReadMore_$1 (line 6269) | function maybeReadMore_$1(stream, state) {
  function onunpipe (line 6319) | function onunpipe(readable) {
  function onend (line 6324) | function onend() {
  function cleanup (line 6335) | function cleanup() {
  function onerror (line 6356) | function onerror(er) {
  function onclose (line 6374) | function onclose() {
  function onfinish (line 6379) | function onfinish() {
  function unpipe (line 6385) | function unpipe() {
  function pipeOnDrain$1 (line 6409) | function pipeOnDrain$1(src) {
  function flow$1 (line 6418) | function flow$1(src) {
  function pipeOnReadable$1 (line 6462) | function pipeOnReadable$1() {
  function emitDataEvents$1 (line 6566) | function emitDataEvents$1(stream$1, startPaused) {
  function fromList$1 (line 6687) | function fromList$1(n, state) {
  function endReadable$1 (line 6751) | function endReadable$1(stream) {
  function forEach$2 (line 6772) | function forEach$2 (xs, f) {
  function indexOf$1 (line 6778) | function indexOf$1 (xs, x) {
  function Duplex$1 (line 6837) | function Duplex$1(options) {
  function onend$1 (line 6858) | function onend$1() {
  function forEach$3 (line 6869) | function forEach$3 (xs, f) {
  function WriteReq$1 (line 6918) | function WriteReq$1(chunk, encoding, cb) {
  function WritableState$1 (line 6924) | function WritableState$1(options, stream) {
  function Writable$1 (line 6995) | function Writable$1(options) {
  function writeAfterEnd$1 (line 7017) | function writeAfterEnd$1(stream, state, cb) {
  function validChunk$1 (line 7031) | function validChunk$1(stream, state, chunk, cb) {
  function decodeChunk$1 (line 7073) | function decodeChunk$1(state, chunk, encoding) {
  function writeOrBuffer$1 (line 7085) | function writeOrBuffer$1(stream, state, chunk, encoding, cb) {
  function doWrite$1 (line 7106) | function doWrite$1(stream, state, len, chunk, encoding, cb) {
  function onwriteError$1 (line 7115) | function onwriteError$1(stream, state, sync, er, cb) {
  function onwriteStateUpdate$1 (line 7127) | function onwriteStateUpdate$1(state) {
  function onwrite$1 (line 7134) | function onwrite$1(stream, er) {
  function afterWrite$1 (line 7160) | function afterWrite$1(stream, state, finished, cb) {
  function onwriteDrain$1 (line 7171) | function onwriteDrain$1(stream, state) {
  function clearBuffer$1 (line 7180) | function clearBuffer$1(stream, state) {
  function needFinish$1 (line 7234) | function needFinish$1(stream, state) {
  function finishMaybe$1 (line 7241) | function finishMaybe$1(stream, state) {
  function endWritable$1 (line 7250) | function endWritable$1(stream, state, cb) {
  function TransformState$1 (line 7338) | function TransformState$1(options, stream) {
  function afterTransform$1 (line 7349) | function afterTransform$1(stream, er, data) {
  function Transform$1 (line 7375) | function Transform$1(options) {
  function done$1 (line 7454) | function done$1(stream, er) {
  function PassThrough$1 (line 7509) | function PassThrough$1(options) {
  function BufferList (line 7542) | function BufferList (callback) {
  function WriteStream (line 7768) | function WriteStream (options, db) {
  function Batch (line 7941) | function Batch (levelup) {
  function getCallback (line 8029) | function getCallback (options, callback) {
  function LevelUP (line 8041) | function LevelUP (location, options, callback) {
  function utilStatic (line 8423) | function utilStatic (name) {
  function assertEncoding (line 8476) | function assertEncoding(encoding) {
  function passThroughWrite (line 8652) | function passThroughWrite(buffer) {
  function utf16DetectIncompleteChar (line 8656) | function utf16DetectIncompleteChar(buffer) {
  function base64DetectIncompleteChar (line 8661) | function base64DetectIncompleteChar(buffer) {
  function ReadableState$2 (line 8721) | function ReadableState$2(options, stream) {
  function Readable$3 (line 8789) | function Readable$3(options) {
  function readableAddChunk$2 (line 8825) | function readableAddChunk$2(stream, state, chunk, encoding, addToFront) {
  function needMoreData$2 (line 8874) | function needMoreData$2(state) {
  function roundUpToNextPowerOf2$2 (line 8891) | function roundUpToNextPowerOf2$2(n) {
  function howMuchToRead$2 (line 8903) | function howMuchToRead$2(n, state) {
  function chunkInvalid$2 (line 9065) | function chunkInvalid$2(state, chunk) {
  function onEofChunk$2 (line 9078) | function onEofChunk$2(stream, state) {
  function emitReadable$2 (line 9099) | function emitReadable$2(stream) {
  function emitReadable_$2 (line 9114) | function emitReadable_$2(stream) {
  function maybeReadMore$2 (line 9125) | function maybeReadMore$2(stream, state) {
  function maybeReadMore_$2 (line 9134) | function maybeReadMore_$2(stream, state) {
  function onunpipe (line 9184) | function onunpipe(readable) {
  function onend (line 9189) | function onend() {
  function cleanup (line 9200) | function cleanup() {
  function onerror (line 9221) | function onerror(er) {
  function onclose (line 9239) | function onclose() {
  function onfinish (line 9244) | function onfinish() {
  function unpipe (line 9250) | function unpipe() {
  function pipeOnDrain$2 (line 9274) | function pipeOnDrain$2(src) {
  function flow$2 (line 9283) | function flow$2(src) {
  function pipeOnReadable$2 (line 9327) | function pipeOnReadable$2() {
  function emitDataEvents$2 (line 9431) | function emitDataEvents$2(stream$1, startPaused) {
  function fromList$2 (line 9552) | function fromList$2(n, state) {
  function endReadable$2 (line 9616) | function endReadable$2(stream) {
  function forEach$4 (line 9637) | function forEach$4 (xs, f) {
  function indexOf$2 (line 9643) | function indexOf$2 (xs, x) {
  function Duplex$2 (line 9702) | function Duplex$2(options) {
  function onend$2 (line 9723) | function onend$2() {
  function forEach$5 (line 9734) | function forEach$5 (xs, f) {
  function WriteReq$2 (line 9783) | function WriteReq$2(chunk, encoding, cb) {
  function WritableState$2 (line 9789) | function WritableState$2(options, stream) {
  function Writable$2 (line 9860) | function Writable$2(options) {
  function writeAfterEnd$2 (line 9882) | function writeAfterEnd$2(stream, state, cb) {
  function validChunk$2 (line 9896) | function validChunk$2(stream, state, chunk, cb) {
  function decodeChunk$2 (line 9938) | function decodeChunk$2(state, chunk, encoding) {
  function writeOrBuffer$2 (line 9950) | function writeOrBuffer$2(stream, state, chunk, encoding, cb) {
  function doWrite$2 (line 9971) | function doWrite$2(stream, state, len, chunk, encoding, cb) {
  function onwriteError$2 (line 9980) | function onwriteError$2(stream, state, sync, er, cb) {
  function onwriteStateUpdate$2 (line 9992) | function onwriteStateUpdate$2(state) {
  function onwrite$2 (line 9999) | function onwrite$2(stream, er) {
  function afterWrite$2 (line 10025) | function afterWrite$2(stream, state, finished, cb) {
  function onwriteDrain$2 (line 10036) | function onwriteDrain$2(stream, state) {
  function clearBuffer$2 (line 10045) | function clearBuffer$2(stream, state) {
  function needFinish$2 (line 10099) | function needFinish$2(stream, state) {
  function finishMaybe$2 (line 10106) | function finishMaybe$2(stream, state) {
  function endWritable$2 (line 10115) | function endWritable$2(stream, state, cb) {
  function TransformState$2 (line 10205) | function TransformState$2(options, stream) {
  function afterTransform$2 (line 10216) | function afterTransform$2(stream, er, data) {
  function Transform$2 (line 10242) | function Transform$2(options) {
  function done$2 (line 10321) | function done$2(stream, er) {
  function PassThrough$2 (line 10376) | function PassThrough$2(options) {
  function objectToString (line 10648) | function objectToString(o) {
  function clone (line 10695) | function clone(parent, circular, depth, prototype) {
  function hasKeys$1 (line 11587) | function hasKeys$1(source) {
  function extend$3 (line 11595) | function extend$3() {
  function addOperation (line 11616) | function addOperation (type, key, value, options) {
  function Batch$1 (line 11634) | function Batch$1(sdb) {
  function SubDB (line 11665) | function SubDB (db, prefix, options) {
  function selectivelyMerge (line 11790) | function selectivelyMerge(_opts, opts) {
  function root (line 11898) | function root(db) {
  function getPrefix (line 11943) | function getPrefix (p) {
  function getKeyEncoding (line 11952) | function getKeyEncoding (db) {
  function getValueEncoding (line 11957) | function getValueEncoding (db) {
  function remover (line 11962) | function remover (array, item) {
  function each (line 11994) | function each (e) {
  function callHooks (line 12018) | function callHooks (isBatch, b, opts, cb) {
  function DB (line 12110) | function DB () {}
  function safeRange (line 12155) | function safeRange(fun) {
  function assertEncoding (line 12228) | function assertEncoding(encoding) {
  function passThroughWrite (line 12404) | function passThroughWrite(buffer) {
  function utf16DetectIncompleteChar (line 12408) | function utf16DetectIncompleteChar(buffer) {
  function base64DetectIncompleteChar (line 12413) | function base64DetectIncompleteChar(buffer) {
  function ReadableState$3 (line 12484) | function ReadableState$3(options, stream) {
  function Readable$4 (line 12552) | function Readable$4(options) {
  function readableAddChunk$3 (line 12589) | function readableAddChunk$3(stream, state, chunk, encoding, addToFront) {
  function needMoreData$3 (line 12645) | function needMoreData$3(state) {
  function roundUpToNextPowerOf2$3 (line 12663) | function roundUpToNextPowerOf2$3(n) {
  function howMuchToRead$3 (line 12675) | function howMuchToRead$3(n, state) {
  function chunkInvalid$3 (line 12828) | function chunkInvalid$3(state, chunk) {
  function onEofChunk$3 (line 12840) | function onEofChunk$3(stream, state) {
  function emitReadable$3 (line 12857) | function emitReadable$3(stream) {
  function emitReadable_$3 (line 12872) | function emitReadable_$3(stream) {
  function maybeReadMore$3 (line 12885) | function maybeReadMore$3(stream, state) {
  function maybeReadMore_$3 (line 12894) | function maybeReadMore_$3(stream, state) {
  function onunpipe (line 12946) | function onunpipe(readable) {
  function onend (line 12953) | function onend() {
  function cleanup (line 12965) | function cleanup() {
  function ondata (line 12988) | function ondata(chunk) {
  function onerror (line 13001) | function onerror(er) {
  function onclose (line 13020) | function onclose() {
  function onfinish (line 13025) | function onfinish() {
  function unpipe (line 13032) | function unpipe() {
  function pipeOnDrain$3 (line 13049) | function pipeOnDrain$3(src) {
  function resume (line 13167) | function resume(stream, state) {
  function resume_ (line 13176) | function resume_(stream, state) {
  function flow$3 (line 13194) | function flow$3(stream) {
  function fromList$3 (line 13273) | function fromList$3(n, state) {
  function endReadable$3 (line 13337) | function endReadable$3(stream) {
  function forEach$6 (line 13358) | function forEach$6 (xs, f) {
  function indexOf$3 (line 13364) | function indexOf$3 (xs, x) {
  function Duplex$3 (line 13423) | function Duplex$3(options) {
  function onend$3 (line 13444) | function onend$3() {
  function forEach$7 (line 13455) | function forEach$7 (xs, f) {
  function WriteReq$3 (line 13504) | function WriteReq$3(chunk, encoding, cb) {
  function WritableState$3 (line 13510) | function WritableState$3(options, stream) {
  function Writable$3 (line 13598) | function Writable$3(options) {
  function writeAfterEnd$3 (line 13620) | function writeAfterEnd$3(stream, state, cb) {
  function validChunk$3 (line 13634) | function validChunk$3(stream, state, chunk, cb) {
  function decodeChunk$3 (line 13698) | function decodeChunk$3(state, chunk, encoding) {
  function writeOrBuffer$3 (line 13710) | function writeOrBuffer$3(stream, state, chunk, encoding, cb) {
  function doWrite$3 (line 13731) | function doWrite$3(stream, state, writev, len, chunk, encoding, cb) {
  function onwriteError$3 (line 13743) | function onwriteError$3(stream, state, sync, er, cb) {
  function onwriteStateUpdate$3 (line 13758) | function onwriteStateUpdate$3(state) {
  function onwrite$3 (line 13765) | function onwrite$3(stream, er) {
  function afterWrite$3 (line 13795) | function afterWrite$3(stream, state, finished, cb) {
  function onwriteDrain$3 (line 13806) | function onwriteDrain$3(stream, state) {
  function clearBuffer$3 (line 13815) | function clearBuffer$3(stream, state) {
  function needFinish$3 (line 13900) | function needFinish$3(stream, state) {
  function prefinish (line 13907) | function prefinish(stream, state) {
  function finishMaybe$3 (line 13914) | function finishMaybe$3(stream, state) {
  function endWritable$3 (line 13927) | function endWritable$3(stream, state, cb) {
  function TransformState$3 (line 14017) | function TransformState$3(options, stream) {
  function afterTransform$3 (line 14028) | function afterTransform$3(stream, er, data) {
  function Transform$3 (line 14054) | function Transform$3(options) {
  function done$3 (line 14133) | function done$3(stream, er) {
  function PassThrough$3 (line 14187) | function PassThrough$3(options) {
  function once (line 14241) | function once(emitter, events, listener) {
  function peek (line 14259) | function peek (db, opts, cb) {
  function first (line 14273) | function first (db, opts, cb) {
  function last (line 14286) | function last (db, opts, cb) {
  function wrappy (line 14318) | function wrappy (fn, cb) {
  function once (line 14365) | function once (fn) {
  function onceStrict (line 14375) | function onceStrict (fn) {
  function nextTick (line 14804) | function nextTick(fn, arg1, arg2, arg3) {
  function copyProps (line 14854) | function copyProps (src, dst) {
  function SafeBuffer (line 14867) | function SafeBuffer (arg, encodingOrOffset, length) {
  function _classCallCheck (line 14916) | function _classCallCheck(instance, Constructor) { if (!(instance instanc...
  function copyBuffer (line 14921) | function copyBuffer(src, target, offset) {
  function BufferList (line 14926) | function BufferList() {
  function destroy$1 (line 15001) | function destroy$1(err, cb) {
  function undestroy (line 15042) | function undestroy() {
  function emitErrorNT (line 15059) | function emitErrorNT(self, err) {
  function deprecate (line 15092) | function deprecate (fn, msg) {
  function config (line 15123) | function config (name) {
  function CorkedRequest (line 15144) | function CorkedRequest(state) {
  function _uint8ArrayToBuffer (line 15184) | function _uint8ArrayToBuffer(chunk) {
  function _isUint8Array (line 15187) | function _isUint8Array(obj) {
  function nop (line 15197) | function nop() {}
  function WritableState$4 (line 15199) | function WritableState$4(options, stream) {
  function Writable$4 (line 15349) | function Writable$4(options) {
  function writeAfterEnd$4 (line 15386) | function writeAfterEnd$4(stream, cb) {
  function validChunk$4 (line 15396) | function validChunk$4(stream, state, chunk, cb) {
  function decodeChunk$4 (line 15463) | function decodeChunk$4(state, chunk, encoding) {
  function writeOrBuffer$4 (line 15483) | function writeOrBuffer$4(stream, state, isBuf, chunk, encoding, cb) {
  function doWrite$4 (line 15522) | function doWrite$4(stream, state, writev, len, chunk, encoding, cb) {
  function onwriteError$4 (line 15531) | function onwriteError$4(stream, state, sync, er, cb) {
  function onwriteStateUpdate$4 (line 15555) | function onwriteStateUpdate$4(state) {
  function onwrite$4 (line 15562) | function onwrite$4(stream, er) {
  function afterWrite$4 (line 15587) | function afterWrite$4(stream, state, finished, cb) {
  function onwriteDrain$4 (line 15597) | function onwriteDrain$4(stream, state) {
  function clearBuffer$4 (line 15605) | function clearBuffer$4(stream, state) {
  function needFinish$4 (line 15696) | function needFinish$4(state) {
  function callFinal (line 15699) | function callFinal(stream, state) {
  function prefinish$1 (line 15710) | function prefinish$1(stream, state) {
  function finishMaybe$4 (line 15723) | function finishMaybe$4(stream, state) {
  function endWritable$4 (line 15735) | function endWritable$4(stream, state, cb) {
  function onCorkedFinish (line 15745) | function onCorkedFinish(corkReq, state, err) {
  function Duplex$5 (line 15823) | function Duplex$5(options) {
  function onend$4 (line 15850) | function onend$4() {
  function onEndNT (line 15860) | function onEndNT(self) {
  function _normalizeEncoding (line 15907) | function _normalizeEncoding(enc) {
  function normalizeEncoding (line 15936) | function normalizeEncoding(enc) {
  function StringDecoder$4 (line 15946) | function StringDecoder$4(encoding) {
  function utf8CheckByte (line 16007) | function utf8CheckByte(byte) {
  function utf8CheckIncomplete (line 16015) | function utf8CheckIncomplete(self, buf, i) {
  function utf8CheckExtraBytes (line 16048) | function utf8CheckExtraBytes(self, buf, p) {
  function utf8FillLast (line 16068) | function utf8FillLast(buf) {
  function utf8Text (line 16083) | function utf8Text(buf, i) {
  function utf8End (line 16094) | function utf8End(buf) {
  function utf16Text (line 16104) | function utf16Text(buf, i) {
  function utf16End (line 16127) | function utf16End(buf) {
  function base64Text (line 16136) | function base64Text(buf, i) {
  function base64End (line 16150) | function base64End(buf) {
  function simpleWrite (line 16157) | function simpleWrite(buf) {
  function simpleEnd (line 16161) | function simpleEnd(buf) {
  function _uint8ArrayToBuffer$1 (line 16202) | function _uint8ArrayToBuffer$1(chunk) {
  function _isUint8Array$1 (line 16205) | function _isUint8Array$1(obj) {
  function prependListener (line 16234) | function prependListener(emitter, event, fn) {
  function ReadableState$4 (line 16246) | function ReadableState$4(options, stream) {
  function Readable$5 (line 16323) | function Readable$5(options) {
  function readableAddChunk$4 (line 16398) | function readableAddChunk$4(stream, chunk, encoding, addToFront, skipChu...
  function addChunk (line 16434) | function addChunk(stream, state, chunk, addToFront) {
  function chunkInvalid$4 (line 16448) | function chunkInvalid$4(state, chunk) {
  function needMoreData$4 (line 16463) | function needMoreData$4(state) {
  function computeNewHighWaterMark (line 16481) | function computeNewHighWaterMark(n) {
  function howMuchToRead$4 (line 16500) | function howMuchToRead$4(n, state) {
  function onEofChunk$4 (line 16619) | function onEofChunk$4(stream, state) {
  function emitReadable$4 (line 16637) | function emitReadable$4(stream) {
  function emitReadable_$4 (line 16647) | function emitReadable_$4(stream) {
  function maybeReadMore$4 (line 16659) | function maybeReadMore$4(stream, state) {
  function maybeReadMore_$4 (line 16666) | function maybeReadMore_$4(stream, state) {
  function onunpipe (line 16710) | function onunpipe(readable, unpipeInfo) {
  function onend (line 16720) | function onend() {
  function cleanup (line 16733) | function cleanup() {
  function ondata (line 16761) | function ondata(chunk) {
  function onerror (line 16781) | function onerror(er) {
  function onclose (line 16792) | function onclose() {
  function onfinish (line 16797) | function onfinish() {
  function unpipe (line 16804) | function unpipe() {
  function pipeOnDrain$4 (line 16821) | function pipeOnDrain$4(src) {
  function nReadingNextTick (line 16908) | function nReadingNextTick(self) {
  function resume$1 (line 16925) | function resume$1(stream, state) {
  function resume_$1 (line 16932) | function resume_$1(stream, state) {
  function flow$4 (line 16955) | function flow$4(stream) {
  function fromList$4 (line 17041) | function fromList$4(n, state) {
  function fromListPartial (line 17061) | function fromListPartial(n, list, hasStrings) {
  function copyFromBufferString (line 17081) | function copyFromBufferString(n, list) {
  function copyFromBuffer (line 17110) | function copyFromBuffer(n, list) {
  function endReadable$4 (line 17137) | function endReadable$4(stream) {
  function endReadableNT (line 17150) | function endReadableNT(state, stream) {
  function indexOf$4 (line 17159) | function indexOf$4(xs, x) {
  function afterTransform$4 (line 17177) | function afterTransform$4(er, data) {
  function Transform$4 (line 17202) | function Transform$4(options) {
  function prefinish$2 (line 17234) | function prefinish$2() {
  function done$4 (line 17301) | function done$4(stream, er, data) {
  function PassThrough$4 (line 17327) | function PassThrough$4(options) {
  function isArrayBuffer (line 17361) | function isArrayBuffer (input) {
  function fromArrayBuffer (line 17365) | function fromArrayBuffer (obj, byteOffset, length) {
  function fromString (line 17389) | function fromString (string, encoding) {
  function bufferFrom (line 17403) | function bufferFrom (value, encodingOrOffset, length) {
  function configureProperties (line 17457) | function configureProperties(obj) {
  function makeArrayAccessors (line 17508) | function makeArrayAccessors(obj) {
  function as_signed (line 17532) | function as_signed(value, bits) { var s = 32 - bits; return (value << s)...
  function as_unsigned (line 17533) | function as_unsigned(value, bits) { var s = 32 - bits; return (value << ...
  function packI8 (line 17535) | function packI8(n) { return [n & 0xff]; }
  function unpackI8 (line 17536) | function unpackI8(bytes) { return as_signed(bytes[0], 8); }
  function packU8 (line 17538) | function packU8(n) { return [n & 0xff]; }
  function unpackU8 (line 17539) | function unpackU8(bytes) { return as_unsigned(bytes[0], 8); }
  function packU8Clamped (line 17541) | function packU8Clamped(n) { n = round(Number(n)); return [n < 0 ? 0 : n ...
  function packI16 (line 17543) | function packI16(n) { return [(n >> 8) & 0xff, n & 0xff]; }
  function unpackI16 (line 17544) | function unpackI16(bytes) { return as_signed(bytes[0] << 8 | bytes[1], 1...
  function packU16 (line 17546) | function packU16(n) { return [(n >> 8) & 0xff, n & 0xff]; }
  function unpackU16 (line 17547) | function unpackU16(bytes) { return as_unsigned(bytes[0] << 8 | bytes[1],...
  function packI32 (line 17549) | function packI32(n) { return [(n >> 24) & 0xff, (n >> 16) & 0xff, (n >> ...
  function unpackI32 (line 17550) | function unpackI32(bytes) { return as_signed(bytes[0] << 24 | bytes[1] <...
  function packU32 (line 17552) | function packU32(n) { return [(n >> 24) & 0xff, (n >> 16) & 0xff, (n >> ...
  function unpackU32 (line 17553) | function unpackU32(bytes) { return as_unsigned(bytes[0] << 24 | bytes[1]...
  function packIEEE754 (line 17555) | function packIEEE754(v, ebits, fbits) {
  function unpackIEEE754 (line 17622) | function unpackIEEE754(bytes, ebits, fbits) {
  function unpackF64 (line 17657) | function unpackF64(b) { return unpackIEEE754(b, 11, 52); }
  function packF64 (line 17658) | function packF64(v) { return packIEEE754(v, 11, 52); }
  function unpackF32 (line 17659) | function unpackF32(b) { return unpackIEEE754(b, 8, 23); }
  function packF32 (line 17660) | function packF32(v) { return packIEEE754(v, 8, 23); }
  function makeConstructor (line 17704) | function makeConstructor(bytesPerElement, pack, unpack) {
  function r (line 17939) | function r(array, index) {
  function makeGetter (line 17980) | function makeGetter(arrayType) {
  function makeSetter (line 18013) | function makeSetter(arrayType) {
  function ConcatStream (line 18076) | function ConcatStream(opts, cb) {
  function isArrayish (line 18134) | function isArrayish (arr) {
  function isBufferish (line 18138) | function isBufferish (p) {
  function stringConcat (line 18142) | function stringConcat (parts) {
  function bufferConcat (line 18165) | function bufferConcat (parts) {
  function arrayConcat (line 18180) | function arrayConcat (parts) {
  function u8Concat (line 18188) | function u8Concat (parts) {
  function hasKeys$2 (line 18260) | function hasKeys$2(source) {
  function extend$4 (line 18268) | function extend$4() {

FILE: polyfills/buffer-es6.js
  function init (line 5) | function init () {
  function toByteArray (line 17) | function toByteArray (b64) {
  function tripletToBase64 (line 62) | function tripletToBase64 (num) {
  function encodeChunk (line 66) | function encodeChunk (uint8, start, end) {
  function fromByteArray (line 76) | function fromByteArray (uint8) {
  function read (line 111) | function read (buffer, offset, isLE, mLen, nBytes) {
  function write (line 144) | function write (buffer, value, offset, isLE, mLen, nBytes) {
  function kMaxLength (line 244) | function kMaxLength () {
  function createBuffer (line 250) | function createBuffer (that, length) {
  function Buffer (line 279) | function Buffer (arg, encodingOrOffset, length) {
  function from (line 304) | function from (that, value, encodingOrOffset, length) {
  function assertSize (line 337) | function assertSize (size) {
  function alloc (line 345) | function alloc (that, size, fill, encoding) {
  function allocUnsafe (line 369) | function allocUnsafe (that, size) {
  function fromString (line 393) | function fromString (that, string, encoding) {
  function fromArrayLike (line 417) | function fromArrayLike (that, array) {
  function fromArrayBuffer (line 426) | function fromArrayBuffer (that, array, byteOffset, length) {
  function fromObject (line 456) | function fromObject (that, obj) {
  function checked (line 486) | function checked (length) {
  function SlowBuffer (line 496) | function SlowBuffer (length) {
  function internalIsBuffer (line 503) | function internalIsBuffer (b) {
  function byteLength (line 579) | function byteLength (string, encoding) {
  function slowToString (line 624) | function slowToString (encoding, start, end) {
  function swap (line 698) | function swap (b, n, m) {
  function bidirectionalIndexOf (line 832) | function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
  function arrayIndexOf (line 889) | function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
  function hexWrite (line 957) | function hexWrite (buf, string, offset, length) {
  function utf8Write (line 984) | function utf8Write (buf, string, offset, length) {
  function asciiWrite (line 988) | function asciiWrite (buf, string, offset, length) {
  function latin1Write (line 992) | function latin1Write (buf, string, offset, length) {
  function base64Write (line 996) | function base64Write (buf, string, offset, length) {
  function ucs2Write (line 1000) | function ucs2Write (buf, string, offset, length) {
  function base64Slice (line 1083) | function base64Slice (buf, start, end) {
  function utf8Slice (line 1091) | function utf8Slice (buf, start, end) {
  function decodeCodePointsArray (line 1169) | function decodeCodePointsArray (codePoints) {
  function asciiSlice (line 1187) | function asciiSlice (buf, start, end) {
  function latin1Slice (line 1197) | function latin1Slice (buf, start, end) {
  function hexSlice (line 1207) | function hexSlice (buf, start, end) {
  function utf16leSlice (line 1220) | function utf16leSlice (buf, start, end) {
  function checkOffset (line 1268) | function checkOffset (offset, ext, length) {
  function checkInt (line 1429) | function checkInt (buf, value, offset, ext, max, min) {
  function objectWriteUInt16 (line 1482) | function objectWriteUInt16 (buf, value, offset, littleEndian) {
  function objectWriteUInt32 (line 1516) | function objectWriteUInt32 (buf, value, offset, littleEndian) {
  function checkIEEE754 (line 1666) | function checkIEEE754 (buf, value, offset, ext, max, min) {
  function writeFloat (line 1671) | function writeFloat (buf, value, offset, littleEndian, noAssert) {
  function writeDouble (line 1687) | function writeDouble (buf, value, offset, littleEndian, noAssert) {
  function base64clean (line 1820) | function base64clean (str) {
  function stringtrim (line 1832) | function stringtrim (str) {
  function toHex (line 1837) | function toHex (n) {
  function utf8ToBytes (line 1842) | function utf8ToBytes (string, units) {
  function asciiToBytes (line 1922) | function asciiToBytes (str) {
  function utf16leToBytes (line 1931) | function utf16leToBytes (str, units) {
  function base64ToBytes (line 1948) | function base64ToBytes (str) {
  function blitBuffer (line 1952) | function blitBuffer (src, dst, offset, length) {
  function isnan (line 1960) | function isnan (val) {
  function isBuffer (line 1968) | function isBuffer(obj) {
  function isFastBuffer (line 1972) | function isFastBuffer (obj) {
  function isSlowBuffer (line 1977) | function isSlowBuffer (obj) {

FILE: polyfills/console.js
  function noop (line 1) | function noop(){}

FILE: polyfills/crypto-browserify.js
  function createCommonjsModule (line 9) | function createCommonjsModule(fn, module) {
  function getCjsExportFromNamespace (line 13) | function getCjsExportFromNamespace (n) {
  function copyProps (line 23) | function copyProps (src, dst) {
  function SafeBuffer (line 36) | function SafeBuffer (arg, encodingOrOffset, length) {
  function oldBrowser (line 93) | function oldBrowser () {
  function randomBytes (line 106) | function randomBytes (size, cb) {
  function throwIfNotStringOrBuffer (line 165) | function throwIfNotStringOrBuffer (val, prefix) {
  function HashBase (line 171) | function HashBase (blockSize) {
  function MD5 (line 260) | function MD5 () {
  function rotl (line 378) | function rotl (x, n) {
  function fnF (line 382) | function fnF (a, b, c, d, m, k, s) {
  function fnG (line 386) | function fnG (a, b, c, d, m, k, s) {
  function fnH (line 390) | function fnH (a, b, c, d, m, k, s) {
  function fnI (line 394) | function fnI (a, b, c, d, m, k, s) {
  function RIPEMD160 (line 441) | function RIPEMD160 () {
  function rotl$1 (line 537) | function rotl$1 (x, n) {
  function fn1 (line 541) | function fn1 (a, b, c, d, e, m, k, s) {
  function fn2 (line 545) | function fn2 (a, b, c, d, e, m, k, s) {
  function fn3 (line 549) | function fn3 (a, b, c, d, e, m, k, s) {
  function fn4 (line 553) | function fn4 (a, b, c, d, e, m, k, s) {
  function fn5 (line 557) | function fn5 (a, b, c, d, e, m, k, s) {
  function Hash (line 566) | function Hash (blockSize, finalSize) {
  function Sha (line 663) | function Sha () {
  function rotl5 (line 682) | function rotl5 (num) {
  function rotl30 (line 686) | function rotl30 (num) {
  function ft (line 690) | function ft (s, b, c, d) {
  function Sha1 (line 759) | function Sha1 () {
  function rotl1 (line 778) | function rotl1 (num) {
  function rotl5$1 (line 782) | function rotl5$1 (num) {
  function rotl30$1 (line 786) | function rotl30$1 (num) {
  function ft$1 (line 790) | function ft$1 (s, b, c, d) {
  function Sha256 (line 873) | function Sha256 () {
  function ch (line 896) | function ch (x, y, z) {
  function maj (line 900) | function maj (x, y, z) {
  function sigma0 (line 904) | function sigma0 (x) {
  function sigma1 (line 908) | function sigma1 (x) {
  function gamma0 (line 912) | function gamma0 (x) {
  function gamma1 (line 916) | function gamma1 (x) {
  function Sha224 (line 991) | function Sha224 () {
  function Sha512 (line 1077) | function Sha512 () {
  function Ch (line 1108) | function Ch (x, y, z) {
  function maj$1 (line 1112) | function maj$1 (x, y, z) {
  function sigma0$1 (line 1116) | function sigma0$1 (x, xl) {
  function sigma1$1 (line 1120) | function sigma1$1 (x, xl) {
  function Gamma0 (line 1124) | function Gamma0 (x, xl) {
  function Gamma0l (line 1128) | function Gamma0l (x, xl) {
  function Gamma1 (line 1132) | function Gamma1 (x, xl) {
  function Gamma1l (line 1136) | function Gamma1l (x, xl) {
  function getCarry (line 1140) | function getCarry (a, b) {
  function writeInt64BE (line 1270) | function writeInt64BE (h, l, offset) {
  function Sha384 (line 1293) | function Sha384 () {
  function writeInt64BE (line 1327) | function writeInt64BE (h, l, offset) {
  function CipherBase (line 1367) | function CipherBase (hashMode) {
  function Hash$1 (line 1462) | function Hash$1 (hash) {
  function Hmac (line 1493) | function Hmac (alg, key) {
  function Hmac$1 (line 1543) | function Hmac$1 (alg, key) {
  function checkBuffer (line 1779) | function checkBuffer (buf, name) {
  function Hmac$2 (line 1830) | function Hmac$2 (alg, key, saltLen) {
  function getDigest (line 1865) | function getDigest (alg) {
  function pbkdf2 (line 1878) | function pbkdf2 (password, salt, iterations, keylen, digest) {
  function checkNative (line 1932) | function checkNative (algo) {
  function browserPbkdf2 (line 1953) | function browserPbkdf2 (password, salt, iterations, length, algo) {
  function resolvePromise (line 1970) | function resolvePromise (promise, callback) {
  function assert (line 2293) | function assert(val, msg) {
  function Cipher (line 2303) | function Cipher(options) {
  function DESState (line 2444) | function DESState() {
  function DES (line 2449) | function DES(options) {
  function CBCState (line 2581) | function CBCState(iv) {
  function instantiate (line 2589) | function instantiate(Base) {
  function EDEState (line 2647) | function EDEState(type, key) {
  function EDE (line 2669) | function EDE(options) {
  function DES$3 (line 2722) | function DES$3 (opts) {
  function encryptStart (line 2804) | function encryptStart (self, data, decrypt) {
  function encryptByte (line 2841) | function encryptByte (self, byteParam, decrypt) {
  function encryptByte$1 (line 2871) | function encryptByte$1 (self, byteParam, decrypt) {
  function shiftIn (line 2887) | function shiftIn (buffer, value) {
  function getBlock (line 2916) | function getBlock (self) {
  function incr32 (line 2935) | function incr32 (iv) {
  function getBlock$1 (line 2954) | function getBlock$1 (self) {
  function asUInt32Array (line 3215) | function asUInt32Array (buf) {
  function scrubVec (line 3228) | function scrubVec (v) {
  function cryptBlock (line 3234) | function cryptBlock (M, keySchedule, SUB_MIX, SBOX, nRounds) {
  function AES (line 3333) | function AES (key) {
  function toArray (line 3444) | function toArray (buf) {
  function fromArray (line 3453) | function fromArray (out) {
  function GHASH (line 3462) | function GHASH (key) {
  function xorTest (line 3538) | function xorTest (a, b) {
  function calcIv (line 3550) | function calcIv (self, iv, ck) {
  function StreamCipher (line 3573) | function StreamCipher (mode, key, iv, decrypt) {
  function StreamCipher$1 (line 3652) | function StreamCipher$1 (mode, key, iv, decrypt) {
  function EVP_BytesToKey (line 3679) | function EVP_BytesToKey (password, salt, keyBits, ivLen) {
  function Cipher$4 (line 3728) | function Cipher$4 (mode, key, iv) {
  function Splitter (line 3775) | function Splitter () {
  function createCipheriv (line 3804) | function createCipheriv (suite, password, iv) {
  function createCipher (line 3823) | function createCipher (suite, password) {
  function Decipher (line 3847) | function Decipher (mode, key, iv) {
  function Splitter$1 (line 3886) | function Splitter$1 () {
  function unpad (line 3917) | function unpad (last) {
  function createDecipheriv (line 3933) | function createDecipheriv (suite, password, iv) {
  function createDecipher (line 3952) | function createDecipher (suite, password) {
  function getCiphers (line 3969) | function getCiphers () {
  function createCipher (line 4020) | function createCipher (suite, password) {
  function createDecipher (line 4038) | function createDecipher (suite, password) {
  function createCipheriv (line 4056) | function createCipheriv (suite, key, iv) {
  function createDecipheriv (line 4064) | function createDecipheriv (suite, key, iv) {
  function getCiphers (line 4072) | function getCiphers () {
  function assert (line 4097) | function assert (val, msg) {
  function inherits (line 4103) | function inherits (ctor, superCtor) {
  function BN (line 4113) | function BN (number, base, endian) {
  function parseHex (line 4278) | function parseHex (str, start, end) {
  function parseBase (line 4332) | function parseBase (str, start, end, mul) {
  function toBitArray (line 4719) | function toBitArray (num) {
  function smallMulTo (line 5084) | function smallMulTo (self, num, out) {
  function bigMulTo (line 5706) | function bigMulTo (self, num, out) {
  function jumboMulTo (line 5747) | function jumboMulTo (self, num, out) {
  function FFTM (line 5771) | function FFTM (x, y) {
  function MPrime (line 7029) | function MPrime (name, p) {
  function K256 (line 7079) | function K256 () {
  function P224 (line 7146) | function P224 () {
  function P192 (line 7154) | function P192 () {
  function P25519 (line 7162) | function P25519 () {
  function Red (line 7213) | function Red (m) {
  function Mont (line 7447) | function Mont (m) {
  function Rand (line 7529) | function Rand(rand) {
  function MillerRabin (line 7587) | function MillerRabin(rand) {
  function _getPrimes (line 7720) | function _getPrimes() {
  function simpleSieve (line 7742) | function simpleSieve(p) {
  function fermatTest (line 7757) | function fermatTest(p) {
  function findPrime (line 7762) | function findPrime(bits, gen) {
  function setPublicKey (line 7870) | function setPublicKey(pub, enc) {
  function setPrivateKey (line 7879) | function setPrivateKey(priv, enc) {
  function checkPrime (line 7889) | function checkPrime(prime, generator) {
  function DH (line 7942) | function DH(prime, generator, malleable) {
  function formatReturnValue (line 8014) | function formatReturnValue(bn, enc) {
  function getDiffieHellman (line 8026) | function getDiffieHellman (mod) {
  function createDiffieHellman (line 8037) | function createDiffieHellman (prime, enc, generator, genc) {
  function blind (line 8071) | function blind(priv) {
  function crt (line 8080) | function crt(msg, priv) {
  function getr (line 8100) | function getr(priv) {
  function toArray (line 8213) | function toArray(msg, enc) {
  function zero2 (line 8245) | function zero2(word) {
  function toHex (line 8253) | function toHex(msg) {
  function getNAF (line 8283) | function getNAF(num, w) {
  function getJSF (line 8313) | function getJSF(k1, k2) {
  function cachedProperty (line 8369) | function cachedProperty(obj, name, computer) {
  function parseBytes (line 8378) | function parseBytes(bytes) {
  function intFromLE (line 8384) | function intFromLE(bytes) {
  function BaseCurve (line 8395) | function BaseCurve(type, conf) {
  function BasePoint (line 8634) | function BasePoint(curve, type) {
  function ShortCurve (line 8766) | function ShortCurve(conf) {
  function Point (line 9007) | function Point(curve, x, y, isRed) {
  function obj2point (line 9091) | function obj2point(obj) {
  function JPoint (line 9245) | function JPoint(curve, x, y, z) {
  function MontCurve (line 9699) | function MontCurve(conf) {
  function Point$1 (line 9720) | function Point$1(curve, x, z) {
  function EdwardsCurve (line 9874) | function EdwardsCurve(conf) {
  function Point$2 (line 9978) | function Point$2(curve, x, y, z, t) {
  function isSurrogatePair (line 10310) | function isSurrogatePair(msg, i) {
  function toArray$1 (line 10320) | function toArray$1(msg, enc) {
  function toHex (line 10367) | function toHex(msg) {
  function htonl (line 10375) | function htonl(w) {
  function toHex32 (line 10384) | function toHex32(msg, endian) {
  function zero2 (line 10396) | function zero2(word) {
  function zero8 (line 10404) | function zero8(word) {
  function join32 (line 10424) | function join32(msg, start, end, endian) {
  function split32 (line 10440) | function split32(msg, endian) {
  function rotr32 (line 10460) | function rotr32(w, b) {
  function rotl32 (line 10465) | function rotl32(w, b) {
  function sum32 (line 10470) | function sum32(a, b) {
  function sum32_3 (line 10475) | function sum32_3(a, b, c) {
  function sum32_4 (line 10480) | function sum32_4(a, b, c, d) {
  function sum32_5 (line 10485) | function sum32_5(a, b, c, d, e) {
  function sum64 (line 10490) | function sum64(buf, pos, ah, al) {
  function sum64_hi (line 10501) | function sum64_hi(ah, al, bh, bl) {
  function sum64_lo (line 10508) | function sum64_lo(ah, al, bh, bl) {
  function sum64_4_hi (line 10514) | function sum64_4_hi(ah, al, bh, bl, ch, cl, dh, dl) {
  function sum64_4_lo (line 10529) | function sum64_4_lo(ah, al, bh, bl, ch, cl, dh, dl) {
  function sum64_5_hi (line 10535) | function sum64_5_hi(ah, al, bh, bl, ch, cl, dh, dl, eh, el) {
  function sum64_5_lo (line 10552) | function sum64_5_lo(ah, al, bh, bl, ch, cl, dh, dl, eh, el) {
  function rotr64_hi (line 10559) | function rotr64_hi(ah, al, num) {
  function rotr64_lo (line 10565) | function rotr64_lo(ah, al, num) {
  function shr64_hi (line 10571) | function shr64_hi(ah, al, num) {
  function shr64_lo (line 10576) | function shr64_lo(ah, al, num) {
  function BlockHash (line 10611) | function BlockHash() {
  function ft_1 (line 10705) | function ft_1(s, x, y, z) {
  function ch32 (line 10715) | function ch32(x, y, z) {
  function maj32 (line 10720) | function maj32(x, y, z) {
  function p32 (line 10725) | function p32(x, y, z) {
  function s0_256 (line 10730) | function s0_256(x) {
  function s1_256 (line 10735) | function s1_256(x) {
  function g0_256 (line 10740) | function g0_256(x) {
  function g1_256 (line 10745) | function g1_256(x) {
  function SHA1 (line 10772) | function SHA1() {
  function SHA256 (line 10861) | function SHA256() {
  function SHA224 (line 10929) | function SHA224() {
  function SHA512 (line 11011) | function SHA512() {
  function ch64_hi (line 11163) | function ch64_hi(xh, xl, yh, yl, zh) {
  function ch64_lo (line 11170) | function ch64_lo(xh, xl, yh, yl, zh, zl) {
  function maj64_hi (line 11177) | function maj64_hi(xh, xl, yh, yl, zh) {
  function maj64_lo (line 11184) | function maj64_lo(xh, xl, yh, yl, zh, zl) {
  function s0_512_hi (line 11191) | function s0_512_hi(xh, xl) {
  function s0_512_lo (line 11202) | function s0_512_lo(xh, xl) {
  function s1_512_hi (line 11213) | function s1_512_hi(xh, xl) {
  function s1_512_lo (line 11224) | function s1_512_lo(xh, xl) {
  function g0_512_hi (line 11235) | function g0_512_hi(xh, xl) {
  function g0_512_lo (line 11246) | function g0_512_lo(xh, xl) {
  function g1_512_hi (line 11257) | function g1_512_hi(xh, xl) {
  function g1_512_lo (line 11268) | function g1_512_lo(xh, xl) {
  function SHA384 (line 11279) | function SHA384() {
  function RIPEMD160$1 (line 11329) | function RIPEMD160$1() {
  function f (line 11394) | function f(j, x, y, z) {
  function K$4 (line 11407) | function K$4(j) {
  function Kh (line 11420) | function Kh(j) {
  function Hmac$3 (line 11469) | function Hmac$3(hash, key, enc) {
  function PresetCurve (line 12320) | function PresetCurve(options) {
  function defineCurve (line 12336) | function defineCurve(name, options) {
  function HmacDRBG (line 12518) | function HmacDRBG(options) {
  function KeyPair (line 12629) | function KeyPair(ec, options) {
  function Signature (line 12745) | function Signature(options, enc) {
  function Position (line 12762) | function Position() {
  function getLength (line 12766) | function getLength(buf, p) {
  function rmPadding (line 12781) | function rmPadding(buf) {
  function constructLength (line 12831) | function constructLength(arr, len) {
  function EC (line 12879) | function EC(options) {
  function KeyPair$1 (line 13123) | function KeyPair$1(eddsa, params) {
  function Signature$1 (line 13216) | function Signature$1(eddsa, sig) {
  function EDDSA (line 13272) | function EDDSA(curve) {
  function Entity (line 13405) | function Entity(name, body) {
  function Reporter (line 13458) | function Reporter(options) {
  function ReporterError (line 13556) | function ReporterError(path, msg) {
  function DecoderBuffer (line 13584) | function DecoderBuffer(base, options) {
  function EncoderBuffer (line 13644) | function EncoderBuffer(value, reporter) {
  function Node (line 13731) | function Node(enc, parent) {
  function DERDecoder (line 14421) | function DERDecoder(entity) {
  function DERNode (line 14440) | function DERNode(parent) {
  function derDecodeTag (line 14671) | function derDecodeTag(buf, fail) {
  function derDecodeLen (line 14704) | function derDecodeLen(buf, primitive, fail) {
  function PEMDecoder (line 14740) | function PEMDecoder(entity) {
  function DEREncoder (line 14799) | function DEREncoder(entity) {
  function DERNode$1 (line 14815) | function DERNode$1(parent) {
  function two (line 14931) | function two(num) {
  function encodeTag (line 15059) | function encodeTag(tag, primitive, cls, reporter) {
  function PEMEncoder (line 15085) | function PEMEncoder(entity) {
  function parseKeys (line 15390) | function parseKeys (buffer) {
  function decrypt$2 (line 15475) | function decrypt$2 (data, password) {
  function sign (line 15513) | function sign (hash, key, hashType, signType, tag) {
  function ecSign (line 15537) | function ecSign (hash, priv) {
  function dsaSign (line 15548) | function dsaSign (hash, priv, algo) {
  function toDER (line 15570) | function toDER (r, s) {
  function getKey (line 15584) | function getKey (x, q, hash, algo) {
  function bits2int (line 15604) | function bits2int (obits, q) {
  function bits2octets (line 15611) | function bits2octets (bits, q) {
  function makeKey (line 15623) | function makeKey (q, kv, algo) {
  function makeR (line 15643) | function makeR (g, k, p, q) {
  function verify (line 15659) | function verify (sig, hash, key, signType, tag) {
  function ecVerify (line 15699) | function ecVerify (sig, hash, pub) {
  function dsaVerify (line 15709) | function dsaVerify (sig, hash, pub) {
  function checkValue (line 15730) | function checkValue (b, q) {
  function Sign (line 15742) | function Sign (algorithm) {
  function Verify (line 15775) | function Verify (algorithm) {
  function createSign (line 15807) | function createSign (algorithm) {
  function createVerify (line 15811) | function createVerify (algorithm) {
  function ECDH (line 15863) | function ECDH (curve) {
  function formatReturnValue$1 (line 15927) | function formatReturnValue$1 (bn, enc, len) {
  function i2ops (line 15957) | function i2ops (c) {
  function withPublic (line 15974) | function withPublic (paddedMsg, key) {
  function oaep (line 16016) | function oaep (key, msg) {
  function pkcs1 (line 16032) | function pkcs1 (key, msg, reverse) {
  function nonZero (line 16046) | function nonZero (len) {
  function oaep$1 (line 16101) | function oaep$1 (key, msg) {
  function pkcs1$1 (line 16125) | function pkcs1$1 (key, msg, reverse) {
  function compare (line 16148) | function compare (a, b) {
  function oldBrowser (line 16183) | function oldBrowser () {
  function assertOffset (line 16192) | function assertOffset (offset, length) {
  function assertSize (line 16206) | function assertSize (size, offset, length) {
  function randomFill (line 16226) | function randomFill (buf, offset, size, cb) {
  function actualFill (line 16246) | function actualFill (buf, offset, size, cb) {
  function randomFillSync (line 16273) | function randomFillSync (buf, offset, size) {

FILE: polyfills/domain.js
  function createEmitError (line 32) | function createEmitError(d) {
  function Domain (line 39) | function Domain() {
  function createDomain (line 91) | function createDomain() {

FILE: polyfills/events.js
  function EventHandlers (line 8) | function EventHandlers() {}
  function EventEmitter (line 11) | function EventEmitter() {
  function $getMaxListeners (line 57) | function $getMaxListeners(that) {
  function emitNone (line 72) | function emitNone(handler, isFn, self) {
  function emitOne (line 82) | function emitOne(handler, isFn, self, arg1) {
  function emitTwo (line 92) | function emitTwo(handler, isFn, self, arg1, arg2) {
  function emitThree (line 102) | function emitThree(handler, isFn, self, arg1, arg2, arg3) {
  function emitMany (line 113) | function emitMany(handler, isFn, self, args) {
  function _addListener (line 193) | function _addListener(target, type, listener, prepend) {
  function emitWarning (line 256) | function emitWarning(e) {
  function _onceWrap (line 270) | function _onceWrap(target, type, listener) {
  function listenerCount (line 435) | function listenerCount(type) {
  function spliceOne (line 456) | function spliceOne(list, index) {
  function arrayClone (line 462) | function arrayClone(arr, i) {
  function unwrapListeners (line 469) | function unwrapListeners(arr) {

FILE: polyfills/http-lib/capability.js
  function blobConstructor (line 4) | function blobConstructor() {
  function checkTypeSupport (line 18) | function checkTypeSupport(type) {
  function isFunction (line 48) | function isFunction(value) {

FILE: polyfills/http-lib/request.js
  function decideMode (line 7) | function decideMode(preferBinary, useFetch) {
  function ClientRequest (line 24) | function ClientRequest(opts) {
  function statusValid (line 216) | function statusValid(xhr) {

FILE: polyfills/http-lib/response.js
  function IncomingMessage (line 15) | function IncomingMessage(xhr, response, mode) {

FILE: polyfills/http.js
  function request (line 33) | function request(opts, cb) {
  function get (line 65) | function get(opts, cb) {
  function Agent (line 71) | function Agent() {}

FILE: polyfills/os.js
  function endianness (line 26) | function endianness() {
  function hostname (line 44) | function hostname() {
  function loadavg (line 50) | function loadavg() {
  function uptime (line 54) | function uptime() {
  function freemem (line 58) | function freemem() {
  function totalmem (line 62) | function totalmem() {
  function cpus (line 66) | function cpus() {
  function type (line 70) | function type() {
  function release (line 74) | function release () {
  function networkInterfaces (line 81) | function networkInterfaces(){}
  function getNetworkInterfaces (line 82) | function getNetworkInterfaces(){}
  function arch (line 84) | function arch() {
  function platform (line 88) | function platform() {
  function tmpDir (line 92) | function tmpDir() {

FILE: polyfills/path.js
  function normalizeArray (line 26) | function normalizeArray(parts, allowAboveRoot) {
  function resolve (line 62) | function resolve() {
  function normalize (line 93) | function normalize(path) {
  function isAbsolute (line 113) | function isAbsolute(path) {
  function join (line 118) | function join() {
  function relative (line 131) | function relative(from, to) {
  function dirname (line 175) | function dirname(path) {
  function basename (line 193) | function basename(path, ext) {
  function extname (line 203) | function extname(path) {
  function filter (line 218) | function filter (xs, f) {

FILE: polyfills/process-es6.js
  function defaultSetTimout (line 4) | function defaultSetTimout() {
  function defaultClearTimeout (line 7) | function defaultClearTimeout () {
  function runTimeout (line 19) | function runTimeout(fun) {
  function runClearTimeout (line 44) | function runClearTimeout(marker) {
  function cleanUpNextTick (line 76) | function cleanUpNextTick() {
  function drainQueue (line 91) | function drainQueue() {
  function nextTick (line 114) | function nextTick(fun) {
  function Item (line 127) | function Item(fun, array) {
  function noop (line 144) | function noop() {}
  function binding (line 154) | function binding(name) {
  function cwd (line 158) | function cwd () { return '/' }
  function chdir (line 159) | function chdir (dir) {
  function umask (line 161) | function umask() { return 0; }
  function hrtime (line 175) | function hrtime(previousTimestamp){
  function uptime (line 191) | function uptime() {

FILE: polyfills/punycode.js
  function error (line 42) | function error(type) {
  function map (line 54) | function map(array, fn) {
  function mapDomain (line 73) | function mapDomain(string, fn) {
  function ucs2decode (line 102) | function ucs2decode(string) {
  function ucs2encode (line 136) | function ucs2encode(array) {
  function basicToDigit (line 158) | function basicToDigit(codePoint) {
  function digitToBasic (line 182) | function digitToBasic(digit, flag) {
  function adapt (line 193) | function adapt(delta, numPoints, firstTime) {
  function decode (line 210) | function decode(input) {
  function encode (line 311) | function encode(input) {
  function toUnicode (line 429) | function toUnicode(input) {
  function toASCII (line 448) | function toASCII(input) {

FILE: polyfills/qs.js
  function hasOwnProperty (line 26) | function hasOwnProperty(obj, prop) {
  function stringifyPrimitive (line 32) | function stringifyPrimitive(v) {
  function stringify (line 48) | function stringify (obj, sep, eq, name) {
  function map (line 74) | function map (xs, f) {
  function parse (line 91) | function parse(qs, sep, eq, options) {

FILE: polyfills/readable-stream/buffer-list.js
  function BufferList (line 5) | function BufferList() {

FILE: polyfills/readable-stream/duplex.js
  function Duplex (line 16) | function Duplex(options) {
  function onend (line 33) | function onend() {
  function onEndNT (line 43) | function onEndNT(self) {

FILE: polyfills/readable-stream/passthrough.js
  function PassThrough (line 7) | function PassThrough(options) {

FILE: polyfills/readable-stream/readable.js
  function prependListener (line 15) | function prependListener(emitter, event, fn) {
  function listenerCount (line 33) | function listenerCount (emitter, type) {
  function ReadableState (line 36) | function ReadableState(options, stream) {
  function Readable (line 103) | function Readable(options) {
  function readableAddChunk (line 145) | function readableAddChunk(stream, state, chunk, encoding, addToFront) {
  function needMoreData (line 200) | function needMoreData(state) {
  function computeNewHighWaterMark (line 213) | function computeNewHighWaterMark(n) {
  function howMuchToRead (line 232) | function howMuchToRead(n, state) {
  function chunkInvalid (line 351) | function chunkInvalid(state, chunk) {
  function onEofChunk (line 359) | function onEofChunk(stream, state) {
  function emitReadable (line 377) | function emitReadable(stream) {
  function emitReadable_ (line 387) | function emitReadable_(stream) {
  function maybeReadMore (line 399) | function maybeReadMore(stream, state) {
  function maybeReadMore_ (line 406) | function maybeReadMore_(stream, state) {
  function onunpipe (line 450) | function onunpipe(readable) {
  function onend (line 457) | function onend() {
  function cleanup (line 470) | function cleanup() {
  function ondata (line 498) | function ondata(chunk) {
  function onerror (line 518) | function onerror(er) {
  function onclose (line 529) | function onclose() {
  function onfinish (line 534) | function onfinish() {
  function unpipe (line 541) | function unpipe() {
  function pipeOnDrain (line 558) | function pipeOnDrain(src) {
  function nReadingNextTick (line 644) | function nReadingNextTick(self) {
  function resume (line 661) | function resume(stream, state) {
  function resume_ (line 668) | function resume_(stream, state) {
  function flow (line 691) | function flow(stream) {
  function fromList (line 767) | function fromList(n, state) {
  function fromListPartial (line 787) | function fromListPartial(n, list, hasStrings) {
  function copyFromBufferString (line 807) | function copyFromBufferString(n, list) {
  function copyFromBuffer (line 836) | function copyFromBuffer(n, list) {
  function endReadable (line 863) | function endReadable(stream) {
  function endReadableNT (line 876) | function endReadableNT(state, stream) {
  function forEach (line 885) | function forEach(xs, f) {
  function indexOf (line 891) | function indexOf(xs, x) {

FILE: polyfills/readable-stream/transform.js
  function TransformState (line 50) | function TransformState(stream) {
  function afterTransform (line 62) | function afterTransform(stream, er, data) {
  function Transform (line 84) | function Transform(options) {
  function done (line 161) | function done(stream, er) {

FILE: polyfills/readable-stream/writable.js
  function nop (line 14) | function nop() {}
  function WriteReq (line 16) | function WriteReq(chunk, encoding, cb) {
  function WritableState (line 23) | function WritableState(options, stream) {
  function Writable (line 132) | function Writable(options) {
  function writeAfterEnd (line 157) | function writeAfterEnd(stream, cb) {
  function validChunk (line 169) | function validChunk(stream, state, chunk, cb) {
  function decodeChunk (line 233) | function decodeChunk(state, chunk, encoding) {
  function writeOrBuffer (line 243) | function writeOrBuffer(stream, state, chunk, encoding, cb) {
  function doWrite (line 271) | function doWrite(stream, state, writev, len, chunk, encoding, cb) {
  function onwriteError (line 280) | function onwriteError(stream, state, sync, er, cb) {
  function onwriteStateUpdate (line 288) | function onwriteStateUpdate(state) {
  function onwrite (line 295) | function onwrite(stream, er) {
  function afterWrite (line 320) | function afterWrite(stream, state, finished, cb) {
  function onwriteDrain (line 330) | function onwriteDrain(stream, state) {
  function clearBuffer (line 338) | function clearBuffer(stream, state) {
  function needFinish (line 425) | function needFinish(state) {
  function prefinish (line 429) | function prefinish(stream, state) {
  function finishMaybe (line 436) | function finishMaybe(stream, state) {
  function endWritable (line 450) | function endWritable(stream, state, cb) {
  function CorkedRequest (line 462) | function CorkedRequest(state) {

FILE: polyfills/setimmediate.js
  function setImmediate (line 13) | function setImmediate(callback) {
  function clearImmediate (line 30) | function clearImmediate(handle) {
  function run (line 34) | function run(task) {
  function runIfPresent (line 56) | function runIfPresent(handle) {
  function installNextTickImplementation (line 77) | function installNextTickImplementation() {
  function canUsePostMessage (line 83) | function canUsePostMessage() {
  function installPostMessageImplementation (line 98) | function installPostMessageImplementation() {
  function installMessageChannelImplementation (line 123) | function installMessageChannelImplementation() {
  function installReadyStateChangeImplementation (line 135) | function installReadyStateChangeImplementation() {
  function installSetTimeoutImplementation (line 151) | function installSetTimeoutImplementation() {

FILE: polyfills/stream.js
  function Stream (line 25) | function Stream() {
  function ondata (line 32) | function ondata(chunk) {
  function ondrain (line 42) | function ondrain() {
  function onend (line 58) | function onend() {
  function onclose (line 66) | function onclose() {
  function onerror (line 74) | function onerror(er) {
  function cleanup (line 85) | function cleanup() {

FILE: polyfills/string-decoder.js
  function assertEncoding (line 32) | function assertEncoding(encoding) {
  function StringDecoder (line 46) | function StringDecoder(encoding) {
  function passThroughWrite (line 208) | function passThroughWrite(buffer) {
  function utf16DetectIncompleteChar (line 212) | function utf16DetectIncompleteChar(buffer) {
  function base64DetectIncompleteChar (line 217) | function base64DetectIncompleteChar(buffer) {

FILE: polyfills/timers.js
  function clearInterval (line 8) | function clearInterval(timeout) {
  function clearTimeout (line 15) | function clearTimeout(timeout) {
  function clearFn (line 22) | function clearFn(timeout) {
  function setTimeout (line 27) | function setTimeout() {
  function setInterval (line 30) | function setInterval() {
  function Timeout (line 34) | function Timeout(id) {
  function enroll (line 43) | function enroll(item, msecs) {
  function unenroll (line 48) | function unenroll(item) {
  function active (line 53) | function active(item) {

FILE: polyfills/tty.js
  function isatty (line 4) | function isatty() {
  function ReadStream (line 8) | function ReadStream() {
  function WriteStream (line 12) | function WriteStream() {

FILE: polyfills/url.js
  function Url (line 39) | function Url() {
  function urlParse (line 106) | function urlParse(url, parseQueryString, slashesDenoteHost) {
  function parse (line 117) | function parse(self, url, parseQueryString, slashesDenoteHost) {
  function urlFormat (line 379) | function urlFormat(obj) {
  function format (line 388) | function format(self) {
  function urlResolve (line 448) | function urlResolve(source, relative) {
  function urlResolveObject (line 456) | function urlResolveObject(source, relative) {
  function parseHost (line 734) | function parseHost(self) {

FILE: polyfills/util.js
  function format (line 23) | function format(f) {
  function deprecate (line 65) | function deprecate(fn, msg) {
  function debuglog (line 98) | function debuglog(set) {
  function inspect (line 125) | function inspect(obj, opts) {
  function stylizeWithColor (line 181) | function stylizeWithColor(str, styleType) {
  function stylizeNoColor (line 193) | function stylizeNoColor(str, styleType) {
  function arrayToHash (line 198) | function arrayToHash(array) {
  function formatValue (line 209) | function formatValue(ctx, value, recurseTimes) {
  function formatPrimitive (line 322) | function formatPrimitive(ctx, value) {
  function formatError (line 341) | function formatError(value) {
  function formatArray (line 346) | function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
  function formatProperty (line 366) | function formatProperty(ctx, value, recurseTimes, visibleKeys, key, arra...
  function reduceToSingleString (line 425) | function reduceToSingleString(output, base, braces) {
  function isArray (line 448) | function isArray(ar) {
  function isBoolean (line 452) | function isBoolean(arg) {
  function isNull (line 456) | function isNull(arg) {
  function isNullOrUndefined (line 460) | function isNullOrUndefined(arg) {
  function isNumber (line 464) | function isNumber(arg) {
  function isString (line 468) | function isString(arg) {
  function isSymbol (line 472) | function isSymbol(arg) {
  function isUndefined (line 476) | function isUndefined(arg) {
  function isRegExp (line 480) | function isRegExp(re) {
  function isObject (line 484) | function isObject(arg) {
  function isDate (line 488) | function isDate(d) {
  function isError (line 492) | function isError(e) {
  function isFunction (line 497) | function isFunction(arg) {
  function isPrimitive (line 501) | function isPrimitive(arg) {
  function isBuffer (line 510) | function isBuffer(maybeBuf) {
  function objectToString (line 514) | function objectToString(o) {
  function pad (line 519) | function pad(n) {
  function timestamp (line 528) | function timestamp() {
  function log (line 538) | function log() {
  function _extend (line 559) | function _extend(origin, add) {
  function hasOwnProperty (line 571) | function hasOwnProperty(obj, prop) {

FILE: polyfills/vm.js
  function Object_keys (line 8) | function Object_keys(obj) {
  function forEach (line 17) | function forEach(xs, fn) {
  function defineProp (line 26) | function defineProp(obj, name, value) {
  function createDefineProp (line 33) | function createDefineProp() {
  function Context (line 58) | function Context() {}
  function Script (line 61) | function Script(code) {
  function otherRunInContext (line 65) | function otherRunInContext(code, context) {
  function createScript (line 147) | function createScript(code) {
  function createContext (line 151) | function createContext(context) {
  function runInContext (line 163) | function runInContext(code, contextifiedSandbox, options) {
  function runInThisContext (line 167) | function runInThisContext(code, options) {
  function isContext (line 171) | function isContext(context) {
  function runInNewContext (line 174) | function runInNewContext(code, sandbox, options) {
  function indexOf (line 196) | function indexOf(arr, obj){

FILE: polyfills/zlib-lib/adler32.js
  function adler32 (line 6) | function adler32(adler, buf, len, pos) {

FILE: polyfills/zlib-lib/binding.js
  function Zlib (line 59) | function Zlib(mode) {
  function bufferSet (line 163) | function bufferSet(data, offset) {

FILE: polyfills/zlib-lib/crc32.js
  function makeTable (line 8) | function makeTable() {
  function crc32 (line 26) | function crc32(crc, buf, len, pos) {

FILE: polyfills/zlib-lib/deflate.js
  function err (line 105) | function err(strm, errorCode) {
  function rank (line 110) | function rank(f) {
  function zero (line 114) | function zero(buf) {
  function flush_pending (line 128) | function flush_pending(strm) {
  function flush_block_only (line 152) | function flush_block_only(s, last) {
  function put_byte (line 159) | function put_byte(s, b) {
  function putShortMSB (line 169) | function putShortMSB(s, b) {
  function read_buf (line 184) | function read_buf(strm, buf, start, size) {
  function longest_match (line 220) | function longest_match(s, cur_match) {
  function fill_window (line 335) | function fill_window(s) {
  function deflate_stored (line 491) | function deflate_stored(s, flush) {
  function deflate_fast (line 589) | function deflate_fast(s, flush) {
  function deflate_slow (line 716) | function deflate_slow(s, flush) {
  function deflate_rle (line 880) | function deflate_rle(s, flush) {
  function deflate_huff (line 977) | function deflate_huff(s, flush) {
  function Config (line 1034) | function Config(good_length, max_lazy, nice_length, max_chain, func) {
  function lm_init (line 1063) | function lm_init(s) {
  function DeflateState (line 1086) | function DeflateState() {
  function deflateResetKeep (line 1275) | function deflateResetKeep(strm) {
  function deflateReset (line 1304) | function deflateReset(strm) {
  function deflateSetHeader (line 1313) | function deflateSetHeader(strm, head) {
  function deflateInit2 (line 1325) | function deflateInit2(strm, level, method, windowBits, memLevel, strateg...
  function deflateInit (line 1401) | function deflateInit(strm, level) {
  function deflate (line 1406) | function deflate(strm, flush) {
  function deflateEnd (line 1740) | function deflateEnd(strm) {
  function deflateSetDictionary (line 1769) | function deflateSetDictionary(strm, dictionary) {

FILE: polyfills/zlib-lib/inffast.js
  function inflate_fast (line 41) | function inflate_fast(strm, start) {

FILE: polyfills/zlib-lib/inflate.js
  function zswap32 (line 94) | function zswap32(q) {
  function InflateState (line 102) | function InflateState() {
  function inflateResetKeep (line 160) | function inflateResetKeep(strm) {
  function inflateReset (line 189) | function inflateReset(strm) {
  function inflateReset2 (line 203) | function inflateReset2(strm, windowBits) {
  function inflateInit2 (line 238) | function inflateInit2(strm, windowBits) {
  function inflateInit (line 260) | function inflateInit(strm) {
  function fixedtables (line 279) | function fixedtables(state) {
  function updatewindow (line 341) | function updatewindow(strm, src, end, copy) {
  function inflate (line 385) | function inflate(strm, flush) {
  function inflateEnd (line 1570) | function inflateEnd(strm) {
  function inflateGetHeader (line 1584) | function inflateGetHeader(strm, head) {
  function inflateSetDictionary (line 1602) | function inflateSetDictionary(strm, dictionary) {

FILE: polyfills/zlib-lib/inftrees.js
  function inflate_table (line 33) | function inflate_table(type, lens, lens_index, codes, table, table_index...

FILE: polyfills/zlib-lib/trees.js
  function zero (line 24) | function zero(buf) {
  function StaticTreeDesc (line 148) | function StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_...
  function TreeDesc (line 166) | function TreeDesc(dyn_tree, stat_desc) {
  function d_code (line 174) | function d_code(dist) {
  function put_short (line 183) | function put_short(s, w) {
  function send_bits (line 195) | function send_bits(s, value, length) {
  function send_code (line 208) | function send_code(s, c, tree) {
  function bi_reverse (line 218) | function bi_reverse(code, len) {
  function bi_flush (line 232) | function bi_flush(s) {
  function gen_bitlen (line 256) | function gen_bitlen(s, desc) {
  function gen_codes (line 360) | function gen_codes(tree, max_code, bl_count) {
  function tr_static_init (line 400) | function tr_static_init() {
  function init_block (line 504) | function init_block(s) {
  function bi_windup (line 527) | function bi_windup(s) {
  function copy_block (line 542) | function copy_block(s, buf, len, header) {
  function smaller (line 565) | function smaller(tree, n, m, depth) {
  function pqdownheap (line 578) | function pqdownheap(s, tree, k)
  function compress_block (line 613) | function compress_block(s, ltree, dtree)
  function build_tree (line 673) | function build_tree(s, desc)
  function scan_tree (line 771) | function scan_tree(s, tree, max_code)
  function send_tree (line 839) | function send_tree(s, tree, max_code)
  function build_bl_tree (line 913) | function build_bl_tree(s) {
  function send_all_trees (line 949) | function send_all_trees(s, lcodes, dcodes, blcodes)
  function detect_data_type (line 989) | function detect_data_type(s) {
  function _tr_init (line 1027) | function _tr_init(s) {
  function _tr_stored_block (line 1049) | function _tr_stored_block(s, buf, stored_len, last)
  function _tr_align (line 1064) | function _tr_align(s) {
  function _tr_flush_block (line 1075) | function _tr_flush_block(s, buf, stored_len, last)
  function _tr_tally (line 1164) | function _tr_tally(s, dist, lc)

FILE: polyfills/zlib-lib/utils.js
  function assign (line 9) | function assign(obj /*from1, from2, from3, ...*/) {
  function shrinkBuf (line 31) | function shrinkBuf(buf, size) {
  function arraySet (line 37) | function arraySet(dest, src, src_offs, len, dest_offs) {
  function flattenChunks (line 47) | function flattenChunks(chunks) {

FILE: polyfills/zlib-lib/zstream.js
  function ZStream (line 3) | function ZStream() {

FILE: polyfills/zlib.js
  function assert (line 25) | function assert (a, msg) {
  function createDeflate (line 73) | function createDeflate(o) {
  function createInflate (line 77) | function createInflate(o) {
  function createDeflateRaw (line 81) | function createDeflateRaw(o) {
  function createInflateRaw (line 85) | function createInflateRaw(o) {
  function createGzip (line 89) | function createGzip(o) {
  function createGunzip (line 93) | function createGunzip(o) {
  function createUnzip (line 97) | function createUnzip(o) {
  function deflate (line 104) | function deflate(buffer, opts, callback) {
  function deflateSync (line 112) | function deflateSync(buffer, opts) {
  function gzip (line 116) | function gzip(buffer, opts, callback) {
  function gzipSync (line 124) | function gzipSync(buffer, opts) {
  function deflateRaw (line 128) | function deflateRaw(buffer, opts, callback) {
  function deflateRawSync (line 136) | function deflateRawSync(buffer, opts) {
  function unzip (line 140) | function unzip(buffer, opts, callback) {
  function unzipSync (line 148) | function unzipSync(buffer, opts) {
  function inflate (line 152) | function inflate(buffer, opts, callback) {
  function inflateSync (line 160) | function inflateSync(buffer, opts) {
  function gunzip (line 164) | function gunzip(buffer, opts, callback) {
  function gunzipSync (line 172) | function gunzipSync(buffer, opts) {
  function inflateRaw (line 176) | function inflateRaw(buffer, opts, callback) {
  function inflateRawSync (line 184) | function inflateRawSync(buffer, opts) {
  function zlibBuffer (line 188) | function zlibBuffer(engine, buffer, callback) {
  function zlibBufferSync (line 221) | function zlibBufferSync(engine, buffer) {
  function Deflate (line 234) | function Deflate(opts) {
  function Inflate (line 239) | function Inflate(opts) {
  function Gzip (line 247) | function Gzip(opts) {
  function Gunzip (line 252) | function Gunzip(opts) {
  function DeflateRaw (line 260) | function DeflateRaw(opts) {
  function InflateRaw (line 265) | function InflateRaw(opts) {
  function Unzip (line 272) | function Unzip(opts) {
  function Zlib (line 283) | function Zlib(opts, mode) {
  function callback (line 540) | function callback(availInAfter, availOutAfter) {

FILE: scripts/build-polyfills.js
  function main (line 8) | async function main() {
  function bundleDependency (line 17) | async function bundleDependency(depName) {

FILE: src/index.ts
  method resolveId (line 25) | resolveId(importee: string, importer: string) {
  method load (line 38) | load(id: string) {
  method transform (line 43) | transform(code: string, id: string)  {
  function getRandomId (line 49) | function getRandomId() {
  constant GLOBAL_PATH (line 53) | const GLOBAL_PATH = require.resolve('../polyfills/global.js');
  constant DIRNAME_PATH (line 54) | const DIRNAME_PATH = '\0node-polyfills:dirname';
  constant FILENAME_PATH (line 55) | const FILENAME_PATH = '\0node-polyfills:filename';

FILE: src/modules.ts
  constant EMPTY_PATH (line 1) | const EMPTY_PATH = require.resolve('../polyfills/empty.js');
  type NodePolyfillsOptions (line 3) | interface NodePolyfillsOptions {
  function builtinsResolver (line 12) | function builtinsResolver(opts: NodePolyfillsOptions) {

FILE: test/examples/domain.js
  function next (line 15) | function next() {

FILE: test/examples/zlib.js
  function next (line 15) | function next() {
Condensed preview — 77 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (1,544K chars).
[
  {
    "path": ".gitignore",
    "chars": 34,
    "preview": "dist\ndist-transpiled\nnode_modules\n"
  },
  {
    "path": "LICENSE.md",
    "chars": 1078,
    "preview": "The MIT License (MIT)\n\nCopyright (c) 2019 these people\n\nPermission is hereby granted, free of charge, to any person obta"
  },
  {
    "path": "browser-test/index.js",
    "chars": 432,
    "preview": "var rollup = require( 'rollup' );\nvar nodePolyfills = require('..');\nrollup.rollup({\n  input: 'browser-test/main.js',\n  "
  },
  {
    "path": "browser-test/main.js",
    "chars": 1015,
    "preview": "import {get} from 'http';\nimport {createContext, runInContext} from 'vm';\nimport {equal, deepEqual} from 'assert';\n\nget("
  },
  {
    "path": "package.json",
    "chars": 1446,
    "preview": "{\n  \"name\": \"rollup-plugin-node-polyfills\",\n  \"version\": \"0.2.1\",\n  \"main\": \"dist/index.js\",\n  \"module\": \"dist/index.mjs"
  },
  {
    "path": "polyfills/LICENSE-browserify-fs.txt",
    "chars": 13341,
    "preview": "Name: browserify-fs\nVersion: 1.0.0\nLicense: undefined\nPrivate: false\nDescription: fs for the browser using level-filesys"
  },
  {
    "path": "polyfills/LICENSE-buffer-es6.txt",
    "chars": 325,
    "preview": "Name: buffer-es6\nVersion: 4.9.3\nLicense: MIT\nPrivate: false\nDescription: Node.js Buffer API, for the browser\nRepository:"
  },
  {
    "path": "polyfills/LICENSE-crypto-browserify.txt",
    "chars": 8727,
    "preview": "Name: crypto-browserify\nVersion: 3.12.0\nLicense: MIT\nPrivate: false\nDescription: implementation of crypto for the browse"
  },
  {
    "path": "polyfills/LICENSE-process-es6.txt",
    "chars": 239,
    "preview": "Name: process-es6\nVersion: 0.11.6\nLicense: MIT\nPrivate: false\nDescription: process information for node.js and browsers,"
  },
  {
    "path": "polyfills/assert.js",
    "chars": 15448,
    "preview": "\nfunction compare(a, b) {\n  if (a === b) {\n    return 0;\n  }\n\n  var x = a.length;\n  var y = b.length;\n\n  for (var i = 0,"
  },
  {
    "path": "polyfills/browserify-fs.js",
    "chars": 542528,
    "preview": "import util$2 from 'util';\nimport buffer from 'buffer';\nimport events from 'events';\nimport stream from 'stream';\nimport"
  },
  {
    "path": "polyfills/buffer-es6.js",
    "chars": 54354,
    "preview": "var lookup = [];\nvar revLookup = [];\nvar Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array;\nvar inited = fals"
  },
  {
    "path": "polyfills/console.js",
    "chars": 203,
    "preview": "function noop(){}\n\nexport default global.console ? global.console : {\n  log: noop,\n  info: noop,\n  warn: noop,\n  error: "
  },
  {
    "path": "polyfills/constants.js",
    "chars": 15777,
    "preview": "export var RTLD_LAZY = 1;\nexport var RTLD_NOW = 2;\nexport var RTLD_GLOBAL = 8;\nexport var RTLD_LOCAL = 4;\nexport var E2B"
  },
  {
    "path": "polyfills/crypto-browserify.js",
    "chars": 430262,
    "preview": "import buffer$1 from 'buffer';\nimport stream from 'stream';\nimport string_decoder from 'string_decoder';\nimport crypto$1"
  },
  {
    "path": "polyfills/domain.js",
    "chars": 2981,
    "preview": "/*\n<!-- LICENSEFILE/ -->\n\n<h1>License</h1>\n\nUnless stated otherwise all works are:\n\n<ul><li>Copyright &copy; 2013+ <a hr"
  },
  {
    "path": "polyfills/empty.js",
    "chars": 19,
    "preview": "export default {};\n"
  },
  {
    "path": "polyfills/events.js",
    "chars": 13111,
    "preview": "'use strict';\n\nvar domain;\n\n// This constructor is used to store event handlers. Instantiating this is\n// faster than ex"
  },
  {
    "path": "polyfills/global.js",
    "chars": 143,
    "preview": "export default (typeof global !== \"undefined\" ? global :\n  typeof self !== \"undefined\" ? self :\n  typeof window !== \"und"
  },
  {
    "path": "polyfills/http-lib/capability.js",
    "chars": 1715,
    "preview": "export var hasFetch = isFunction(global.fetch) && isFunction(global.ReadableStream)\n\nvar _blobConstructor;\nexport functi"
  },
  {
    "path": "polyfills/http-lib/request.js",
    "chars": 7526,
    "preview": "import * as capability from './capability';\nimport {inherits} from 'util';\nimport {IncomingMessage, readyStates as rStat"
  },
  {
    "path": "polyfills/http-lib/response.js",
    "chars": 5191,
    "preview": "import {overrideMimeType} from './capability';\nimport {inherits} from 'util';\nimport {Readable} from 'stream';\n\nvar rSta"
  },
  {
    "path": "polyfills/http-lib/to-arraybuffer.js",
    "chars": 1063,
    "preview": "// from https://github.com/jhiesey/to-arraybuffer/blob/6502d9850e70ba7935a7df4ad86b358fc216f9f0/index.js\n\n// MIT License"
  },
  {
    "path": "polyfills/http.js",
    "chars": 4536,
    "preview": "/*\nthis and http-lib folder\n\nThe MIT License\n\nCopyright (c) 2015 John Hiesey\n\nPermission is hereby granted, free of char"
  },
  {
    "path": "polyfills/inherits.js",
    "chars": 663,
    "preview": "\nvar inherits;\nif (typeof Object.create === 'function'){\n  inherits = function inherits(ctor, superCtor) {\n    // implem"
  },
  {
    "path": "polyfills/os.js",
    "chars": 2685,
    "preview": "/*\nThe MIT License (MIT)\n\nCopyright (c) 2016 CoderPuppy\n\nPermission is hereby granted, free of charge, to any person obt"
  },
  {
    "path": "polyfills/path.js",
    "chars": 6356,
    "preview": "// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person"
  },
  {
    "path": "polyfills/process-es6.js",
    "chars": 6372,
    "preview": "// shim for using process in browser\n// based off https://github.com/defunctzombie/node-process/blob/master/browser.js\n\n"
  },
  {
    "path": "polyfills/punycode.js",
    "chars": 13335,
    "preview": "/*! https://mths.be/punycode v1.4.1 by @mathias */\n\n\n/** Highest positive signed 32-bit float value */\nvar maxInt = 2147"
  },
  {
    "path": "polyfills/qs.js",
    "chars": 3906,
    "preview": "// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person"
  },
  {
    "path": "polyfills/readable-stream/buffer-list.js",
    "chars": 1347,
    "preview": "import {Buffer} from 'buffer';\n\nexport default BufferList;\n\nfunction BufferList() {\n  this.head = null;\n  this.tail = nu"
  },
  {
    "path": "polyfills/readable-stream/duplex.js",
    "chars": 1182,
    "preview": "\nimport {inherits} from 'util';\nimport {nextTick} from 'process';\nimport {Readable} from './readable';\nimport {Writable}"
  },
  {
    "path": "polyfills/readable-stream/passthrough.js",
    "chars": 371,
    "preview": "\nimport {Transform} from './transform';\n\nimport {inherits} from 'util';\ninherits(PassThrough, Transform);\nexport default"
  },
  {
    "path": "polyfills/readable-stream/readable.js",
    "chars": 27160,
    "preview": "'use strict';\n\n\nReadable.ReadableState = ReadableState;\nimport EventEmitter from 'events';\nimport {inherits, debuglog} f"
  },
  {
    "path": "polyfills/readable-stream/transform.js",
    "chars": 6251,
    "preview": "// a transform stream is a readable/writable stream where you do\n// something with the data.  Sometimes it's called a \"f"
  },
  {
    "path": "polyfills/readable-stream/writable.js",
    "chars": 14191,
    "preview": "// A bit simpler than readable streams.\n// Implement an async ._write(chunk, encoding, cb), and it'll handle all\n// the "
  },
  {
    "path": "polyfills/setimmediate.js",
    "chars": 5854,
    "preview": "/*\nMIT Licence\nCopyright (c) 2012 Barnesandnoble.com, llc, Donavon West, and Domenic Denicola\nhttps://github.com/YuzuJS/"
  },
  {
    "path": "polyfills/stream.js",
    "chars": 2665,
    "preview": "import EE from 'events';\nimport {inherits} from 'util';\n\nimport {Duplex} from './readable-stream/duplex.js';\nimport {Rea"
  },
  {
    "path": "polyfills/string-decoder.js",
    "chars": 7764,
    "preview": "// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person"
  },
  {
    "path": "polyfills/timers.js",
    "chars": 1972,
    "preview": "// License https://jryans.mit-license.org/\n\nimport {setImmediate, clearImmediate} from './setimmediate';\nexport {setImme"
  },
  {
    "path": "polyfills/tty.js",
    "chars": 439,
    "preview": "// MIT lisence\n// from https://github.com/substack/tty-browserify/blob/1ba769a6429d242f36226538835b4034bf6b7886/index.js"
  },
  {
    "path": "polyfills/url.js",
    "chars": 23272,
    "preview": "// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person"
  },
  {
    "path": "polyfills/util.js",
    "chars": 15717,
    "preview": "// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person"
  },
  {
    "path": "polyfills/vm.js",
    "chars": 5079,
    "preview": "/*\nfrom https://github.com/substack/vm-browserify/blob/bfd7c5f59edec856dc7efe0b77a4f6b2fa20f226/index.js\n\nMIT license no"
  },
  {
    "path": "polyfills/zlib-lib/LICENSE",
    "chars": 1084,
    "preview": "(The MIT License)\n\nCopyright (C) 2014-2016 by Vitaly Puzrin\n\nPermission is hereby granted, free of charge, to any person"
  },
  {
    "path": "polyfills/zlib-lib/adler32.js",
    "chars": 678,
    "preview": "\n// Note: adler32 takes 12% for level 0 and 2% for level 6.\n// It doesn't worth to make additional optimizationa as in o"
  },
  {
    "path": "polyfills/zlib-lib/binding.js",
    "chars": 6173,
    "preview": "import msg from './messages';\nimport zstream from './zstream';\nimport {deflateInit2, deflateEnd, deflateReset, deflate} "
  },
  {
    "path": "polyfills/zlib-lib/crc32.js",
    "chars": 774,
    "preview": "\n// Note: we can't get significant speed boost here.\n// So write code to minimize size - no pregenerated tables\n// and a"
  },
  {
    "path": "polyfills/zlib-lib/deflate.js",
    "chars": 59199,
    "preview": "\nimport {Buf8,Buf16,arraySet} from './utils';\nimport {_tr_flush_block, _tr_tally, _tr_init, _tr_align, _tr_stored_block}"
  },
  {
    "path": "polyfills/zlib-lib/inffast.js",
    "chars": 11691,
    "preview": "\n// See state defs from inflate.js\nvar BAD = 30;       /* got a data error -- remain here until reset */\nvar TYPE = 12; "
  },
  {
    "path": "polyfills/zlib-lib/inflate.js",
    "chars": 49114,
    "preview": "'use strict';\n\nimport {Buf8,Buf16,Buf32,arraySet} from './utils';\nimport adler32 from './adler32';\nimport crc32 from './"
  },
  {
    "path": "polyfills/zlib-lib/inftrees.js",
    "chars": 11116,
    "preview": "import {Buf16} from './utils';\nvar MAXBITS = 15;\nvar ENOUGH_LENS = 852;\nvar ENOUGH_DISTS = 592;\n//var ENOUGH = (ENOUGH_L"
  },
  {
    "path": "polyfills/zlib-lib/messages.js",
    "chars": 560,
    "preview": "export default {\n  2:      'need dictionary',     /* Z_NEED_DICT       2  */\n  1:      'stream end',          /* Z_STREA"
  },
  {
    "path": "polyfills/zlib-lib/trees.js",
    "chars": 38399,
    "preview": "'use strict';\n\nimport {arraySet} from './utils';\n\n/* Public constants =================================================="
  },
  {
    "path": "polyfills/zlib-lib/utils.js",
    "chars": 1691,
    "preview": "'use strict';\n\n\nvar TYPED_OK =  (typeof Uint8Array !== 'undefined') &&\n                (typeof Uint16Array !== 'undefine"
  },
  {
    "path": "polyfills/zlib-lib/zstream.js",
    "chars": 835,
    "preview": "\n\nfunction ZStream() {\n  /* next input byte */\n  this.input = null; // JS specific, because we have no pointers\n  this.n"
  },
  {
    "path": "polyfills/zlib.js",
    "chars": 17056,
    "preview": "// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person"
  },
  {
    "path": "readme.md",
    "chars": 2185,
    "preview": "rollup-plugin-node-polyfills\n===\n\n```\nnpm install --save-dev rollup-plugin-node-polyfills\n```\n\nAllows the node builtins "
  },
  {
    "path": "rollup.config.js",
    "chars": 284,
    "preview": "\nexport default {\n\tinput: 'dist-transpiled/index.js',\n\texternal: [\n\t\t'path',\n\t\t'crypto',\n\t\t'rollup-plugin-inject'\n\t],\n\to"
  },
  {
    "path": "scripts/build-constants.js",
    "chars": 511,
    "preview": "const fs = require('fs');\nconst constants = require('constants');\nconst path = require('path');\n\nvar out = fs.createWrit"
  },
  {
    "path": "scripts/build-polyfills.js",
    "chars": 1225,
    "preview": "const rollup = require('rollup');\nconst path = require('path');\nconst nodeResolve = require('rollup-plugin-node-resolve'"
  },
  {
    "path": "src/index.ts",
    "chars": 1731,
    "preview": "// @ts-ignore\nimport inject from 'rollup-plugin-inject';\nimport { builtinsResolver, NodePolyfillsOptions } from './modul"
  },
  {
    "path": "src/modules.ts",
    "chars": 3012,
    "preview": "const EMPTY_PATH = require.resolve('../polyfills/empty.js');\n\nexport interface NodePolyfillsOptions {\n  fs?: boolean;\n  "
  },
  {
    "path": "test/examples/assert.js",
    "chars": 252,
    "preview": "import {deepEqual} from 'assert';\nvar err;\ntry {\n  deepEqual({foo: {bar: ['baz']}}, {foo: {bar: ['bat']}}, 'something');"
  },
  {
    "path": "test/examples/constants.js",
    "chars": 215,
    "preview": "import {SIGHUP, defaultCoreCipherList} from 'constants';\n\nif (SIGHUP !== _constants.SIGHUP || defaultCoreCipherList !== "
  },
  {
    "path": "test/examples/crypto.js",
    "chars": 132,
    "preview": "import crypto from 'crypto';\n\nif (Object.keys(crypto).length) {\n  done(new Error('should not import crypto'));\n} else {\n"
  },
  {
    "path": "test/examples/domain.js",
    "chars": 754,
    "preview": "import {create} from 'domain';\n\nvar d = create()\nd.on('error', function(err) {\n  if (!err || err.message !== 'a thrown e"
  },
  {
    "path": "test/examples/events.js",
    "chars": 127,
    "preview": "import {EventEmitter as EE} from 'events';\n\nvar e = new EE();\ne.on('it', function (foo) {\n  done();\n});\ne.emit('it', 'wo"
  },
  {
    "path": "test/examples/os.js",
    "chars": 197,
    "preview": "import {endianness} from 'os';\nvar ourE = endianness();\nif (endianness() === _osEndianness) {\n  done();\n} else {\n  done("
  },
  {
    "path": "test/examples/path.js",
    "chars": 273,
    "preview": "import {dirname, relative} from 'path';\n\n\nvar basedir = '/';\nvar importer = './src/es6/path.js';\nvar out = dirname('/' +"
  },
  {
    "path": "test/examples/stream.js",
    "chars": 498,
    "preview": "import {Transform} from 'stream';\n\nvar total = 0;\nvar ended = false;\nvar t = new Transform({\n  objectMode: true,\n  trans"
  },
  {
    "path": "test/examples/string-decoder.js",
    "chars": 426,
    "preview": "import {StringDecoder} from 'string_decoder';\n\nvar text = Buffer.from('\\uD835\\uDC00\\uD83D\\uDCA9\\uD835\\uDC01');\n\nvar deco"
  },
  {
    "path": "test/examples/url-format.js",
    "chars": 199,
    "preview": "import {format} from 'url';\n\nvar created = format({\n  protocol: 'foo',\n  host: 'bar',\n  pathname: '/baz'\n});\n\nif (create"
  },
  {
    "path": "test/examples/url-parse.js",
    "chars": 275,
    "preview": "import {parse} from 'url';\n\nvar ourUrl = 'https://💩.gov/baz/bat?a=b#lalalallala';\nvar parsed = parse(ourUrl);\n\nif (\n  pa"
  },
  {
    "path": "test/examples/zlib.js",
    "chars": 686,
    "preview": "import {deflateSync, inflateSync} from 'zlib';\n\n\nvar input = new Buffer('hello hello hello');\n\nvar deflated = deflateSyn"
  },
  {
    "path": "test/index.js",
    "chars": 1623,
    "preview": "const vm = require('vm');\nconst rollup = require('rollup');\nconst nodePolyfills = require('..');\nconst os = require('os'"
  },
  {
    "path": "tsconfig.json",
    "chars": 231,
    "preview": "{\n  \"compilerOptions\": {\n    \"strict\": true,\n    \"module\": \"es2015\",\n    \"target\": \"es2017\",\n    \"declaration\": true,\n  "
  }
]

About this extraction

This page contains the full source code of the ionic-team/rollup-plugin-node-polyfills GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 77 files (1.4 MB), approximately 436.3k tokens, and a symbol index with 1173 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!