├── .gitignore ├── LICENSE.md ├── browser-test ├── index.js └── main.js ├── package-lock.json ├── 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 /.gitignore: -------------------------------------------------------------------------------- 1 | dist 2 | dist-transpiled 3 | node_modules 4 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2019 these people 4 | 5 | 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: 6 | 7 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 8 | 9 | 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. -------------------------------------------------------------------------------- /browser-test/index.js: -------------------------------------------------------------------------------- 1 | var rollup = require( 'rollup' ); 2 | var nodePolyfills = require('..'); 3 | rollup.rollup({ 4 | input: 'browser-test/main.js', 5 | plugins: [ 6 | nodePolyfills(), 7 | ] 8 | }).then( function ( bundle ) { 9 | return bundle.write({ 10 | format: 'iife', 11 | file: 'browser-test/dist/bundle.js' 12 | }); 13 | }).then(function () { 14 | console.log('done'); 15 | process.exit(); 16 | }).catch(function (e) { 17 | console.log('oh noes!'); 18 | console.log(e); 19 | process.exit(1); 20 | }); 21 | -------------------------------------------------------------------------------- /browser-test/main.js: -------------------------------------------------------------------------------- 1 | import {get} from 'http'; 2 | import {createContext, runInContext} from 'vm'; 3 | import {equal, deepEqual} from 'assert'; 4 | 5 | get('foo.json', function (res) { 6 | console.log('status', res.statusCode); 7 | var data = ''; 8 | res.on('data', function (d) { 9 | data += d.toString(); 10 | }).on('error', function (e) { 11 | console.log('error', e); 12 | }).on('end', function () { 13 | console.log(data); 14 | if (global.document) { 15 | afterMain(); 16 | } else { 17 | afterWorker(); 18 | } 19 | }); 20 | }) 21 | function afterMain() { 22 | var context = createContext(); 23 | 24 | runInContext('var x = 1', context); 25 | deepEqual(context, { x: 1 }); 26 | 27 | runInContext('var y = 2;', context); 28 | var x = runInContext('++x', context); 29 | equal(x, 2); 30 | equal(context.x, 2); 31 | equal(context.x, context.y); 32 | console.log('ok main'); 33 | } 34 | function afterWorker() { 35 | var context = createContext({x: 0}); 36 | 37 | runInContext('x++', context); 38 | deepEqual(context, { x: 1 }); 39 | 40 | var x = runInContext('++x', context); 41 | equal(x, 2); 42 | equal(context.x, 2); 43 | console.log('ok worker'); 44 | } 45 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "rollup-plugin-node-polyfills", 3 | "version": "0.2.1", 4 | "main": "dist/index.js", 5 | "module": "dist/index.mjs", 6 | "types": "dist/types/index.d.ts", 7 | "scripts": { 8 | "pretest": "npm run build", 9 | "test": "mocha", 10 | "prebuild": "rm -rf dist && mkdir dist", 11 | "build": "npm run build:constants && npm run build:deps && npm run build:bundlers", 12 | "build:bundlers": "tsc -p . && rollup -c", 13 | "build:deps": "node scripts/build-polyfills.js", 14 | "build:constants": "node scripts/build-constants.js", 15 | "release": "np --no-yarn --no-release-draft", 16 | "browser-test": "serve browser-test/dist", 17 | "prebrowser-test": "npm run build && node ./browser-test/index.js" 18 | }, 19 | "files": [ 20 | "dist", 21 | "polyfills" 22 | ], 23 | "keywords": [ 24 | "rollup-plugin" 25 | ], 26 | "author": "", 27 | "license": "MIT", 28 | "dependencies": { 29 | "rollup-plugin-inject": "^3.0.0" 30 | }, 31 | "devDependencies": { 32 | "browserify-fs": "^1.0.0", 33 | "buffer-es6": "^4.9.2", 34 | "crypto-browserify": "^3.11.0", 35 | "debug": "^4.1.1", 36 | "mocha": "^6.1.4", 37 | "np": "^5.0.3", 38 | "process-es6": "^0.11.2", 39 | "rollup": "^1.15.4", 40 | "rollup-plugin-commonjs": "^10.0.0", 41 | "rollup-plugin-json": "^4.0.0", 42 | "rollup-plugin-license": "^0.9.0", 43 | "rollup-plugin-node-resolve": "^5.0.2", 44 | "serve": "^11.0.1", 45 | "typescript": "^3.5.2" 46 | }, 47 | "repository": { 48 | "type": "git", 49 | "url": "git@github.com:ionic-team/rollup-plugin-node-polyfills.git" 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /polyfills/LICENSE-browserify-fs.txt: -------------------------------------------------------------------------------- 1 | Name: browserify-fs 2 | Version: 1.0.0 3 | License: undefined 4 | Private: false 5 | Description: fs for the browser using level-filesystem and browserify 6 | Repository: undefined 7 | 8 | --- 9 | 10 | Name: level-js 11 | Version: 2.2.4 12 | License: BSD-2-Clause 13 | Private: false 14 | Description: leveldown/leveldb library for browsers using IndexedDB 15 | Repository: git@github.com:maxogden/level.js.git 16 | Author: max ogden 17 | 18 | --- 19 | 20 | Name: levelup 21 | Version: 0.18.6 22 | License: MIT 23 | Private: false 24 | Description: Fast & simple storage - a Node.js-style LevelDB wrapper 25 | Repository: https://github.com/rvagg/node-levelup.git 26 | Homepage: https://github.com/rvagg/node-levelup 27 | Contributors: 28 | Rod Vagg (https://github.com/rvagg) 29 | John Chesley (https://github.com/chesles/) 30 | Jake Verbaten (https://github.com/raynos) 31 | Dominic Tarr (https://github.com/dominictarr) 32 | Max Ogden (https://github.com/maxogden) 33 | Lars-Magnus Skog (https://github.com/ralphtheninja) 34 | David Björklund (https://github.com/kesla) 35 | Julian Gruber (https://github.com/juliangruber) 36 | Paolo Fragomeni (https://github.com/hij1nx) 37 | Anton Whalley (https://github.com/No9) 38 | Matteo Collina (https://github.com/mcollina) 39 | Pedro Teixeira (https://github.com/pgte) 40 | James Halliday (https://github.com/substack) 41 | 42 | --- 43 | 44 | Name: level-filesystem 45 | Version: 1.2.0 46 | License: undefined 47 | Private: false 48 | Description: Full implementation of the fs module on top of leveldb 49 | Repository: undefined 50 | 51 | --- 52 | 53 | Name: rollup-plugin-node-resolve 54 | Version: 5.0.1 55 | License: MIT 56 | Private: false 57 | Description: Bundle third-party dependencies in node_modules 58 | Repository: undefined 59 | Homepage: https://github.com/rollup/rollup-plugin-node-resolve#readme 60 | Author: Rich Harris 61 | 62 | --- 63 | 64 | Name: prr 65 | Version: 0.0.0 66 | License: MIT 67 | Private: false 68 | Description: A better Object.defineProperty() 69 | Repository: https://github.com/rvagg/prr.git 70 | Homepage: https://github.com/rvagg/prr 71 | 72 | --- 73 | 74 | Name: xtend 75 | Version: 2.1.2 76 | License: (MIT) 77 | Private: false 78 | Description: extend like a boss 79 | Repository: undefined 80 | Homepage: https://github.com/Raynos/xtend 81 | Author: Raynos 82 | Contributors: 83 | Jake Verbaten 84 | Matt Esch 85 | 86 | --- 87 | 88 | Name: once 89 | Version: 1.4.0 90 | License: ISC 91 | Private: false 92 | Description: Run a function exactly one time 93 | Repository: git://github.com/isaacs/once 94 | Author: Isaac Z. Schlueter (http://blog.izs.me/) 95 | 96 | --- 97 | 98 | Name: octal 99 | Version: 1.0.0 100 | License: MIT 101 | Private: false 102 | Description: Interpret a number as base 8 103 | Repository: https://github.com/mafintosh/octal.git 104 | Homepage: https://github.com/mafintosh/octal 105 | Author: Mathias Buus (@mafintosh) 106 | 107 | --- 108 | 109 | Name: readable-stream 110 | Version: 1.0.34 111 | License: MIT 112 | Private: false 113 | Description: Streams2, a user-land copy of the stream library from Node.js v0.10.x 114 | Repository: git://github.com/isaacs/readable-stream 115 | Author: Isaac Z. Schlueter (http://blog.izs.me/) 116 | 117 | --- 118 | 119 | Name: level-blobs 120 | Version: 0.1.7 121 | License: undefined 122 | Private: false 123 | Description: Save binary blobs in level and stream then back 124 | Repository: undefined 125 | 126 | --- 127 | 128 | Name: level-sublevel 129 | Version: 5.2.3 130 | License: MIT 131 | Private: false 132 | Description: partition levelup databases 133 | Repository: git://github.com/dominictarr/level-sublevel.git 134 | Homepage: https://github.com/dominictarr/level-sublevel 135 | Author: Dominic Tarr (http://dominictarr.com) 136 | 137 | --- 138 | 139 | Name: fwd-stream 140 | Version: 1.0.4 141 | License: undefined 142 | Private: false 143 | Description: Forward a readable stream to another readable stream or a writable stream to another writable stream 144 | Repository: undefined 145 | 146 | --- 147 | 148 | Name: level-peek 149 | Version: 1.0.6 150 | License: MIT 151 | Private: false 152 | Repository: git://github.com/dominictarr/level-peek.git 153 | Homepage: https://github.com/dominictarr/level-peek 154 | Author: Dominic Tarr (http://dominictarr.com) 155 | 156 | --- 157 | 158 | Name: errno 159 | Version: 0.1.7 160 | License: MIT 161 | Private: false 162 | Description: libuv errno details exposed 163 | Repository: https://github.com/rvagg/node-errno.git 164 | 165 | --- 166 | 167 | Name: concat-stream 168 | Version: 1.6.2 169 | License: MIT 170 | Private: false 171 | Description: writable stream that concatenates strings or binary data and calls a callback with the result 172 | Repository: http://github.com/maxogden/concat-stream.git 173 | Author: Max Ogden 174 | 175 | --- 176 | 177 | Name: inherits 178 | Version: 2.0.3 179 | License: ISC 180 | Private: false 181 | Description: Browser-friendly inheritance fully compatible with standard node.js inherits() 182 | Repository: undefined 183 | 184 | --- 185 | 186 | Name: idb-wrapper 187 | Version: 1.7.2 188 | License: MIT 189 | Private: false 190 | Description: A cross-browser wrapper for IndexedDB 191 | Repository: undefined 192 | Homepage: https://github.com/jensarps/IDBWrapper 193 | Author: jensarps (http://jensarps.de/) 194 | Contributors: 195 | Github Contributors (https://github.com/jensarps/IDBWrapper/graphs/contributors) 196 | 197 | --- 198 | 199 | Name: typedarray-to-buffer 200 | Version: 1.0.4 201 | License: MIT 202 | Private: false 203 | Description: Convert a typed array to a Buffer without a copy 204 | Repository: git://github.com/feross/typedarray-to-buffer.git 205 | Homepage: http://feross.org 206 | Author: Feross Aboukhadijeh (http://feross.org/) 207 | 208 | --- 209 | 210 | Name: abstract-leveldown 211 | Version: 0.12.4 212 | License: MIT 213 | Private: false 214 | Description: An abstract prototype matching the LevelDOWN API 215 | Repository: https://github.com/rvagg/node-abstract-leveldown.git 216 | Homepage: https://github.com/rvagg/node-abstract-leveldown 217 | Contributors: 218 | Rod Vagg (https://github.com/rvagg) 219 | John Chesley (https://github.com/chesles/) 220 | Jake Verbaten (https://github.com/raynos) 221 | Dominic Tarr (https://github.com/dominictarr) 222 | Max Ogden (https://github.com/maxogden) 223 | Lars-Magnus Skog (https://github.com/ralphtheninja) 224 | David Björklund (https://github.com/kesla) 225 | Julian Gruber (https://github.com/juliangruber) 226 | Paolo Fragomeni (https://github.com/hij1nx) 227 | Anton Whalley (https://github.com/No9) 228 | Matteo Collina (https://github.com/mcollina) 229 | Pedro Teixeira (https://github.com/pgte) 230 | James Halliday (https://github.com/substack) 231 | 232 | --- 233 | 234 | Name: isbuffer 235 | Version: 0.0.0 236 | License: MIT 237 | Private: false 238 | Description: isBuffer for node and browser (supports typed arrays) 239 | Repository: git://github.com/juliangruber/isbuffer.git 240 | Homepage: https://github.com/juliangruber/isbuffer 241 | Author: Julian Gruber (http://juliangruber.com) 242 | 243 | --- 244 | 245 | Name: deferred-leveldown 246 | Version: 0.2.0 247 | License: MIT 248 | Private: false 249 | Description: For handling delayed-open on LevelDOWN compatible libraries 250 | Repository: https://github.com/Level/deferred-leveldown.git 251 | Homepage: https://github.com/Level/deferred-leveldown 252 | Contributors: 253 | Rod Vagg (https://github.com/rvagg) 254 | John Chesley (https://github.com/chesles/) 255 | Jake Verbaten (https://github.com/raynos) 256 | Dominic Tarr (https://github.com/dominictarr) 257 | Max Ogden (https://github.com/maxogden) 258 | Lars-Magnus Skog (https://github.com/ralphtheninja) 259 | David Björklund (https://github.com/kesla) 260 | Julian Gruber (https://github.com/juliangruber) 261 | Paolo Fragomeni (https://github.com/hij1nx) 262 | Anton Whalley (https://github.com/No9) 263 | Matteo Collina (https://github.com/mcollina) 264 | Pedro Teixeira (https://github.com/pgte) 265 | James Halliday (https://github.com/substack) 266 | 267 | --- 268 | 269 | Name: wrappy 270 | Version: 1.0.2 271 | License: ISC 272 | Private: false 273 | Description: Callback wrapping utility 274 | Repository: https://github.com/npm/wrappy 275 | Homepage: https://github.com/npm/wrappy 276 | Author: Isaac Z. Schlueter (http://blog.izs.me/) 277 | 278 | --- 279 | 280 | Name: bl 281 | Version: 0.8.2 282 | License: MIT 283 | Private: false 284 | Description: Buffer List: collect buffers and access with a standard readable Buffer interface, streamable too! 285 | Repository: https://github.com/rvagg/bl.git 286 | Homepage: https://github.com/rvagg/bl 287 | 288 | --- 289 | 290 | Name: object-keys 291 | Version: 0.4.0 292 | License: MIT 293 | Private: false 294 | Description: An Object.keys replacement, in case Object.keys is not available. From https://github.com/kriskowal/es5-shim 295 | Repository: git://github.com/ljharb/object-keys.git 296 | Author: Jordan Harband 297 | 298 | --- 299 | 300 | Name: ltgt 301 | Version: 2.2.1 302 | License: MIT 303 | Private: false 304 | Repository: git://github.com/dominictarr/ltgt.git 305 | Homepage: https://github.com/dominictarr/ltgt 306 | Author: Dominic Tarr (http://dominictarr.com) 307 | 308 | --- 309 | 310 | Name: typedarray 311 | Version: 0.0.6 312 | License: MIT 313 | Private: false 314 | Description: TypedArray polyfill for old browsers 315 | Repository: git://github.com/substack/typedarray.git 316 | Homepage: https://github.com/substack/typedarray 317 | Author: James Halliday (http://substack.net) 318 | 319 | --- 320 | 321 | Name: level-fix-range 322 | Version: 2.0.0 323 | License: MIT 324 | Private: false 325 | Description: make using levelup reverse ranges easy 326 | Repository: git://github.com/dominictarr/level-fix-range.git 327 | Homepage: https://github.com/dominictarr/level-fix-range 328 | Author: Dominic Tarr (http://dominictarr.com) 329 | 330 | --- 331 | 332 | Name: buffer-from 333 | Version: 1.1.1 334 | License: MIT 335 | Private: false 336 | Repository: undefined 337 | 338 | --- 339 | 340 | Name: isarray 341 | Version: 0.0.1 342 | License: MIT 343 | Private: false 344 | Description: Array#isArray for older browsers 345 | Repository: git://github.com/juliangruber/isarray.git 346 | Homepage: https://github.com/juliangruber/isarray 347 | Author: Julian Gruber (http://juliangruber.com) 348 | 349 | --- 350 | 351 | Name: string_decoder 352 | Version: 0.10.31 353 | License: MIT 354 | Private: false 355 | Description: The string_decoder module from Node core 356 | Repository: git://github.com/rvagg/string_decoder.git 357 | Homepage: https://github.com/rvagg/string_decoder 358 | 359 | --- 360 | 361 | Name: safe-buffer 362 | Version: 5.1.2 363 | License: MIT 364 | Private: false 365 | Description: Safer Node.js Buffer API 366 | Repository: git://github.com/feross/safe-buffer.git 367 | Homepage: https://github.com/feross/safe-buffer 368 | Author: Feross Aboukhadijeh (http://feross.org) 369 | 370 | --- 371 | 372 | Name: level-hooks 373 | Version: 4.5.0 374 | License: undefined 375 | Private: false 376 | Description: pre/post hooks for leveldb 377 | Repository: git://github.com/dominictarr/level-hooks.git 378 | Homepage: https://github.com/dominictarr/level-hooks 379 | Author: Dominic Tarr (http://bit.ly/dominictarr) 380 | 381 | --- 382 | 383 | Name: core-util-is 384 | Version: 1.0.2 385 | License: MIT 386 | Private: false 387 | Description: The `util.is*` functions introduced in Node v0.12. 388 | Repository: git://github.com/isaacs/core-util-is 389 | Author: Isaac Z. Schlueter (http://blog.izs.me/) 390 | 391 | --- 392 | 393 | Name: string-range 394 | Version: 1.2.2 395 | License: MIT 396 | Private: false 397 | Description: check if a string is within a range 398 | Repository: git://github.com/dominictarr/string-range.git 399 | Homepage: https://github.com/dominictarr/string-range 400 | Author: Dominic Tarr (http://dominictarr.com) 401 | 402 | --- 403 | 404 | Name: process-nextick-args 405 | Version: 2.0.0 406 | License: MIT 407 | Private: false 408 | Description: process.nextTick but always with args 409 | Repository: https://github.com/calvinmetcalf/process-nextick-args.git 410 | Homepage: https://github.com/calvinmetcalf/process-nextick-args 411 | 412 | --- 413 | 414 | Name: util-deprecate 415 | Version: 1.0.2 416 | License: MIT 417 | Private: false 418 | Description: The Node.js `util.deprecate()` function with browser support 419 | Repository: git://github.com/TooTallNate/util-deprecate.git 420 | Homepage: https://github.com/TooTallNate/util-deprecate 421 | Author: Nathan Rajlich (http://n8.io/) 422 | 423 | --- 424 | 425 | Name: clone 426 | Version: 0.1.19 427 | License: MIT 428 | Private: false 429 | Description: deep cloning of objects and arrays 430 | Repository: git://github.com/pvorb/node-clone.git 431 | Author: Paul Vorbach (http://paul.vorba.ch/) 432 | Contributors: 433 | Blake Miner (http://www.blakeminer.com/) 434 | Tian You (http://blog.axqd.net/) 435 | George Stagas (http://stagas.com/) 436 | Tobiasz Cudnik (https://github.com/TobiaszCudnik) 437 | Pavel Lang (https://github.com/langpavel) 438 | Dan MacTough (http://yabfog.com/) 439 | w1nk (https://github.com/w1nk) 440 | Hugh Kennedy (http://twitter.com/hughskennedy) 441 | Dustin Diaz (http://dustindiaz.com) 442 | Ilya Shaisultanov (https://github.com/diversario) 443 | Nathan MacInnes (http://macinn.es/) 444 | Benjamin E. Coe (https://twitter.com/benjamincoe) 445 | Nathan Zadoks (https://github.com/nathan7) 446 | Róbert Oroszi (https://github.com/oroce) 447 | 448 | --- 449 | 450 | Name: is 451 | Version: 0.2.7 452 | License: undefined 453 | Private: false 454 | Description: the definitive JavaScript type testing library 455 | Repository: git://github.com/enricomarino/is.git 456 | Homepage: https://github.com/enricomarino/is 457 | Author: Enrico Marino (http://onirame.com) 458 | Contributors: 459 | Jordan Harband (https://github.com/ljharb) 460 | 461 | --- 462 | 463 | Name: foreach 464 | Version: 2.0.5 465 | License: MIT 466 | Private: false 467 | Description: foreach component + npm package 468 | Repository: git://github.com/manuelstofer/foreach 469 | Author: Manuel Stofer 470 | Contributors: 471 | Manuel Stofer 472 | Jordan Harband (https://github.com/ljharb) -------------------------------------------------------------------------------- /polyfills/LICENSE-buffer-es6.txt: -------------------------------------------------------------------------------- 1 | Name: buffer-es6 2 | Version: 4.9.3 3 | License: MIT 4 | Private: false 5 | Description: Node.js Buffer API, for the browser 6 | Repository: git://github.com/calvinmetcalf/buffer-es6.git 7 | Author: Feross Aboukhadijeh (http://feross.org) 8 | Contributors: 9 | Romain Beauxis 10 | James Halliday -------------------------------------------------------------------------------- /polyfills/LICENSE-crypto-browserify.txt: -------------------------------------------------------------------------------- 1 | Name: crypto-browserify 2 | Version: 3.12.0 3 | License: MIT 4 | Private: false 5 | Description: implementation of crypto for the browser 6 | Repository: git://github.com/crypto-browserify/crypto-browserify.git 7 | Homepage: https://github.com/crypto-browserify/crypto-browserify 8 | Author: Dominic Tarr (dominictarr.com) 9 | 10 | --- 11 | 12 | Name: browserify-sign 13 | Version: 4.0.4 14 | License: ISC 15 | Private: false 16 | Description: adds node crypto signing for browsers 17 | Repository: https://github.com/crypto-browserify/browserify-sign.git 18 | 19 | --- 20 | 21 | Name: randombytes 22 | Version: 2.1.0 23 | License: MIT 24 | Private: false 25 | Description: random bytes from browserify stand alone 26 | Repository: git@github.com:crypto-browserify/randombytes.git 27 | Homepage: https://github.com/crypto-browserify/randombytes 28 | 29 | --- 30 | 31 | Name: create-hash 32 | Version: 1.2.0 33 | License: MIT 34 | Private: false 35 | Description: create hashes for browserify 36 | Repository: git@github.com:crypto-browserify/createHash.git 37 | Homepage: https://github.com/crypto-browserify/createHash 38 | 39 | --- 40 | 41 | Name: browserify-cipher 42 | Version: 1.0.1 43 | License: MIT 44 | Private: false 45 | Description: ciphers for the browser 46 | Repository: git@github.com:crypto-browserify/browserify-cipher.git 47 | Author: Calvin Metcalf 48 | 49 | --- 50 | 51 | Name: pbkdf2 52 | Version: 3.0.17 53 | License: MIT 54 | Private: false 55 | Description: This library provides the functionality of PBKDF2 with the ability to use any supported hashing algorithm returned from crypto.getHashes() 56 | Repository: https://github.com/crypto-browserify/pbkdf2.git 57 | Homepage: https://github.com/crypto-browserify/pbkdf2 58 | Author: Daniel Cousens 59 | 60 | --- 61 | 62 | Name: diffie-hellman 63 | Version: 5.0.3 64 | License: MIT 65 | Private: false 66 | Description: pure js diffie-hellman 67 | Repository: https://github.com/crypto-browserify/diffie-hellman.git 68 | Homepage: https://github.com/crypto-browserify/diffie-hellman 69 | Author: Calvin Metcalf 70 | 71 | --- 72 | 73 | Name: create-hmac 74 | Version: 1.1.7 75 | License: MIT 76 | Private: false 77 | Description: node style hmacs in the browser 78 | Repository: https://github.com/crypto-browserify/createHmac.git 79 | Homepage: https://github.com/crypto-browserify/createHmac 80 | 81 | --- 82 | 83 | Name: create-ecdh 84 | Version: 4.0.3 85 | License: MIT 86 | Private: false 87 | Description: createECDH but browserifiable 88 | Repository: https://github.com/crypto-browserify/createECDH.git 89 | Homepage: https://github.com/crypto-browserify/createECDH 90 | Author: Calvin Metcalf 91 | 92 | --- 93 | 94 | Name: public-encrypt 95 | Version: 4.0.3 96 | License: MIT 97 | Private: false 98 | Description: browserify version of publicEncrypt & privateDecrypt 99 | Repository: https://github.com/crypto-browserify/publicEncrypt.git 100 | Homepage: https://github.com/crypto-browserify/publicEncrypt 101 | Author: Calvin Metcalf 102 | 103 | --- 104 | 105 | Name: randomfill 106 | Version: 1.0.4 107 | License: MIT 108 | Private: false 109 | Description: random fill from browserify stand alone 110 | Repository: https://github.com/crypto-browserify/randomfill.git 111 | Homepage: https://github.com/crypto-browserify/randomfill 112 | 113 | --- 114 | 115 | Name: browserify-des 116 | Version: 1.0.2 117 | License: MIT 118 | Private: false 119 | Repository: git+https://github.com/crypto-browserify/browserify-des.git 120 | Homepage: https://github.com/crypto-browserify/browserify-des#readme 121 | Author: Calvin Metcalf 122 | 123 | --- 124 | 125 | Name: browserify-aes 126 | Version: 1.2.0 127 | License: MIT 128 | Private: false 129 | Description: aes, for browserify 130 | Repository: git://github.com/crypto-browserify/browserify-aes.git 131 | Homepage: https://github.com/crypto-browserify/browserify-aes 132 | 133 | --- 134 | 135 | Name: safe-buffer 136 | Version: 5.1.2 137 | License: MIT 138 | Private: false 139 | Description: Safer Node.js Buffer API 140 | Repository: git://github.com/feross/safe-buffer.git 141 | Homepage: https://github.com/feross/safe-buffer 142 | Author: Feross Aboukhadijeh (http://feross.org) 143 | 144 | --- 145 | 146 | Name: md5.js 147 | Version: 1.3.5 148 | License: MIT 149 | Private: false 150 | Description: node style md5 on pure JavaScript 151 | Repository: https://github.com/crypto-browserify/md5.js.git 152 | Homepage: https://github.com/crypto-browserify/md5.js 153 | Author: Kirill Fomichev (https://github.com/fanatid) 154 | 155 | --- 156 | 157 | Name: inherits 158 | Version: 2.0.3 159 | License: ISC 160 | Private: false 161 | Description: Browser-friendly inheritance fully compatible with standard node.js inherits() 162 | Repository: undefined 163 | 164 | --- 165 | 166 | Name: cipher-base 167 | Version: 1.0.4 168 | License: MIT 169 | Private: false 170 | Description: abstract base class for crypto-streams 171 | Repository: git+https://github.com/crypto-browserify/cipher-base.git 172 | Homepage: https://github.com/crypto-browserify/cipher-base#readme 173 | Author: Calvin Metcalf 174 | 175 | --- 176 | 177 | Name: evp_bytestokey 178 | Version: 1.0.3 179 | License: MIT 180 | Private: false 181 | Description: The insecure key derivation algorithm from OpenSSL 182 | Repository: https://github.com/crypto-browserify/EVP_BytesToKey.git 183 | Homepage: https://github.com/crypto-browserify/EVP_BytesToKey 184 | Author: Calvin Metcalf 185 | Contributors: 186 | Kirill Fomichev 187 | 188 | --- 189 | 190 | Name: elliptic 191 | Version: 6.4.1 192 | License: MIT 193 | Private: false 194 | Description: EC cryptography 195 | Repository: git@github.com:indutny/elliptic 196 | Homepage: https://github.com/indutny/elliptic 197 | Author: Fedor Indutny 198 | 199 | --- 200 | 201 | Name: bn.js 202 | Version: 4.11.8 203 | License: MIT 204 | Private: false 205 | Description: Big number implementation in pure javascript 206 | Repository: git@github.com:indutny/bn.js 207 | Homepage: https://github.com/indutny/bn.js 208 | Author: Fedor Indutny 209 | 210 | --- 211 | 212 | Name: browserify-rsa 213 | Version: 4.0.1 214 | License: MIT 215 | Private: false 216 | Description: RSA for browserify 217 | Repository: git@github.com:crypto-browserify/browserify-rsa.git 218 | 219 | --- 220 | 221 | Name: parse-asn1 222 | Version: 5.1.4 223 | License: ISC 224 | Private: false 225 | Description: utility library for parsing asn1 files for use with browserify-sign. 226 | Repository: git://github.com/crypto-browserify/parse-asn1.git 227 | 228 | --- 229 | 230 | Name: ripemd160 231 | Version: 2.0.2 232 | License: MIT 233 | Private: false 234 | Description: Compute ripemd160 of bytes or strings. 235 | Repository: https://github.com/crypto-browserify/ripemd160 236 | 237 | --- 238 | 239 | Name: sha.js 240 | Version: 2.4.11 241 | License: (MIT AND BSD-3-Clause) 242 | Private: false 243 | Description: Streamable SHA hashes in pure javascript 244 | Repository: git://github.com/crypto-browserify/sha.js.git 245 | Homepage: https://github.com/crypto-browserify/sha.js 246 | Author: Dominic Tarr (dominictarr.com) 247 | 248 | --- 249 | 250 | Name: miller-rabin 251 | Version: 4.0.1 252 | License: MIT 253 | Private: false 254 | Description: Miller Rabin algorithm for primality test 255 | Repository: git@github.com:indutny/miller-rabin 256 | Homepage: https://github.com/indutny/miller-rabin 257 | Author: Fedor Indutny 258 | 259 | --- 260 | 261 | Name: des.js 262 | Version: 1.0.0 263 | License: MIT 264 | Private: false 265 | Description: DES implementation 266 | Repository: git+ssh://git@github.com/indutny/des.js.git 267 | Homepage: https://github.com/indutny/des.js#readme 268 | Author: Fedor Indutny 269 | 270 | --- 271 | 272 | Name: hash-base 273 | Version: 3.0.4 274 | License: MIT 275 | Private: false 276 | Description: abstract base class for hash-streams 277 | Repository: https://github.com/crypto-browserify/hash-base.git 278 | Homepage: https://github.com/crypto-browserify/hash-base 279 | Author: Kirill Fomichev (https://github.com/fanatid) 280 | 281 | --- 282 | 283 | Name: brorand 284 | Version: 1.1.0 285 | License: MIT 286 | Private: false 287 | Description: Random number generator for browsers and node.js 288 | Repository: git@github.com:indutny/brorand 289 | Homepage: https://github.com/indutny/brorand 290 | Author: Fedor Indutny 291 | 292 | --- 293 | 294 | Name: buffer-xor 295 | Version: 1.0.3 296 | License: MIT 297 | Private: false 298 | Description: A simple module for bitwise-xor on buffers 299 | Repository: https://github.com/crypto-browserify/buffer-xor.git 300 | Homepage: https://github.com/crypto-browserify/buffer-xor 301 | Author: Daniel Cousens 302 | 303 | --- 304 | 305 | Name: asn1.js 306 | Version: 4.10.1 307 | License: MIT 308 | Private: false 309 | Description: ASN.1 encoder and decoder 310 | Repository: git@github.com:indutny/asn1.js 311 | Homepage: https://github.com/indutny/asn1.js 312 | Author: Fedor Indutny 313 | 314 | --- 315 | 316 | Name: minimalistic-assert 317 | Version: 1.0.1 318 | License: ISC 319 | Private: false 320 | Description: minimalistic-assert === 321 | Repository: https://github.com/calvinmetcalf/minimalistic-assert.git 322 | Homepage: https://github.com/calvinmetcalf/minimalistic-assert 323 | 324 | --- 325 | 326 | Name: hash.js 327 | Version: 1.1.7 328 | License: MIT 329 | Private: false 330 | Description: Various hash functions that could be run by both browser and node 331 | Repository: git@github.com:indutny/hash.js 332 | Homepage: https://github.com/indutny/hash.js 333 | Author: Fedor Indutny 334 | 335 | --- 336 | 337 | Name: minimalistic-crypto-utils 338 | Version: 1.0.1 339 | License: MIT 340 | Private: false 341 | Description: Minimalistic tools for JS crypto modules 342 | Repository: git+ssh://git@github.com/indutny/minimalistic-crypto-utils.git 343 | Homepage: https://github.com/indutny/minimalistic-crypto-utils#readme 344 | Author: Fedor Indutny 345 | 346 | --- 347 | 348 | Name: hmac-drbg 349 | Version: 1.0.1 350 | License: MIT 351 | Private: false 352 | Description: Deterministic random bit generator (hmac) 353 | Repository: git+ssh://git@github.com/indutny/hmac-drbg.git 354 | Homepage: https://github.com/indutny/hmac-drbg#readme 355 | Author: Fedor Indutny -------------------------------------------------------------------------------- /polyfills/LICENSE-process-es6.txt: -------------------------------------------------------------------------------- 1 | Name: process-es6 2 | Version: 0.11.6 3 | License: MIT 4 | Private: false 5 | Description: process information for node.js and browsers, but in es6 6 | Repository: git://github.com/calvinmetcalf/node-process-es6.git 7 | Author: Roman Shtylman -------------------------------------------------------------------------------- /polyfills/console.js: -------------------------------------------------------------------------------- 1 | function noop(){} 2 | 3 | export default global.console ? global.console : { 4 | log: noop, 5 | info: noop, 6 | warn: noop, 7 | error: noop, 8 | dir: noop, 9 | assert: noop, 10 | time: noop, 11 | timeEnd: noop, 12 | trace: noop 13 | }; 14 | -------------------------------------------------------------------------------- /polyfills/domain.js: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | 4 |

License

5 | 6 | Unless stated otherwise all works are: 7 | 8 | 9 | 10 | and licensed under: 11 | 12 | 13 | 14 |

MIT License

15 | 16 |
 17 | 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:
 18 | 
 19 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
 20 | 
 21 | 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.
 22 | 
23 | 24 | 25 | */ 26 | /* 27 | modified by Calvin Metcalf to adhere to how the node one works a little better 28 | */ 29 | import {EventEmitter} from 'events'; 30 | import inherits from './inherits'; 31 | inherits(Domain, EventEmitter); 32 | function createEmitError(d) { 33 | return emitError; 34 | function emitError(e) { 35 | d.emit('error', e) 36 | } 37 | } 38 | 39 | export function Domain() { 40 | EventEmitter.call(this); 41 | this.__emitError = createEmitError(this); 42 | } 43 | Domain.prototype.add = function (emitter) { 44 | emitter.on('error', this.__emitError); 45 | } 46 | Domain.prototype.remove = function(emitter) { 47 | emitter.removeListener('error', this.__emitError) 48 | } 49 | Domain.prototype.bind = function(fn) { 50 | var emitError = this.__emitError; 51 | return function() { 52 | var args = Array.prototype.slice.call(arguments) 53 | try { 54 | fn.apply(null, args) 55 | } catch (err) { 56 | emitError(err) 57 | } 58 | } 59 | } 60 | Domain.prototype.intercept = function(fn) { 61 | var emitError = this.__emitError; 62 | return function(err) { 63 | if (err) { 64 | emitError(err) 65 | } else { 66 | var args = Array.prototype.slice.call(arguments, 1) 67 | try { 68 | fn.apply(null, args) 69 | } catch (err) { 70 | emitError(err) 71 | } 72 | } 73 | } 74 | } 75 | Domain.prototype.run = function(fn) { 76 | var emitError = this.__emitError; 77 | try { 78 | fn() 79 | } catch (err) { 80 | emitError(err) 81 | } 82 | return this 83 | } 84 | Domain.prototype.dispose = function() { 85 | this.removeAllListeners() 86 | return this 87 | } 88 | Domain.prototype.enter = Domain.prototype.exit = function() { 89 | return this 90 | } 91 | export function createDomain() { 92 | return new Domain(); 93 | } 94 | export var create = createDomain; 95 | 96 | export default { 97 | Domain: Domain, 98 | createDomain: createDomain, 99 | create: create 100 | } 101 | -------------------------------------------------------------------------------- /polyfills/empty.js: -------------------------------------------------------------------------------- 1 | export default {}; 2 | -------------------------------------------------------------------------------- /polyfills/events.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | var domain; 4 | 5 | // This constructor is used to store event handlers. Instantiating this is 6 | // faster than explicitly calling `Object.create(null)` to get a "clean" empty 7 | // object (tested with v8 v4.9). 8 | function EventHandlers() {} 9 | EventHandlers.prototype = Object.create(null); 10 | 11 | function EventEmitter() { 12 | EventEmitter.init.call(this); 13 | } 14 | export default EventEmitter; 15 | export {EventEmitter}; 16 | 17 | // nodejs oddity 18 | // require('events') === require('events').EventEmitter 19 | EventEmitter.EventEmitter = EventEmitter 20 | 21 | EventEmitter.usingDomains = false; 22 | 23 | EventEmitter.prototype.domain = undefined; 24 | EventEmitter.prototype._events = undefined; 25 | EventEmitter.prototype._maxListeners = undefined; 26 | 27 | // By default EventEmitters will print a warning if more than 10 listeners are 28 | // added to it. This is a useful default which helps finding memory leaks. 29 | EventEmitter.defaultMaxListeners = 10; 30 | 31 | EventEmitter.init = function() { 32 | this.domain = null; 33 | if (EventEmitter.usingDomains) { 34 | // if there is an active domain, then attach to it. 35 | if (domain.active && !(this instanceof domain.Domain)) { 36 | this.domain = domain.active; 37 | } 38 | } 39 | 40 | if (!this._events || this._events === Object.getPrototypeOf(this)._events) { 41 | this._events = new EventHandlers(); 42 | this._eventsCount = 0; 43 | } 44 | 45 | this._maxListeners = this._maxListeners || undefined; 46 | }; 47 | 48 | // Obviously not all Emitters should be limited to 10. This function allows 49 | // that to be increased. Set to zero for unlimited. 50 | EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) { 51 | if (typeof n !== 'number' || n < 0 || isNaN(n)) 52 | throw new TypeError('"n" argument must be a positive number'); 53 | this._maxListeners = n; 54 | return this; 55 | }; 56 | 57 | function $getMaxListeners(that) { 58 | if (that._maxListeners === undefined) 59 | return EventEmitter.defaultMaxListeners; 60 | return that._maxListeners; 61 | } 62 | 63 | EventEmitter.prototype.getMaxListeners = function getMaxListeners() { 64 | return $getMaxListeners(this); 65 | }; 66 | 67 | // These standalone emit* functions are used to optimize calling of event 68 | // handlers for fast cases because emit() itself often has a variable number of 69 | // arguments and can be deoptimized because of that. These functions always have 70 | // the same number of arguments and thus do not get deoptimized, so the code 71 | // inside them can execute faster. 72 | function emitNone(handler, isFn, self) { 73 | if (isFn) 74 | handler.call(self); 75 | else { 76 | var len = handler.length; 77 | var listeners = arrayClone(handler, len); 78 | for (var i = 0; i < len; ++i) 79 | listeners[i].call(self); 80 | } 81 | } 82 | function emitOne(handler, isFn, self, arg1) { 83 | if (isFn) 84 | handler.call(self, arg1); 85 | else { 86 | var len = handler.length; 87 | var listeners = arrayClone(handler, len); 88 | for (var i = 0; i < len; ++i) 89 | listeners[i].call(self, arg1); 90 | } 91 | } 92 | function emitTwo(handler, isFn, self, arg1, arg2) { 93 | if (isFn) 94 | handler.call(self, arg1, arg2); 95 | else { 96 | var len = handler.length; 97 | var listeners = arrayClone(handler, len); 98 | for (var i = 0; i < len; ++i) 99 | listeners[i].call(self, arg1, arg2); 100 | } 101 | } 102 | function emitThree(handler, isFn, self, arg1, arg2, arg3) { 103 | if (isFn) 104 | handler.call(self, arg1, arg2, arg3); 105 | else { 106 | var len = handler.length; 107 | var listeners = arrayClone(handler, len); 108 | for (var i = 0; i < len; ++i) 109 | listeners[i].call(self, arg1, arg2, arg3); 110 | } 111 | } 112 | 113 | function emitMany(handler, isFn, self, args) { 114 | if (isFn) 115 | handler.apply(self, args); 116 | else { 117 | var len = handler.length; 118 | var listeners = arrayClone(handler, len); 119 | for (var i = 0; i < len; ++i) 120 | listeners[i].apply(self, args); 121 | } 122 | } 123 | 124 | EventEmitter.prototype.emit = function emit(type) { 125 | var er, handler, len, args, i, events, domain; 126 | var needDomainExit = false; 127 | var doError = (type === 'error'); 128 | 129 | events = this._events; 130 | if (events) 131 | doError = (doError && events.error == null); 132 | else if (!doError) 133 | return false; 134 | 135 | domain = this.domain; 136 | 137 | // If there is no 'error' event listener then throw. 138 | if (doError) { 139 | er = arguments[1]; 140 | if (domain) { 141 | if (!er) 142 | er = new Error('Uncaught, unspecified "error" event'); 143 | er.domainEmitter = this; 144 | er.domain = domain; 145 | er.domainThrown = false; 146 | domain.emit('error', er); 147 | } else if (er instanceof Error) { 148 | throw er; // Unhandled 'error' event 149 | } else { 150 | // At least give some kind of context to the user 151 | var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); 152 | err.context = er; 153 | throw err; 154 | } 155 | return false; 156 | } 157 | 158 | handler = events[type]; 159 | 160 | if (!handler) 161 | return false; 162 | 163 | var isFn = typeof handler === 'function'; 164 | len = arguments.length; 165 | switch (len) { 166 | // fast cases 167 | case 1: 168 | emitNone(handler, isFn, this); 169 | break; 170 | case 2: 171 | emitOne(handler, isFn, this, arguments[1]); 172 | break; 173 | case 3: 174 | emitTwo(handler, isFn, this, arguments[1], arguments[2]); 175 | break; 176 | case 4: 177 | emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]); 178 | break; 179 | // slower 180 | default: 181 | args = new Array(len - 1); 182 | for (i = 1; i < len; i++) 183 | args[i - 1] = arguments[i]; 184 | emitMany(handler, isFn, this, args); 185 | } 186 | 187 | if (needDomainExit) 188 | domain.exit(); 189 | 190 | return true; 191 | }; 192 | 193 | function _addListener(target, type, listener, prepend) { 194 | var m; 195 | var events; 196 | var existing; 197 | 198 | if (typeof listener !== 'function') 199 | throw new TypeError('"listener" argument must be a function'); 200 | 201 | events = target._events; 202 | if (!events) { 203 | events = target._events = new EventHandlers(); 204 | target._eventsCount = 0; 205 | } else { 206 | // To avoid recursion in the case that type === "newListener"! Before 207 | // adding it to the listeners, first emit "newListener". 208 | if (events.newListener) { 209 | target.emit('newListener', type, 210 | listener.listener ? listener.listener : listener); 211 | 212 | // Re-assign `events` because a newListener handler could have caused the 213 | // this._events to be assigned to a new object 214 | events = target._events; 215 | } 216 | existing = events[type]; 217 | } 218 | 219 | if (!existing) { 220 | // Optimize the case of one listener. Don't need the extra array object. 221 | existing = events[type] = listener; 222 | ++target._eventsCount; 223 | } else { 224 | if (typeof existing === 'function') { 225 | // Adding the second element, need to change to array. 226 | existing = events[type] = prepend ? [listener, existing] : 227 | [existing, listener]; 228 | } else { 229 | // If we've already got an array, just append. 230 | if (prepend) { 231 | existing.unshift(listener); 232 | } else { 233 | existing.push(listener); 234 | } 235 | } 236 | 237 | // Check for listener leak 238 | if (!existing.warned) { 239 | m = $getMaxListeners(target); 240 | if (m && m > 0 && existing.length > m) { 241 | existing.warned = true; 242 | var w = new Error('Possible EventEmitter memory leak detected. ' + 243 | existing.length + ' ' + type + ' listeners added. ' + 244 | 'Use emitter.setMaxListeners() to increase limit'); 245 | w.name = 'MaxListenersExceededWarning'; 246 | w.emitter = target; 247 | w.type = type; 248 | w.count = existing.length; 249 | emitWarning(w); 250 | } 251 | } 252 | } 253 | 254 | return target; 255 | } 256 | function emitWarning(e) { 257 | typeof console.warn === 'function' ? console.warn(e) : console.log(e); 258 | } 259 | EventEmitter.prototype.addListener = function addListener(type, listener) { 260 | return _addListener(this, type, listener, false); 261 | }; 262 | 263 | EventEmitter.prototype.on = EventEmitter.prototype.addListener; 264 | 265 | EventEmitter.prototype.prependListener = 266 | function prependListener(type, listener) { 267 | return _addListener(this, type, listener, true); 268 | }; 269 | 270 | function _onceWrap(target, type, listener) { 271 | var fired = false; 272 | function g() { 273 | target.removeListener(type, g); 274 | if (!fired) { 275 | fired = true; 276 | listener.apply(target, arguments); 277 | } 278 | } 279 | g.listener = listener; 280 | return g; 281 | } 282 | 283 | EventEmitter.prototype.once = function once(type, listener) { 284 | if (typeof listener !== 'function') 285 | throw new TypeError('"listener" argument must be a function'); 286 | this.on(type, _onceWrap(this, type, listener)); 287 | return this; 288 | }; 289 | 290 | EventEmitter.prototype.prependOnceListener = 291 | function prependOnceListener(type, listener) { 292 | if (typeof listener !== 'function') 293 | throw new TypeError('"listener" argument must be a function'); 294 | this.prependListener(type, _onceWrap(this, type, listener)); 295 | return this; 296 | }; 297 | 298 | // emits a 'removeListener' event iff the listener was removed 299 | EventEmitter.prototype.removeListener = 300 | function removeListener(type, listener) { 301 | var list, events, position, i, originalListener; 302 | 303 | if (typeof listener !== 'function') 304 | throw new TypeError('"listener" argument must be a function'); 305 | 306 | events = this._events; 307 | if (!events) 308 | return this; 309 | 310 | list = events[type]; 311 | if (!list) 312 | return this; 313 | 314 | if (list === listener || (list.listener && list.listener === listener)) { 315 | if (--this._eventsCount === 0) 316 | this._events = new EventHandlers(); 317 | else { 318 | delete events[type]; 319 | if (events.removeListener) 320 | this.emit('removeListener', type, list.listener || listener); 321 | } 322 | } else if (typeof list !== 'function') { 323 | position = -1; 324 | 325 | for (i = list.length; i-- > 0;) { 326 | if (list[i] === listener || 327 | (list[i].listener && list[i].listener === listener)) { 328 | originalListener = list[i].listener; 329 | position = i; 330 | break; 331 | } 332 | } 333 | 334 | if (position < 0) 335 | return this; 336 | 337 | if (list.length === 1) { 338 | list[0] = undefined; 339 | if (--this._eventsCount === 0) { 340 | this._events = new EventHandlers(); 341 | return this; 342 | } else { 343 | delete events[type]; 344 | } 345 | } else { 346 | spliceOne(list, position); 347 | } 348 | 349 | if (events.removeListener) 350 | this.emit('removeListener', type, originalListener || listener); 351 | } 352 | 353 | return this; 354 | }; 355 | 356 | EventEmitter.prototype.removeAllListeners = 357 | function removeAllListeners(type) { 358 | var listeners, events; 359 | 360 | events = this._events; 361 | if (!events) 362 | return this; 363 | 364 | // not listening for removeListener, no need to emit 365 | if (!events.removeListener) { 366 | if (arguments.length === 0) { 367 | this._events = new EventHandlers(); 368 | this._eventsCount = 0; 369 | } else if (events[type]) { 370 | if (--this._eventsCount === 0) 371 | this._events = new EventHandlers(); 372 | else 373 | delete events[type]; 374 | } 375 | return this; 376 | } 377 | 378 | // emit removeListener for all listeners on all events 379 | if (arguments.length === 0) { 380 | var keys = Object.keys(events); 381 | for (var i = 0, key; i < keys.length; ++i) { 382 | key = keys[i]; 383 | if (key === 'removeListener') continue; 384 | this.removeAllListeners(key); 385 | } 386 | this.removeAllListeners('removeListener'); 387 | this._events = new EventHandlers(); 388 | this._eventsCount = 0; 389 | return this; 390 | } 391 | 392 | listeners = events[type]; 393 | 394 | if (typeof listeners === 'function') { 395 | this.removeListener(type, listeners); 396 | } else if (listeners) { 397 | // LIFO order 398 | do { 399 | this.removeListener(type, listeners[listeners.length - 1]); 400 | } while (listeners[0]); 401 | } 402 | 403 | return this; 404 | }; 405 | 406 | EventEmitter.prototype.listeners = function listeners(type) { 407 | var evlistener; 408 | var ret; 409 | var events = this._events; 410 | 411 | if (!events) 412 | ret = []; 413 | else { 414 | evlistener = events[type]; 415 | if (!evlistener) 416 | ret = []; 417 | else if (typeof evlistener === 'function') 418 | ret = [evlistener.listener || evlistener]; 419 | else 420 | ret = unwrapListeners(evlistener); 421 | } 422 | 423 | return ret; 424 | }; 425 | 426 | EventEmitter.listenerCount = function(emitter, type) { 427 | if (typeof emitter.listenerCount === 'function') { 428 | return emitter.listenerCount(type); 429 | } else { 430 | return listenerCount.call(emitter, type); 431 | } 432 | }; 433 | 434 | EventEmitter.prototype.listenerCount = listenerCount; 435 | function listenerCount(type) { 436 | var events = this._events; 437 | 438 | if (events) { 439 | var evlistener = events[type]; 440 | 441 | if (typeof evlistener === 'function') { 442 | return 1; 443 | } else if (evlistener) { 444 | return evlistener.length; 445 | } 446 | } 447 | 448 | return 0; 449 | } 450 | 451 | EventEmitter.prototype.eventNames = function eventNames() { 452 | return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : []; 453 | }; 454 | 455 | // About 1.5x faster than the two-arg version of Array#splice(). 456 | function spliceOne(list, index) { 457 | for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1) 458 | list[i] = list[k]; 459 | list.pop(); 460 | } 461 | 462 | function arrayClone(arr, i) { 463 | var copy = new Array(i); 464 | while (i--) 465 | copy[i] = arr[i]; 466 | return copy; 467 | } 468 | 469 | function unwrapListeners(arr) { 470 | var ret = new Array(arr.length); 471 | for (var i = 0; i < ret.length; ++i) { 472 | ret[i] = arr[i].listener || arr[i]; 473 | } 474 | return ret; 475 | } 476 | -------------------------------------------------------------------------------- /polyfills/global.js: -------------------------------------------------------------------------------- 1 | export default (typeof global !== "undefined" ? global : 2 | typeof self !== "undefined" ? self : 3 | typeof window !== "undefined" ? window : {}); -------------------------------------------------------------------------------- /polyfills/http-lib/capability.js: -------------------------------------------------------------------------------- 1 | export var hasFetch = isFunction(global.fetch) && isFunction(global.ReadableStream) 2 | 3 | var _blobConstructor; 4 | export function blobConstructor() { 5 | if (typeof _blobConstructor !== 'undefined') { 6 | return _blobConstructor; 7 | } 8 | try { 9 | new global.Blob([new ArrayBuffer(1)]) 10 | _blobConstructor = true 11 | } catch (e) { 12 | _blobConstructor = false 13 | } 14 | return _blobConstructor 15 | } 16 | var xhr; 17 | 18 | function checkTypeSupport(type) { 19 | if (!xhr) { 20 | xhr = new global.XMLHttpRequest() 21 | // If location.host is empty, e.g. if this page/worker was loaded 22 | // from a Blob, then use example.com to avoid an error 23 | xhr.open('GET', global.location.host ? '/' : 'https://example.com') 24 | } 25 | try { 26 | xhr.responseType = type 27 | return xhr.responseType === type 28 | } catch (e) { 29 | return false 30 | } 31 | 32 | } 33 | 34 | // For some strange reason, Safari 7.0 reports typeof global.ArrayBuffer === 'object'. 35 | // Safari 7.1 appears to have fixed this bug. 36 | var haveArrayBuffer = typeof global.ArrayBuffer !== 'undefined' 37 | var haveSlice = haveArrayBuffer && isFunction(global.ArrayBuffer.prototype.slice) 38 | 39 | export var arraybuffer = haveArrayBuffer && checkTypeSupport('arraybuffer') 40 | // These next two tests unavoidably show warnings in Chrome. Since fetch will always 41 | // be used if it's available, just return false for these to avoid the warnings. 42 | export var msstream = !hasFetch && haveSlice && checkTypeSupport('ms-stream') 43 | export var mozchunkedarraybuffer = !hasFetch && haveArrayBuffer && 44 | checkTypeSupport('moz-chunked-arraybuffer') 45 | export var overrideMimeType = isFunction(xhr.overrideMimeType) 46 | export var vbArray = isFunction(global.VBArray) 47 | 48 | function isFunction(value) { 49 | return typeof value === 'function' 50 | } 51 | 52 | xhr = null // Help gc 53 | -------------------------------------------------------------------------------- /polyfills/http-lib/request.js: -------------------------------------------------------------------------------- 1 | import * as capability from './capability'; 2 | import {inherits} from 'util'; 3 | import {IncomingMessage, readyStates as rStates} from './response'; 4 | import {Writable} from 'stream'; 5 | import toArrayBuffer from './to-arraybuffer'; 6 | 7 | function decideMode(preferBinary, useFetch) { 8 | if (capability.hasFetch && useFetch) { 9 | return 'fetch' 10 | } else if (capability.mozchunkedarraybuffer) { 11 | return 'moz-chunked-arraybuffer' 12 | } else if (capability.msstream) { 13 | return 'ms-stream' 14 | } else if (capability.arraybuffer && preferBinary) { 15 | return 'arraybuffer' 16 | } else if (capability.vbArray && preferBinary) { 17 | return 'text:vbarray' 18 | } else { 19 | return 'text' 20 | } 21 | } 22 | export default ClientRequest; 23 | 24 | function ClientRequest(opts) { 25 | var self = this 26 | Writable.call(self) 27 | 28 | self._opts = opts 29 | self._body = [] 30 | self._headers = {} 31 | if (opts.auth) 32 | self.setHeader('Authorization', 'Basic ' + new Buffer(opts.auth).toString('base64')) 33 | Object.keys(opts.headers).forEach(function(name) { 34 | self.setHeader(name, opts.headers[name]) 35 | }) 36 | 37 | var preferBinary 38 | var useFetch = true 39 | if (opts.mode === 'disable-fetch') { 40 | // If the use of XHR should be preferred and includes preserving the 'content-type' header 41 | useFetch = false 42 | preferBinary = true 43 | } else if (opts.mode === 'prefer-streaming') { 44 | // If streaming is a high priority but binary compatibility and 45 | // the accuracy of the 'content-type' header aren't 46 | preferBinary = false 47 | } else if (opts.mode === 'allow-wrong-content-type') { 48 | // If streaming is more important than preserving the 'content-type' header 49 | preferBinary = !capability.overrideMimeType 50 | } else if (!opts.mode || opts.mode === 'default' || opts.mode === 'prefer-fast') { 51 | // Use binary if text streaming may corrupt data or the content-type header, or for speed 52 | preferBinary = true 53 | } else { 54 | throw new Error('Invalid value for opts.mode') 55 | } 56 | self._mode = decideMode(preferBinary, useFetch) 57 | 58 | self.on('finish', function() { 59 | self._onFinish() 60 | }) 61 | } 62 | 63 | inherits(ClientRequest, Writable) 64 | // Taken from http://www.w3.org/TR/XMLHttpRequest/#the-setrequestheader%28%29-method 65 | var unsafeHeaders = [ 66 | 'accept-charset', 67 | 'accept-encoding', 68 | 'access-control-request-headers', 69 | 'access-control-request-method', 70 | 'connection', 71 | 'content-length', 72 | 'cookie', 73 | 'cookie2', 74 | 'date', 75 | 'dnt', 76 | 'expect', 77 | 'host', 78 | 'keep-alive', 79 | 'origin', 80 | 'referer', 81 | 'te', 82 | 'trailer', 83 | 'transfer-encoding', 84 | 'upgrade', 85 | 'user-agent', 86 | 'via' 87 | ] 88 | ClientRequest.prototype.setHeader = function(name, value) { 89 | var self = this 90 | var lowerName = name.toLowerCase() 91 | // This check is not necessary, but it prevents warnings from browsers about setting unsafe 92 | // headers. To be honest I'm not entirely sure hiding these warnings is a good thing, but 93 | // http-browserify did it, so I will too. 94 | if (unsafeHeaders.indexOf(lowerName) !== -1) 95 | return 96 | 97 | self._headers[lowerName] = { 98 | name: name, 99 | value: value 100 | } 101 | } 102 | 103 | ClientRequest.prototype.getHeader = function(name) { 104 | var self = this 105 | return self._headers[name.toLowerCase()].value 106 | } 107 | 108 | ClientRequest.prototype.removeHeader = function(name) { 109 | var self = this 110 | delete self._headers[name.toLowerCase()] 111 | } 112 | 113 | ClientRequest.prototype._onFinish = function() { 114 | var self = this 115 | 116 | if (self._destroyed) 117 | return 118 | var opts = self._opts 119 | 120 | var headersObj = self._headers 121 | var body 122 | if (opts.method === 'POST' || opts.method === 'PUT' || opts.method === 'PATCH') { 123 | if (capability.blobConstructor()) { 124 | body = new global.Blob(self._body.map(function(buffer) { 125 | return toArrayBuffer(buffer) 126 | }), { 127 | type: (headersObj['content-type'] || {}).value || '' 128 | }) 129 | } else { 130 | // get utf8 string 131 | body = Buffer.concat(self._body).toString() 132 | } 133 | } 134 | 135 | if (self._mode === 'fetch') { 136 | var headers = Object.keys(headersObj).map(function(name) { 137 | return [headersObj[name].name, headersObj[name].value] 138 | }) 139 | 140 | global.fetch(self._opts.url, { 141 | method: self._opts.method, 142 | headers: headers, 143 | body: body, 144 | mode: 'cors', 145 | credentials: opts.withCredentials ? 'include' : 'same-origin' 146 | }).then(function(response) { 147 | self._fetchResponse = response 148 | self._connect() 149 | }, function(reason) { 150 | self.emit('error', reason) 151 | }) 152 | } else { 153 | var xhr = self._xhr = new global.XMLHttpRequest() 154 | try { 155 | xhr.open(self._opts.method, self._opts.url, true) 156 | } catch (err) { 157 | process.nextTick(function() { 158 | self.emit('error', err) 159 | }) 160 | return 161 | } 162 | 163 | // Can't set responseType on really old browsers 164 | if ('responseType' in xhr) 165 | xhr.responseType = self._mode.split(':')[0] 166 | 167 | if ('withCredentials' in xhr) 168 | xhr.withCredentials = !!opts.withCredentials 169 | 170 | if (self._mode === 'text' && 'overrideMimeType' in xhr) 171 | xhr.overrideMimeType('text/plain; charset=x-user-defined') 172 | 173 | Object.keys(headersObj).forEach(function(name) { 174 | xhr.setRequestHeader(headersObj[name].name, headersObj[name].value) 175 | }) 176 | 177 | self._response = null 178 | xhr.onreadystatechange = function() { 179 | switch (xhr.readyState) { 180 | case rStates.LOADING: 181 | case rStates.DONE: 182 | self._onXHRProgress() 183 | break 184 | } 185 | } 186 | // Necessary for streaming in Firefox, since xhr.response is ONLY defined 187 | // in onprogress, not in onreadystatechange with xhr.readyState = 3 188 | if (self._mode === 'moz-chunked-arraybuffer') { 189 | xhr.onprogress = function() { 190 | self._onXHRProgress() 191 | } 192 | } 193 | 194 | xhr.onerror = function() { 195 | if (self._destroyed) 196 | return 197 | self.emit('error', new Error('XHR error')) 198 | } 199 | 200 | try { 201 | xhr.send(body) 202 | } catch (err) { 203 | process.nextTick(function() { 204 | self.emit('error', err) 205 | }) 206 | return 207 | } 208 | } 209 | } 210 | 211 | /** 212 | * Checks if xhr.status is readable and non-zero, indicating no error. 213 | * Even though the spec says it should be available in readyState 3, 214 | * accessing it throws an exception in IE8 215 | */ 216 | function statusValid(xhr) { 217 | try { 218 | var status = xhr.status 219 | return (status !== null && status !== 0) 220 | } catch (e) { 221 | return false 222 | } 223 | } 224 | 225 | ClientRequest.prototype._onXHRProgress = function() { 226 | var self = this 227 | 228 | if (!statusValid(self._xhr) || self._destroyed) 229 | return 230 | 231 | if (!self._response) 232 | self._connect() 233 | 234 | self._response._onXHRProgress() 235 | } 236 | 237 | ClientRequest.prototype._connect = function() { 238 | var self = this 239 | 240 | if (self._destroyed) 241 | return 242 | 243 | self._response = new IncomingMessage(self._xhr, self._fetchResponse, self._mode) 244 | self.emit('response', self._response) 245 | } 246 | 247 | ClientRequest.prototype._write = function(chunk, encoding, cb) { 248 | var self = this 249 | 250 | self._body.push(chunk) 251 | cb() 252 | } 253 | 254 | ClientRequest.prototype.abort = ClientRequest.prototype.destroy = function() { 255 | var self = this 256 | self._destroyed = true 257 | if (self._response) 258 | self._response._destroyed = true 259 | if (self._xhr) 260 | self._xhr.abort() 261 | // Currently, there isn't a way to truly abort a fetch. 262 | // If you like bikeshedding, see https://github.com/whatwg/fetch/issues/27 263 | } 264 | 265 | ClientRequest.prototype.end = function(data, encoding, cb) { 266 | var self = this 267 | if (typeof data === 'function') { 268 | cb = data 269 | data = undefined 270 | } 271 | 272 | Writable.prototype.end.call(self, data, encoding, cb) 273 | } 274 | 275 | ClientRequest.prototype.flushHeaders = function() {} 276 | ClientRequest.prototype.setTimeout = function() {} 277 | ClientRequest.prototype.setNoDelay = function() {} 278 | ClientRequest.prototype.setSocketKeepAlive = function() {} 279 | -------------------------------------------------------------------------------- /polyfills/http-lib/response.js: -------------------------------------------------------------------------------- 1 | import {overrideMimeType} from './capability'; 2 | import {inherits} from 'util'; 3 | import {Readable} from 'stream'; 4 | 5 | var rStates = { 6 | UNSENT: 0, 7 | OPENED: 1, 8 | HEADERS_RECEIVED: 2, 9 | LOADING: 3, 10 | DONE: 4 11 | } 12 | export { 13 | rStates as readyStates 14 | }; 15 | export function IncomingMessage(xhr, response, mode) { 16 | var self = this 17 | Readable.call(self) 18 | 19 | self._mode = mode 20 | self.headers = {} 21 | self.rawHeaders = [] 22 | self.trailers = {} 23 | self.rawTrailers = [] 24 | 25 | // Fake the 'close' event, but only once 'end' fires 26 | self.on('end', function() { 27 | // The nextTick is necessary to prevent the 'request' module from causing an infinite loop 28 | process.nextTick(function() { 29 | self.emit('close') 30 | }) 31 | }) 32 | var read; 33 | if (mode === 'fetch') { 34 | self._fetchResponse = response 35 | 36 | self.url = response.url 37 | self.statusCode = response.status 38 | self.statusMessage = response.statusText 39 | // backwards compatible version of for ( of ): 40 | // for (var ,_i,_it = [Symbol.iterator](); = (_i = _it.next()).value,!_i.done;) 41 | for (var header, _i, _it = response.headers[Symbol.iterator](); header = (_i = _it.next()).value, !_i.done;) { 42 | self.headers[header[0].toLowerCase()] = header[1] 43 | self.rawHeaders.push(header[0], header[1]) 44 | } 45 | 46 | // TODO: this doesn't respect backpressure. Once WritableStream is available, this can be fixed 47 | var reader = response.body.getReader() 48 | 49 | read = function () { 50 | reader.read().then(function(result) { 51 | if (self._destroyed) 52 | return 53 | if (result.done) { 54 | self.push(null) 55 | return 56 | } 57 | self.push(new Buffer(result.value)) 58 | read() 59 | }) 60 | } 61 | read() 62 | 63 | } else { 64 | self._xhr = xhr 65 | self._pos = 0 66 | 67 | self.url = xhr.responseURL 68 | self.statusCode = xhr.status 69 | self.statusMessage = xhr.statusText 70 | var headers = xhr.getAllResponseHeaders().split(/\r?\n/) 71 | headers.forEach(function(header) { 72 | var matches = header.match(/^([^:]+):\s*(.*)/) 73 | if (matches) { 74 | var key = matches[1].toLowerCase() 75 | if (key === 'set-cookie') { 76 | if (self.headers[key] === undefined) { 77 | self.headers[key] = [] 78 | } 79 | self.headers[key].push(matches[2]) 80 | } else if (self.headers[key] !== undefined) { 81 | self.headers[key] += ', ' + matches[2] 82 | } else { 83 | self.headers[key] = matches[2] 84 | } 85 | self.rawHeaders.push(matches[1], matches[2]) 86 | } 87 | }) 88 | 89 | self._charset = 'x-user-defined' 90 | if (!overrideMimeType) { 91 | var mimeType = self.rawHeaders['mime-type'] 92 | if (mimeType) { 93 | var charsetMatch = mimeType.match(/;\s*charset=([^;])(;|$)/) 94 | if (charsetMatch) { 95 | self._charset = charsetMatch[1].toLowerCase() 96 | } 97 | } 98 | if (!self._charset) 99 | self._charset = 'utf-8' // best guess 100 | } 101 | } 102 | } 103 | 104 | inherits(IncomingMessage, Readable) 105 | 106 | IncomingMessage.prototype._read = function() {} 107 | 108 | IncomingMessage.prototype._onXHRProgress = function() { 109 | var self = this 110 | 111 | var xhr = self._xhr 112 | 113 | var response = null 114 | switch (self._mode) { 115 | case 'text:vbarray': // For IE9 116 | if (xhr.readyState !== rStates.DONE) 117 | break 118 | try { 119 | // This fails in IE8 120 | response = new global.VBArray(xhr.responseBody).toArray() 121 | } catch (e) { 122 | // pass 123 | } 124 | if (response !== null) { 125 | self.push(new Buffer(response)) 126 | break 127 | } 128 | // Falls through in IE8 129 | case 'text': 130 | try { // This will fail when readyState = 3 in IE9. Switch mode and wait for readyState = 4 131 | response = xhr.responseText 132 | } catch (e) { 133 | self._mode = 'text:vbarray' 134 | break 135 | } 136 | if (response.length > self._pos) { 137 | var newData = response.substr(self._pos) 138 | if (self._charset === 'x-user-defined') { 139 | var buffer = new Buffer(newData.length) 140 | for (var i = 0; i < newData.length; i++) 141 | buffer[i] = newData.charCodeAt(i) & 0xff 142 | 143 | self.push(buffer) 144 | } else { 145 | self.push(newData, self._charset) 146 | } 147 | self._pos = response.length 148 | } 149 | break 150 | case 'arraybuffer': 151 | if (xhr.readyState !== rStates.DONE || !xhr.response) 152 | break 153 | response = xhr.response 154 | self.push(new Buffer(new Uint8Array(response))) 155 | break 156 | case 'moz-chunked-arraybuffer': // take whole 157 | response = xhr.response 158 | if (xhr.readyState !== rStates.LOADING || !response) 159 | break 160 | self.push(new Buffer(new Uint8Array(response))) 161 | break 162 | case 'ms-stream': 163 | response = xhr.response 164 | if (xhr.readyState !== rStates.LOADING) 165 | break 166 | var reader = new global.MSStreamReader() 167 | reader.onprogress = function() { 168 | if (reader.result.byteLength > self._pos) { 169 | self.push(new Buffer(new Uint8Array(reader.result.slice(self._pos)))) 170 | self._pos = reader.result.byteLength 171 | } 172 | } 173 | reader.onload = function() { 174 | self.push(null) 175 | } 176 | // reader.onerror = ??? // TODO: this 177 | reader.readAsArrayBuffer(response) 178 | break 179 | } 180 | 181 | // The ms-stream case handles end separately in reader.onload() 182 | if (self._xhr.readyState === rStates.DONE && self._mode !== 'ms-stream') { 183 | self.push(null) 184 | } 185 | } 186 | -------------------------------------------------------------------------------- /polyfills/http-lib/to-arraybuffer.js: -------------------------------------------------------------------------------- 1 | // from https://github.com/jhiesey/to-arraybuffer/blob/6502d9850e70ba7935a7df4ad86b358fc216f9f0/index.js 2 | 3 | // MIT License 4 | // Copyright (c) 2016 John Hiesey 5 | import {isBuffer} from 'buffer'; 6 | export default function (buf) { 7 | // If the buffer is backed by a Uint8Array, a faster version will work 8 | if (buf instanceof Uint8Array) { 9 | // If the buffer isn't a subarray, return the underlying ArrayBuffer 10 | if (buf.byteOffset === 0 && buf.byteLength === buf.buffer.byteLength) { 11 | return buf.buffer 12 | } else if (typeof buf.buffer.slice === 'function') { 13 | // Otherwise we need to get a proper copy 14 | return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength) 15 | } 16 | } 17 | 18 | if (isBuffer(buf)) { 19 | // This is the slow version that will work with any Buffer 20 | // implementation (even in old browsers) 21 | var arrayCopy = new Uint8Array(buf.length) 22 | var len = buf.length 23 | for (var i = 0; i < len; i++) { 24 | arrayCopy[i] = buf[i] 25 | } 26 | return arrayCopy.buffer 27 | } else { 28 | throw new Error('Argument must be a Buffer') 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /polyfills/http.js: -------------------------------------------------------------------------------- 1 | /* 2 | this and http-lib folder 3 | 4 | The MIT License 5 | 6 | Copyright (c) 2015 John Hiesey 7 | 8 | Permission is hereby granted, free of charge, 9 | to any person obtaining a copy of this software and 10 | associated documentation files (the "Software"), to 11 | deal in the Software without restriction, including 12 | without limitation the rights to use, copy, modify, 13 | merge, publish, distribute, sublicense, and/or sell 14 | copies of the Software, and to permit persons to whom 15 | the Software is furnished to do so, 16 | subject to the following conditions: 17 | 18 | The above copyright notice and this permission notice 19 | shall be included in all copies or substantial portions of the Software. 20 | 21 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 22 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES 23 | OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 24 | IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 25 | ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, 26 | TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 27 | SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 28 | 29 | */ 30 | import ClientRequest from './http-lib/request'; 31 | import {parse} from 'url'; 32 | 33 | export function request(opts, cb) { 34 | if (typeof opts === 'string') 35 | opts = parse(opts) 36 | 37 | 38 | // Normally, the page is loaded from http or https, so not specifying a protocol 39 | // will result in a (valid) protocol-relative url. However, this won't work if 40 | // the protocol is something else, like 'file:' 41 | var defaultProtocol = global.location.protocol.search(/^https?:$/) === -1 ? 'http:' : '' 42 | 43 | var protocol = opts.protocol || defaultProtocol 44 | var host = opts.hostname || opts.host 45 | var port = opts.port 46 | var path = opts.path || '/' 47 | 48 | // Necessary for IPv6 addresses 49 | if (host && host.indexOf(':') !== -1) 50 | host = '[' + host + ']' 51 | 52 | // This may be a relative url. The browser should always be able to interpret it correctly. 53 | opts.url = (host ? (protocol + '//' + host) : '') + (port ? ':' + port : '') + path 54 | opts.method = (opts.method || 'GET').toUpperCase() 55 | opts.headers = opts.headers || {} 56 | 57 | // Also valid opts.auth, opts.mode 58 | 59 | var req = new ClientRequest(opts) 60 | if (cb) 61 | req.on('response', cb) 62 | return req 63 | } 64 | 65 | export function get(opts, cb) { 66 | var req = request(opts, cb) 67 | req.end() 68 | return req 69 | } 70 | 71 | export function Agent() {} 72 | Agent.defaultMaxSockets = 4 73 | 74 | export var METHODS = [ 75 | 'CHECKOUT', 76 | 'CONNECT', 77 | 'COPY', 78 | 'DELETE', 79 | 'GET', 80 | 'HEAD', 81 | 'LOCK', 82 | 'M-SEARCH', 83 | 'MERGE', 84 | 'MKACTIVITY', 85 | 'MKCOL', 86 | 'MOVE', 87 | 'NOTIFY', 88 | 'OPTIONS', 89 | 'PATCH', 90 | 'POST', 91 | 'PROPFIND', 92 | 'PROPPATCH', 93 | 'PURGE', 94 | 'PUT', 95 | 'REPORT', 96 | 'SEARCH', 97 | 'SUBSCRIBE', 98 | 'TRACE', 99 | 'UNLOCK', 100 | 'UNSUBSCRIBE' 101 | ] 102 | export var STATUS_CODES = { 103 | 100: 'Continue', 104 | 101: 'Switching Protocols', 105 | 102: 'Processing', // RFC 2518, obsoleted by RFC 4918 106 | 200: 'OK', 107 | 201: 'Created', 108 | 202: 'Accepted', 109 | 203: 'Non-Authoritative Information', 110 | 204: 'No Content', 111 | 205: 'Reset Content', 112 | 206: 'Partial Content', 113 | 207: 'Multi-Status', // RFC 4918 114 | 300: 'Multiple Choices', 115 | 301: 'Moved Permanently', 116 | 302: 'Moved Temporarily', 117 | 303: 'See Other', 118 | 304: 'Not Modified', 119 | 305: 'Use Proxy', 120 | 307: 'Temporary Redirect', 121 | 400: 'Bad Request', 122 | 401: 'Unauthorized', 123 | 402: 'Payment Required', 124 | 403: 'Forbidden', 125 | 404: 'Not Found', 126 | 405: 'Method Not Allowed', 127 | 406: 'Not Acceptable', 128 | 407: 'Proxy Authentication Required', 129 | 408: 'Request Time-out', 130 | 409: 'Conflict', 131 | 410: 'Gone', 132 | 411: 'Length Required', 133 | 412: 'Precondition Failed', 134 | 413: 'Request Entity Too Large', 135 | 414: 'Request-URI Too Large', 136 | 415: 'Unsupported Media Type', 137 | 416: 'Requested Range Not Satisfiable', 138 | 417: 'Expectation Failed', 139 | 418: 'I\'m a teapot', // RFC 2324 140 | 422: 'Unprocessable Entity', // RFC 4918 141 | 423: 'Locked', // RFC 4918 142 | 424: 'Failed Dependency', // RFC 4918 143 | 425: 'Unordered Collection', // RFC 4918 144 | 426: 'Upgrade Required', // RFC 2817 145 | 428: 'Precondition Required', // RFC 6585 146 | 429: 'Too Many Requests', // RFC 6585 147 | 431: 'Request Header Fields Too Large', // RFC 6585 148 | 500: 'Internal Server Error', 149 | 501: 'Not Implemented', 150 | 502: 'Bad Gateway', 151 | 503: 'Service Unavailable', 152 | 504: 'Gateway Time-out', 153 | 505: 'HTTP Version Not Supported', 154 | 506: 'Variant Also Negotiates', // RFC 2295 155 | 507: 'Insufficient Storage', // RFC 4918 156 | 509: 'Bandwidth Limit Exceeded', 157 | 510: 'Not Extended', // RFC 2774 158 | 511: 'Network Authentication Required' // RFC 6585 159 | }; 160 | 161 | export default { 162 | request, 163 | get, 164 | Agent, 165 | METHODS, 166 | STATUS_CODES 167 | } 168 | -------------------------------------------------------------------------------- /polyfills/inherits.js: -------------------------------------------------------------------------------- 1 | 2 | var inherits; 3 | if (typeof Object.create === 'function'){ 4 | inherits = function inherits(ctor, superCtor) { 5 | // implementation from standard node.js 'util' module 6 | ctor.super_ = superCtor 7 | ctor.prototype = Object.create(superCtor.prototype, { 8 | constructor: { 9 | value: ctor, 10 | enumerable: false, 11 | writable: true, 12 | configurable: true 13 | } 14 | }); 15 | }; 16 | } else { 17 | inherits = function inherits(ctor, superCtor) { 18 | ctor.super_ = superCtor 19 | var TempCtor = function () {} 20 | TempCtor.prototype = superCtor.prototype 21 | ctor.prototype = new TempCtor() 22 | ctor.prototype.constructor = ctor 23 | } 24 | } 25 | export default inherits; 26 | -------------------------------------------------------------------------------- /polyfills/os.js: -------------------------------------------------------------------------------- 1 | /* 2 | The MIT License (MIT) 3 | 4 | Copyright (c) 2016 CoderPuppy 5 | 6 | Permission is hereby granted, free of charge, to any person obtaining a copy 7 | of this software and associated documentation files (the "Software"), to deal 8 | in the Software without restriction, including without limitation the rights 9 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | copies of the Software, and to permit persons to whom the Software is 11 | furnished to do so, subject to the following conditions: 12 | 13 | The above copyright notice and this permission notice shall be included in all 14 | copies or substantial portions of the Software. 15 | 16 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 22 | SOFTWARE. 23 | 24 | */ 25 | var _endianness; 26 | export function endianness() { 27 | if (typeof _endianness === 'undefined') { 28 | var a = new ArrayBuffer(2); 29 | var b = new Uint8Array(a); 30 | var c = new Uint16Array(a); 31 | b[0] = 1; 32 | b[1] = 2; 33 | if (c[0] === 258) { 34 | _endianness = 'BE'; 35 | } else if (c[0] === 513){ 36 | _endianness = 'LE'; 37 | } else { 38 | throw new Error('unable to figure out endianess'); 39 | } 40 | } 41 | return _endianness; 42 | } 43 | 44 | export function hostname() { 45 | if (typeof global.location !== 'undefined') { 46 | return global.location.hostname 47 | } else return ''; 48 | } 49 | 50 | export function loadavg() { 51 | return []; 52 | } 53 | 54 | export function uptime() { 55 | return 0; 56 | } 57 | 58 | export function freemem() { 59 | return Number.MAX_VALUE; 60 | } 61 | 62 | export function totalmem() { 63 | return Number.MAX_VALUE; 64 | } 65 | 66 | export function cpus() { 67 | return []; 68 | } 69 | 70 | export function type() { 71 | return 'Browser'; 72 | } 73 | 74 | export function release () { 75 | if (typeof global.navigator !== 'undefined') { 76 | return global.navigator.appVersion; 77 | } 78 | return ''; 79 | } 80 | 81 | export function networkInterfaces(){} 82 | export function getNetworkInterfaces(){} 83 | 84 | export function arch() { 85 | return 'javascript'; 86 | } 87 | 88 | export function platform() { 89 | return 'browser'; 90 | } 91 | 92 | export function tmpDir() { 93 | return '/tmp'; 94 | } 95 | export var tmpdir = tmpDir; 96 | 97 | export var EOL = '\n'; 98 | export default { 99 | EOL: EOL, 100 | tmpdir: tmpdir, 101 | tmpDir: tmpDir, 102 | networkInterfaces:networkInterfaces, 103 | getNetworkInterfaces: getNetworkInterfaces, 104 | release: release, 105 | type: type, 106 | cpus: cpus, 107 | totalmem: totalmem, 108 | freemem: freemem, 109 | uptime: uptime, 110 | loadavg: loadavg, 111 | hostname: hostname, 112 | endianness: endianness, 113 | } 114 | -------------------------------------------------------------------------------- /polyfills/path.js: -------------------------------------------------------------------------------- 1 | // Copyright Joyent, Inc. and other Node contributors. 2 | // 3 | // Permission is hereby granted, free of charge, to any person obtaining a 4 | // copy of this software and associated documentation files (the 5 | // "Software"), to deal in the Software without restriction, including 6 | // without limitation the rights to use, copy, modify, merge, publish, 7 | // distribute, sublicense, and/or sell copies of the Software, and to permit 8 | // persons to whom the Software is furnished to do so, subject to the 9 | // following conditions: 10 | // 11 | // The above copyright notice and this permission notice shall be included 12 | // in all copies or substantial portions of the Software. 13 | // 14 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS 15 | // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 16 | // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN 17 | // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 18 | // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 19 | // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE 20 | // USE OR OTHER DEALINGS IN THE SOFTWARE. 21 | 22 | // resolves . and .. elements in a path array with directory names there 23 | // must be no slashes, empty elements, or device names (c:\) in the array 24 | // (so also no leading and trailing slashes - it does not distinguish 25 | // relative and absolute paths) 26 | function normalizeArray(parts, allowAboveRoot) { 27 | // if the path tries to go above the root, `up` ends up > 0 28 | var up = 0; 29 | for (var i = parts.length - 1; i >= 0; i--) { 30 | var last = parts[i]; 31 | if (last === '.') { 32 | parts.splice(i, 1); 33 | } else if (last === '..') { 34 | parts.splice(i, 1); 35 | up++; 36 | } else if (up) { 37 | parts.splice(i, 1); 38 | up--; 39 | } 40 | } 41 | 42 | // if the path is allowed to go above the root, restore leading ..s 43 | if (allowAboveRoot) { 44 | for (; up--; up) { 45 | parts.unshift('..'); 46 | } 47 | } 48 | 49 | return parts; 50 | } 51 | 52 | // Split a filename into [root, dir, basename, ext], unix version 53 | // 'root' is just a slash, or nothing. 54 | var splitPathRe = 55 | /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/; 56 | var splitPath = function(filename) { 57 | return splitPathRe.exec(filename).slice(1); 58 | }; 59 | 60 | // path.resolve([from ...], to) 61 | // posix version 62 | export function resolve() { 63 | var resolvedPath = '', 64 | resolvedAbsolute = false; 65 | 66 | for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) { 67 | var path = (i >= 0) ? arguments[i] : '/'; 68 | 69 | // Skip empty and invalid entries 70 | if (typeof path !== 'string') { 71 | throw new TypeError('Arguments to path.resolve must be strings'); 72 | } else if (!path) { 73 | continue; 74 | } 75 | 76 | resolvedPath = path + '/' + resolvedPath; 77 | resolvedAbsolute = path.charAt(0) === '/'; 78 | } 79 | 80 | // At this point the path should be resolved to a full absolute path, but 81 | // handle relative paths to be safe (might happen when process.cwd() fails) 82 | 83 | // Normalize the path 84 | resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) { 85 | return !!p; 86 | }), !resolvedAbsolute).join('/'); 87 | 88 | return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.'; 89 | }; 90 | 91 | // path.normalize(path) 92 | // posix version 93 | export function normalize(path) { 94 | var isPathAbsolute = isAbsolute(path), 95 | trailingSlash = substr(path, -1) === '/'; 96 | 97 | // Normalize the path 98 | path = normalizeArray(filter(path.split('/'), function(p) { 99 | return !!p; 100 | }), !isPathAbsolute).join('/'); 101 | 102 | if (!path && !isPathAbsolute) { 103 | path = '.'; 104 | } 105 | if (path && trailingSlash) { 106 | path += '/'; 107 | } 108 | 109 | return (isPathAbsolute ? '/' : '') + path; 110 | }; 111 | 112 | // posix version 113 | export function isAbsolute(path) { 114 | return path.charAt(0) === '/'; 115 | } 116 | 117 | // posix version 118 | export function join() { 119 | var paths = Array.prototype.slice.call(arguments, 0); 120 | return normalize(filter(paths, function(p, index) { 121 | if (typeof p !== 'string') { 122 | throw new TypeError('Arguments to path.join must be strings'); 123 | } 124 | return p; 125 | }).join('/')); 126 | } 127 | 128 | 129 | // path.relative(from, to) 130 | // posix version 131 | export function relative(from, to) { 132 | from = resolve(from).substr(1); 133 | to = resolve(to).substr(1); 134 | 135 | function trim(arr) { 136 | var start = 0; 137 | for (; start < arr.length; start++) { 138 | if (arr[start] !== '') break; 139 | } 140 | 141 | var end = arr.length - 1; 142 | for (; end >= 0; end--) { 143 | if (arr[end] !== '') break; 144 | } 145 | 146 | if (start > end) return []; 147 | return arr.slice(start, end - start + 1); 148 | } 149 | 150 | var fromParts = trim(from.split('/')); 151 | var toParts = trim(to.split('/')); 152 | 153 | var length = Math.min(fromParts.length, toParts.length); 154 | var samePartsLength = length; 155 | for (var i = 0; i < length; i++) { 156 | if (fromParts[i] !== toParts[i]) { 157 | samePartsLength = i; 158 | break; 159 | } 160 | } 161 | 162 | var outputParts = []; 163 | for (var i = samePartsLength; i < fromParts.length; i++) { 164 | outputParts.push('..'); 165 | } 166 | 167 | outputParts = outputParts.concat(toParts.slice(samePartsLength)); 168 | 169 | return outputParts.join('/'); 170 | } 171 | 172 | export var sep = '/'; 173 | export var delimiter = ':'; 174 | 175 | export function dirname(path) { 176 | var result = splitPath(path), 177 | root = result[0], 178 | dir = result[1]; 179 | 180 | if (!root && !dir) { 181 | // No dirname whatsoever 182 | return '.'; 183 | } 184 | 185 | if (dir) { 186 | // It has a dirname, strip trailing slash 187 | dir = dir.substr(0, dir.length - 1); 188 | } 189 | 190 | return root + dir; 191 | } 192 | 193 | export function basename(path, ext) { 194 | var f = splitPath(path)[2]; 195 | // TODO: make this comparison case-insensitive on windows? 196 | if (ext && f.substr(-1 * ext.length) === ext) { 197 | f = f.substr(0, f.length - ext.length); 198 | } 199 | return f; 200 | } 201 | 202 | 203 | export function extname(path) { 204 | return splitPath(path)[3]; 205 | } 206 | export default { 207 | extname: extname, 208 | basename: basename, 209 | dirname: dirname, 210 | sep: sep, 211 | delimiter: delimiter, 212 | relative: relative, 213 | join: join, 214 | isAbsolute: isAbsolute, 215 | normalize: normalize, 216 | resolve: resolve 217 | }; 218 | function filter (xs, f) { 219 | if (xs.filter) return xs.filter(f); 220 | var res = []; 221 | for (var i = 0; i < xs.length; i++) { 222 | if (f(xs[i], i, xs)) res.push(xs[i]); 223 | } 224 | return res; 225 | } 226 | 227 | // String.prototype.substr - negative index don't work in IE8 228 | var substr = 'ab'.substr(-1) === 'b' ? 229 | function (str, start, len) { return str.substr(start, len) } : 230 | function (str, start, len) { 231 | if (start < 0) start = str.length + start; 232 | return str.substr(start, len); 233 | } 234 | ; 235 | -------------------------------------------------------------------------------- /polyfills/process-es6.js: -------------------------------------------------------------------------------- 1 | // shim for using process in browser 2 | // based off https://github.com/defunctzombie/node-process/blob/master/browser.js 3 | 4 | function defaultSetTimout() { 5 | throw new Error('setTimeout has not been defined'); 6 | } 7 | function defaultClearTimeout () { 8 | throw new Error('clearTimeout has not been defined'); 9 | } 10 | var cachedSetTimeout = defaultSetTimout; 11 | var cachedClearTimeout = defaultClearTimeout; 12 | if (typeof global.setTimeout === 'function') { 13 | cachedSetTimeout = setTimeout; 14 | } 15 | if (typeof global.clearTimeout === 'function') { 16 | cachedClearTimeout = clearTimeout; 17 | } 18 | 19 | function runTimeout(fun) { 20 | if (cachedSetTimeout === setTimeout) { 21 | //normal enviroments in sane situations 22 | return setTimeout(fun, 0); 23 | } 24 | // if setTimeout wasn't available but was latter defined 25 | if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { 26 | cachedSetTimeout = setTimeout; 27 | return setTimeout(fun, 0); 28 | } 29 | try { 30 | // when when somebody has screwed with setTimeout but no I.E. maddness 31 | return cachedSetTimeout(fun, 0); 32 | } catch(e){ 33 | try { 34 | // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally 35 | return cachedSetTimeout.call(null, fun, 0); 36 | } catch(e){ 37 | // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error 38 | return cachedSetTimeout.call(this, fun, 0); 39 | } 40 | } 41 | 42 | 43 | } 44 | function runClearTimeout(marker) { 45 | if (cachedClearTimeout === clearTimeout) { 46 | //normal enviroments in sane situations 47 | return clearTimeout(marker); 48 | } 49 | // if clearTimeout wasn't available but was latter defined 50 | if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { 51 | cachedClearTimeout = clearTimeout; 52 | return clearTimeout(marker); 53 | } 54 | try { 55 | // when when somebody has screwed with setTimeout but no I.E. maddness 56 | return cachedClearTimeout(marker); 57 | } catch (e){ 58 | try { 59 | // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally 60 | return cachedClearTimeout.call(null, marker); 61 | } catch (e){ 62 | // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. 63 | // Some versions of I.E. have different rules for clearTimeout vs setTimeout 64 | return cachedClearTimeout.call(this, marker); 65 | } 66 | } 67 | 68 | 69 | 70 | } 71 | var queue = []; 72 | var draining = false; 73 | var currentQueue; 74 | var queueIndex = -1; 75 | 76 | function cleanUpNextTick() { 77 | if (!draining || !currentQueue) { 78 | return; 79 | } 80 | draining = false; 81 | if (currentQueue.length) { 82 | queue = currentQueue.concat(queue); 83 | } else { 84 | queueIndex = -1; 85 | } 86 | if (queue.length) { 87 | drainQueue(); 88 | } 89 | } 90 | 91 | function drainQueue() { 92 | if (draining) { 93 | return; 94 | } 95 | var timeout = runTimeout(cleanUpNextTick); 96 | draining = true; 97 | 98 | var len = queue.length; 99 | while(len) { 100 | currentQueue = queue; 101 | queue = []; 102 | while (++queueIndex < len) { 103 | if (currentQueue) { 104 | currentQueue[queueIndex].run(); 105 | } 106 | } 107 | queueIndex = -1; 108 | len = queue.length; 109 | } 110 | currentQueue = null; 111 | draining = false; 112 | runClearTimeout(timeout); 113 | } 114 | function nextTick(fun) { 115 | var args = new Array(arguments.length - 1); 116 | if (arguments.length > 1) { 117 | for (var i = 1; i < arguments.length; i++) { 118 | args[i - 1] = arguments[i]; 119 | } 120 | } 121 | queue.push(new Item(fun, args)); 122 | if (queue.length === 1 && !draining) { 123 | runTimeout(drainQueue); 124 | } 125 | } 126 | // v8 likes predictible objects 127 | function Item(fun, array) { 128 | this.fun = fun; 129 | this.array = array; 130 | } 131 | Item.prototype.run = function () { 132 | this.fun.apply(null, this.array); 133 | }; 134 | var title = 'browser'; 135 | var platform = 'browser'; 136 | var browser = true; 137 | var env = {}; 138 | var argv = []; 139 | var version = ''; // empty string to avoid regexp issues 140 | var versions = {}; 141 | var release = {}; 142 | var config = {}; 143 | 144 | function noop() {} 145 | 146 | var on = noop; 147 | var addListener = noop; 148 | var once = noop; 149 | var off = noop; 150 | var removeListener = noop; 151 | var removeAllListeners = noop; 152 | var emit = noop; 153 | 154 | function binding(name) { 155 | throw new Error('process.binding is not supported'); 156 | } 157 | 158 | function cwd () { return '/' } 159 | function chdir (dir) { 160 | throw new Error('process.chdir is not supported'); 161 | }function umask() { return 0; } 162 | 163 | // from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js 164 | var performance = global.performance || {}; 165 | var performanceNow = 166 | performance.now || 167 | performance.mozNow || 168 | performance.msNow || 169 | performance.oNow || 170 | performance.webkitNow || 171 | function(){ return (new Date()).getTime() }; 172 | 173 | // generate timestamp or delta 174 | // see http://nodejs.org/api/process.html#process_process_hrtime 175 | function hrtime(previousTimestamp){ 176 | var clocktime = performanceNow.call(performance)*1e-3; 177 | var seconds = Math.floor(clocktime); 178 | var nanoseconds = Math.floor((clocktime%1)*1e9); 179 | if (previousTimestamp) { 180 | seconds = seconds - previousTimestamp[0]; 181 | nanoseconds = nanoseconds - previousTimestamp[1]; 182 | if (nanoseconds<0) { 183 | seconds--; 184 | nanoseconds += 1e9; 185 | } 186 | } 187 | return [seconds,nanoseconds] 188 | } 189 | 190 | var startTime = new Date(); 191 | function uptime() { 192 | var currentTime = new Date(); 193 | var dif = currentTime - startTime; 194 | return dif / 1000; 195 | } 196 | 197 | var browser$1 = { 198 | nextTick: nextTick, 199 | title: title, 200 | browser: browser, 201 | env: env, 202 | argv: argv, 203 | version: version, 204 | versions: versions, 205 | on: on, 206 | addListener: addListener, 207 | once: once, 208 | off: off, 209 | removeListener: removeListener, 210 | removeAllListeners: removeAllListeners, 211 | emit: emit, 212 | binding: binding, 213 | cwd: cwd, 214 | chdir: chdir, 215 | umask: umask, 216 | hrtime: hrtime, 217 | platform: platform, 218 | release: release, 219 | config: config, 220 | uptime: uptime 221 | }; 222 | 223 | export default browser$1; 224 | export { addListener, argv, binding, browser, chdir, config, cwd, emit, env, hrtime, nextTick, off, on, once, platform, release, removeAllListeners, removeListener, title, umask, uptime, version, versions }; 225 | -------------------------------------------------------------------------------- /polyfills/punycode.js: -------------------------------------------------------------------------------- 1 | /*! https://mths.be/punycode v1.4.1 by @mathias */ 2 | 3 | 4 | /** Highest positive signed 32-bit float value */ 5 | var maxInt = 2147483647; // aka. 0x7FFFFFFF or 2^31-1 6 | 7 | /** Bootstring parameters */ 8 | var base = 36; 9 | var tMin = 1; 10 | var tMax = 26; 11 | var skew = 38; 12 | var damp = 700; 13 | var initialBias = 72; 14 | var initialN = 128; // 0x80 15 | var delimiter = '-'; // '\x2D' 16 | 17 | /** Regular expressions */ 18 | var regexPunycode = /^xn--/; 19 | var regexNonASCII = /[^\x20-\x7E]/; // unprintable ASCII chars + non-ASCII chars 20 | var regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g; // RFC 3490 separators 21 | 22 | /** Error messages */ 23 | var errors = { 24 | 'overflow': 'Overflow: input needs wider integers to process', 25 | 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', 26 | 'invalid-input': 'Invalid input' 27 | }; 28 | 29 | /** Convenience shortcuts */ 30 | var baseMinusTMin = base - tMin; 31 | var floor = Math.floor; 32 | var stringFromCharCode = String.fromCharCode; 33 | 34 | /*--------------------------------------------------------------------------*/ 35 | 36 | /** 37 | * A generic error utility function. 38 | * @private 39 | * @param {String} type The error type. 40 | * @returns {Error} Throws a `RangeError` with the applicable error message. 41 | */ 42 | function error(type) { 43 | throw new RangeError(errors[type]); 44 | } 45 | 46 | /** 47 | * A generic `Array#map` utility function. 48 | * @private 49 | * @param {Array} array The array to iterate over. 50 | * @param {Function} callback The function that gets called for every array 51 | * item. 52 | * @returns {Array} A new array of values returned by the callback function. 53 | */ 54 | function map(array, fn) { 55 | var length = array.length; 56 | var result = []; 57 | while (length--) { 58 | result[length] = fn(array[length]); 59 | } 60 | return result; 61 | } 62 | 63 | /** 64 | * A simple `Array#map`-like wrapper to work with domain name strings or email 65 | * addresses. 66 | * @private 67 | * @param {String} domain The domain name or email address. 68 | * @param {Function} callback The function that gets called for every 69 | * character. 70 | * @returns {Array} A new string of characters returned by the callback 71 | * function. 72 | */ 73 | function mapDomain(string, fn) { 74 | var parts = string.split('@'); 75 | var result = ''; 76 | if (parts.length > 1) { 77 | // In email addresses, only the domain name should be punycoded. Leave 78 | // the local part (i.e. everything up to `@`) intact. 79 | result = parts[0] + '@'; 80 | string = parts[1]; 81 | } 82 | // Avoid `split(regex)` for IE8 compatibility. See #17. 83 | string = string.replace(regexSeparators, '\x2E'); 84 | var labels = string.split('.'); 85 | var encoded = map(labels, fn).join('.'); 86 | return result + encoded; 87 | } 88 | 89 | /** 90 | * Creates an array containing the numeric code points of each Unicode 91 | * character in the string. While JavaScript uses UCS-2 internally, 92 | * this function will convert a pair of surrogate halves (each of which 93 | * UCS-2 exposes as separate characters) into a single code point, 94 | * matching UTF-16. 95 | * @see `punycode.ucs2.encode` 96 | * @see 97 | * @memberOf punycode.ucs2 98 | * @name decode 99 | * @param {String} string The Unicode input string (UCS-2). 100 | * @returns {Array} The new array of code points. 101 | */ 102 | function ucs2decode(string) { 103 | var output = [], 104 | counter = 0, 105 | length = string.length, 106 | value, 107 | extra; 108 | while (counter < length) { 109 | value = string.charCodeAt(counter++); 110 | if (value >= 0xD800 && value <= 0xDBFF && counter < length) { 111 | // high surrogate, and there is a next character 112 | extra = string.charCodeAt(counter++); 113 | if ((extra & 0xFC00) == 0xDC00) { // low surrogate 114 | output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); 115 | } else { 116 | // unmatched surrogate; only append this code unit, in case the next 117 | // code unit is the high surrogate of a surrogate pair 118 | output.push(value); 119 | counter--; 120 | } 121 | } else { 122 | output.push(value); 123 | } 124 | } 125 | return output; 126 | } 127 | 128 | /** 129 | * Creates a string based on an array of numeric code points. 130 | * @see `punycode.ucs2.decode` 131 | * @memberOf punycode.ucs2 132 | * @name encode 133 | * @param {Array} codePoints The array of numeric code points. 134 | * @returns {String} The new Unicode string (UCS-2). 135 | */ 136 | function ucs2encode(array) { 137 | return map(array, function(value) { 138 | var output = ''; 139 | if (value > 0xFFFF) { 140 | value -= 0x10000; 141 | output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800); 142 | value = 0xDC00 | value & 0x3FF; 143 | } 144 | output += stringFromCharCode(value); 145 | return output; 146 | }).join(''); 147 | } 148 | 149 | /** 150 | * Converts a basic code point into a digit/integer. 151 | * @see `digitToBasic()` 152 | * @private 153 | * @param {Number} codePoint The basic numeric code point value. 154 | * @returns {Number} The numeric value of a basic code point (for use in 155 | * representing integers) in the range `0` to `base - 1`, or `base` if 156 | * the code point does not represent a value. 157 | */ 158 | function basicToDigit(codePoint) { 159 | if (codePoint - 48 < 10) { 160 | return codePoint - 22; 161 | } 162 | if (codePoint - 65 < 26) { 163 | return codePoint - 65; 164 | } 165 | if (codePoint - 97 < 26) { 166 | return codePoint - 97; 167 | } 168 | return base; 169 | } 170 | 171 | /** 172 | * Converts a digit/integer into a basic code point. 173 | * @see `basicToDigit()` 174 | * @private 175 | * @param {Number} digit The numeric value of a basic code point. 176 | * @returns {Number} The basic code point whose value (when used for 177 | * representing integers) is `digit`, which needs to be in the range 178 | * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is 179 | * used; else, the lowercase form is used. The behavior is undefined 180 | * if `flag` is non-zero and `digit` has no uppercase form. 181 | */ 182 | function digitToBasic(digit, flag) { 183 | // 0..25 map to ASCII a..z or A..Z 184 | // 26..35 map to ASCII 0..9 185 | return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); 186 | } 187 | 188 | /** 189 | * Bias adaptation function as per section 3.4 of RFC 3492. 190 | * https://tools.ietf.org/html/rfc3492#section-3.4 191 | * @private 192 | */ 193 | function adapt(delta, numPoints, firstTime) { 194 | var k = 0; 195 | delta = firstTime ? floor(delta / damp) : delta >> 1; 196 | delta += floor(delta / numPoints); 197 | for ( /* no initialization */ ; delta > baseMinusTMin * tMax >> 1; k += base) { 198 | delta = floor(delta / baseMinusTMin); 199 | } 200 | return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); 201 | } 202 | 203 | /** 204 | * Converts a Punycode string of ASCII-only symbols to a string of Unicode 205 | * symbols. 206 | * @memberOf punycode 207 | * @param {String} input The Punycode string of ASCII-only symbols. 208 | * @returns {String} The resulting string of Unicode symbols. 209 | */ 210 | export function decode(input) { 211 | // Don't use UCS-2 212 | var output = [], 213 | inputLength = input.length, 214 | out, 215 | i = 0, 216 | n = initialN, 217 | bias = initialBias, 218 | basic, 219 | j, 220 | index, 221 | oldi, 222 | w, 223 | k, 224 | digit, 225 | t, 226 | /** Cached calculation results */ 227 | baseMinusT; 228 | 229 | // Handle the basic code points: let `basic` be the number of input code 230 | // points before the last delimiter, or `0` if there is none, then copy 231 | // the first basic code points to the output. 232 | 233 | basic = input.lastIndexOf(delimiter); 234 | if (basic < 0) { 235 | basic = 0; 236 | } 237 | 238 | for (j = 0; j < basic; ++j) { 239 | // if it's not a basic code point 240 | if (input.charCodeAt(j) >= 0x80) { 241 | error('not-basic'); 242 | } 243 | output.push(input.charCodeAt(j)); 244 | } 245 | 246 | // Main decoding loop: start just after the last delimiter if any basic code 247 | // points were copied; start at the beginning otherwise. 248 | 249 | for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */ ) { 250 | 251 | // `index` is the index of the next character to be consumed. 252 | // Decode a generalized variable-length integer into `delta`, 253 | // which gets added to `i`. The overflow checking is easier 254 | // if we increase `i` as we go, then subtract off its starting 255 | // value at the end to obtain `delta`. 256 | for (oldi = i, w = 1, k = base; /* no condition */ ; k += base) { 257 | 258 | if (index >= inputLength) { 259 | error('invalid-input'); 260 | } 261 | 262 | digit = basicToDigit(input.charCodeAt(index++)); 263 | 264 | if (digit >= base || digit > floor((maxInt - i) / w)) { 265 | error('overflow'); 266 | } 267 | 268 | i += digit * w; 269 | t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); 270 | 271 | if (digit < t) { 272 | break; 273 | } 274 | 275 | baseMinusT = base - t; 276 | if (w > floor(maxInt / baseMinusT)) { 277 | error('overflow'); 278 | } 279 | 280 | w *= baseMinusT; 281 | 282 | } 283 | 284 | out = output.length + 1; 285 | bias = adapt(i - oldi, out, oldi == 0); 286 | 287 | // `i` was supposed to wrap around from `out` to `0`, 288 | // incrementing `n` each time, so we'll fix that now: 289 | if (floor(i / out) > maxInt - n) { 290 | error('overflow'); 291 | } 292 | 293 | n += floor(i / out); 294 | i %= out; 295 | 296 | // Insert `n` at position `i` of the output 297 | output.splice(i++, 0, n); 298 | 299 | } 300 | 301 | return ucs2encode(output); 302 | } 303 | 304 | /** 305 | * Converts a string of Unicode symbols (e.g. a domain name label) to a 306 | * Punycode string of ASCII-only symbols. 307 | * @memberOf punycode 308 | * @param {String} input The string of Unicode symbols. 309 | * @returns {String} The resulting Punycode string of ASCII-only symbols. 310 | */ 311 | export function encode(input) { 312 | var n, 313 | delta, 314 | handledCPCount, 315 | basicLength, 316 | bias, 317 | j, 318 | m, 319 | q, 320 | k, 321 | t, 322 | currentValue, 323 | output = [], 324 | /** `inputLength` will hold the number of code points in `input`. */ 325 | inputLength, 326 | /** Cached calculation results */ 327 | handledCPCountPlusOne, 328 | baseMinusT, 329 | qMinusT; 330 | 331 | // Convert the input in UCS-2 to Unicode 332 | input = ucs2decode(input); 333 | 334 | // Cache the length 335 | inputLength = input.length; 336 | 337 | // Initialize the state 338 | n = initialN; 339 | delta = 0; 340 | bias = initialBias; 341 | 342 | // Handle the basic code points 343 | for (j = 0; j < inputLength; ++j) { 344 | currentValue = input[j]; 345 | if (currentValue < 0x80) { 346 | output.push(stringFromCharCode(currentValue)); 347 | } 348 | } 349 | 350 | handledCPCount = basicLength = output.length; 351 | 352 | // `handledCPCount` is the number of code points that have been handled; 353 | // `basicLength` is the number of basic code points. 354 | 355 | // Finish the basic string - if it is not empty - with a delimiter 356 | if (basicLength) { 357 | output.push(delimiter); 358 | } 359 | 360 | // Main encoding loop: 361 | while (handledCPCount < inputLength) { 362 | 363 | // All non-basic code points < n have been handled already. Find the next 364 | // larger one: 365 | for (m = maxInt, j = 0; j < inputLength; ++j) { 366 | currentValue = input[j]; 367 | if (currentValue >= n && currentValue < m) { 368 | m = currentValue; 369 | } 370 | } 371 | 372 | // Increase `delta` enough to advance the decoder's state to , 373 | // but guard against overflow 374 | handledCPCountPlusOne = handledCPCount + 1; 375 | if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { 376 | error('overflow'); 377 | } 378 | 379 | delta += (m - n) * handledCPCountPlusOne; 380 | n = m; 381 | 382 | for (j = 0; j < inputLength; ++j) { 383 | currentValue = input[j]; 384 | 385 | if (currentValue < n && ++delta > maxInt) { 386 | error('overflow'); 387 | } 388 | 389 | if (currentValue == n) { 390 | // Represent delta as a generalized variable-length integer 391 | for (q = delta, k = base; /* no condition */ ; k += base) { 392 | t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); 393 | if (q < t) { 394 | break; 395 | } 396 | qMinusT = q - t; 397 | baseMinusT = base - t; 398 | output.push( 399 | stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)) 400 | ); 401 | q = floor(qMinusT / baseMinusT); 402 | } 403 | 404 | output.push(stringFromCharCode(digitToBasic(q, 0))); 405 | bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); 406 | delta = 0; 407 | ++handledCPCount; 408 | } 409 | } 410 | 411 | ++delta; 412 | ++n; 413 | 414 | } 415 | return output.join(''); 416 | } 417 | 418 | /** 419 | * Converts a Punycode string representing a domain name or an email address 420 | * to Unicode. Only the Punycoded parts of the input will be converted, i.e. 421 | * it doesn't matter if you call it on a string that has already been 422 | * converted to Unicode. 423 | * @memberOf punycode 424 | * @param {String} input The Punycoded domain name or email address to 425 | * convert to Unicode. 426 | * @returns {String} The Unicode representation of the given Punycode 427 | * string. 428 | */ 429 | export function toUnicode(input) { 430 | return mapDomain(input, function(string) { 431 | return regexPunycode.test(string) ? 432 | decode(string.slice(4).toLowerCase()) : 433 | string; 434 | }); 435 | } 436 | 437 | /** 438 | * Converts a Unicode string representing a domain name or an email address to 439 | * Punycode. Only the non-ASCII parts of the domain name will be converted, 440 | * i.e. it doesn't matter if you call it with a domain that's already in 441 | * ASCII. 442 | * @memberOf punycode 443 | * @param {String} input The domain name or email address to convert, as a 444 | * Unicode string. 445 | * @returns {String} The Punycode representation of the given domain name or 446 | * email address. 447 | */ 448 | export function toASCII(input) { 449 | return mapDomain(input, function(string) { 450 | return regexNonASCII.test(string) ? 451 | 'xn--' + encode(string) : 452 | string; 453 | }); 454 | } 455 | export var version = '1.4.1'; 456 | /** 457 | * An object of methods to convert from JavaScript's internal character 458 | * representation (UCS-2) to Unicode code points, and back. 459 | * @see 460 | * @memberOf punycode 461 | * @type Object 462 | */ 463 | 464 | export var ucs2 = { 465 | decode: ucs2decode, 466 | encode: ucs2encode 467 | }; 468 | export default { 469 | version: version, 470 | ucs2: ucs2, 471 | toASCII: toASCII, 472 | toUnicode: toUnicode, 473 | encode: encode, 474 | decode: decode 475 | } 476 | -------------------------------------------------------------------------------- /polyfills/qs.js: -------------------------------------------------------------------------------- 1 | // Copyright Joyent, Inc. and other Node contributors. 2 | // 3 | // Permission is hereby granted, free of charge, to any person obtaining a 4 | // copy of this software and associated documentation files (the 5 | // "Software"), to deal in the Software without restriction, including 6 | // without limitation the rights to use, copy, modify, merge, publish, 7 | // distribute, sublicense, and/or sell copies of the Software, and to permit 8 | // persons to whom the Software is furnished to do so, subject to the 9 | // following conditions: 10 | // 11 | // The above copyright notice and this permission notice shall be included 12 | // in all copies or substantial portions of the Software. 13 | // 14 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS 15 | // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 16 | // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN 17 | // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 18 | // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 19 | // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE 20 | // USE OR OTHER DEALINGS IN THE SOFTWARE. 21 | 22 | 23 | // If obj.hasOwnProperty has been overridden, then calling 24 | // obj.hasOwnProperty(prop) will break. 25 | // See: https://github.com/joyent/node/issues/1707 26 | function hasOwnProperty(obj, prop) { 27 | return Object.prototype.hasOwnProperty.call(obj, prop); 28 | } 29 | var isArray = Array.isArray || function (xs) { 30 | return Object.prototype.toString.call(xs) === '[object Array]'; 31 | }; 32 | function stringifyPrimitive(v) { 33 | switch (typeof v) { 34 | case 'string': 35 | return v; 36 | 37 | case 'boolean': 38 | return v ? 'true' : 'false'; 39 | 40 | case 'number': 41 | return isFinite(v) ? v : ''; 42 | 43 | default: 44 | return ''; 45 | } 46 | } 47 | 48 | export function stringify (obj, sep, eq, name) { 49 | sep = sep || '&'; 50 | eq = eq || '='; 51 | if (obj === null) { 52 | obj = undefined; 53 | } 54 | 55 | if (typeof obj === 'object') { 56 | return map(objectKeys(obj), function(k) { 57 | var ks = encodeURIComponent(stringifyPrimitive(k)) + eq; 58 | if (isArray(obj[k])) { 59 | return map(obj[k], function(v) { 60 | return ks + encodeURIComponent(stringifyPrimitive(v)); 61 | }).join(sep); 62 | } else { 63 | return ks + encodeURIComponent(stringifyPrimitive(obj[k])); 64 | } 65 | }).join(sep); 66 | 67 | } 68 | 69 | if (!name) return ''; 70 | return encodeURIComponent(stringifyPrimitive(name)) + eq + 71 | encodeURIComponent(stringifyPrimitive(obj)); 72 | }; 73 | 74 | function map (xs, f) { 75 | if (xs.map) return xs.map(f); 76 | var res = []; 77 | for (var i = 0; i < xs.length; i++) { 78 | res.push(f(xs[i], i)); 79 | } 80 | return res; 81 | } 82 | 83 | var objectKeys = Object.keys || function (obj) { 84 | var res = []; 85 | for (var key in obj) { 86 | if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key); 87 | } 88 | return res; 89 | }; 90 | 91 | export function parse(qs, sep, eq, options) { 92 | sep = sep || '&'; 93 | eq = eq || '='; 94 | var obj = {}; 95 | 96 | if (typeof qs !== 'string' || qs.length === 0) { 97 | return obj; 98 | } 99 | 100 | var regexp = /\+/g; 101 | qs = qs.split(sep); 102 | 103 | var maxKeys = 1000; 104 | if (options && typeof options.maxKeys === 'number') { 105 | maxKeys = options.maxKeys; 106 | } 107 | 108 | var len = qs.length; 109 | // maxKeys <= 0 means that we should not limit keys count 110 | if (maxKeys > 0 && len > maxKeys) { 111 | len = maxKeys; 112 | } 113 | 114 | for (var i = 0; i < len; ++i) { 115 | var x = qs[i].replace(regexp, '%20'), 116 | idx = x.indexOf(eq), 117 | kstr, vstr, k, v; 118 | 119 | if (idx >= 0) { 120 | kstr = x.substr(0, idx); 121 | vstr = x.substr(idx + 1); 122 | } else { 123 | kstr = x; 124 | vstr = ''; 125 | } 126 | 127 | k = decodeURIComponent(kstr); 128 | v = decodeURIComponent(vstr); 129 | 130 | if (!hasOwnProperty(obj, k)) { 131 | obj[k] = v; 132 | } else if (isArray(obj[k])) { 133 | obj[k].push(v); 134 | } else { 135 | obj[k] = [obj[k], v]; 136 | } 137 | } 138 | 139 | return obj; 140 | }; 141 | export default { 142 | encode: stringify, 143 | stringify: stringify, 144 | decode: parse, 145 | parse: parse 146 | } 147 | export {stringify as encode, parse as decode}; 148 | -------------------------------------------------------------------------------- /polyfills/readable-stream/buffer-list.js: -------------------------------------------------------------------------------- 1 | import {Buffer} from 'buffer'; 2 | 3 | export default BufferList; 4 | 5 | function BufferList() { 6 | this.head = null; 7 | this.tail = null; 8 | this.length = 0; 9 | } 10 | 11 | BufferList.prototype.push = function (v) { 12 | var entry = { data: v, next: null }; 13 | if (this.length > 0) this.tail.next = entry;else this.head = entry; 14 | this.tail = entry; 15 | ++this.length; 16 | }; 17 | 18 | BufferList.prototype.unshift = function (v) { 19 | var entry = { data: v, next: this.head }; 20 | if (this.length === 0) this.tail = entry; 21 | this.head = entry; 22 | ++this.length; 23 | }; 24 | 25 | BufferList.prototype.shift = function () { 26 | if (this.length === 0) return; 27 | var ret = this.head.data; 28 | if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; 29 | --this.length; 30 | return ret; 31 | }; 32 | 33 | BufferList.prototype.clear = function () { 34 | this.head = this.tail = null; 35 | this.length = 0; 36 | }; 37 | 38 | BufferList.prototype.join = function (s) { 39 | if (this.length === 0) return ''; 40 | var p = this.head; 41 | var ret = '' + p.data; 42 | while (p = p.next) { 43 | ret += s + p.data; 44 | }return ret; 45 | }; 46 | 47 | BufferList.prototype.concat = function (n) { 48 | if (this.length === 0) return Buffer.alloc(0); 49 | if (this.length === 1) return this.head.data; 50 | var ret = Buffer.allocUnsafe(n >>> 0); 51 | var p = this.head; 52 | var i = 0; 53 | while (p) { 54 | p.data.copy(ret, i); 55 | i += p.data.length; 56 | p = p.next; 57 | } 58 | return ret; 59 | }; 60 | -------------------------------------------------------------------------------- /polyfills/readable-stream/duplex.js: -------------------------------------------------------------------------------- 1 | 2 | import {inherits} from 'util'; 3 | import {nextTick} from 'process'; 4 | import {Readable} from './readable'; 5 | import {Writable} from './writable'; 6 | 7 | 8 | inherits(Duplex, Readable); 9 | 10 | var keys = Object.keys(Writable.prototype); 11 | for (var v = 0; v < keys.length; v++) { 12 | var method = keys[v]; 13 | if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; 14 | } 15 | export default Duplex; 16 | export function Duplex(options) { 17 | if (!(this instanceof Duplex)) return new Duplex(options); 18 | 19 | Readable.call(this, options); 20 | Writable.call(this, options); 21 | 22 | if (options && options.readable === false) this.readable = false; 23 | 24 | if (options && options.writable === false) this.writable = false; 25 | 26 | this.allowHalfOpen = true; 27 | if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; 28 | 29 | this.once('end', onend); 30 | } 31 | 32 | // the no-half-open enforcer 33 | function onend() { 34 | // if we allow half-open state, or if the writable side ended, 35 | // then we're ok. 36 | if (this.allowHalfOpen || this._writableState.ended) return; 37 | 38 | // no more data can be written. 39 | // But allow more writes to happen in this tick. 40 | nextTick(onEndNT, this); 41 | } 42 | 43 | function onEndNT(self) { 44 | self.end(); 45 | } 46 | -------------------------------------------------------------------------------- /polyfills/readable-stream/passthrough.js: -------------------------------------------------------------------------------- 1 | 2 | import {Transform} from './transform'; 3 | 4 | import {inherits} from 'util'; 5 | inherits(PassThrough, Transform); 6 | export default PassThrough; 7 | export function PassThrough(options) { 8 | if (!(this instanceof PassThrough)) return new PassThrough(options); 9 | 10 | Transform.call(this, options); 11 | } 12 | 13 | PassThrough.prototype._transform = function (chunk, encoding, cb) { 14 | cb(null, chunk); 15 | }; 16 | -------------------------------------------------------------------------------- /polyfills/readable-stream/transform.js: -------------------------------------------------------------------------------- 1 | // a transform stream is a readable/writable stream where you do 2 | // something with the data. Sometimes it's called a "filter", 3 | // but that's not a great name for it, since that implies a thing where 4 | // some bits pass through, and others are simply ignored. (That would 5 | // be a valid example of a transform, of course.) 6 | // 7 | // While the output is causally related to the input, it's not a 8 | // necessarily symmetric or synchronous transformation. For example, 9 | // a zlib stream might take multiple plain-text writes(), and then 10 | // emit a single compressed chunk some time in the future. 11 | // 12 | // Here's how this works: 13 | // 14 | // The Transform stream has all the aspects of the readable and writable 15 | // stream classes. When you write(chunk), that calls _write(chunk,cb) 16 | // internally, and returns false if there's a lot of pending writes 17 | // buffered up. When you call read(), that calls _read(n) until 18 | // there's enough pending readable data buffered up. 19 | // 20 | // In a transform stream, the written data is placed in a buffer. When 21 | // _read(n) is called, it transforms the queued up data, calling the 22 | // buffered _write cb's as it consumes chunks. If consuming a single 23 | // written chunk would result in multiple output chunks, then the first 24 | // outputted bit calls the readcb, and subsequent chunks just go into 25 | // the read buffer, and will cause it to emit 'readable' if necessary. 26 | // 27 | // This way, back-pressure is actually determined by the reading side, 28 | // since _read has to be called to start processing a new chunk. However, 29 | // a pathological inflate type of transform can cause excessive buffering 30 | // here. For example, imagine a stream where every byte of input is 31 | // interpreted as an integer from 0-255, and then results in that many 32 | // bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in 33 | // 1kb of data being output. In this case, you could write a very small 34 | // amount of input, and end up with a very large amount of output. In 35 | // such a pathological inflating mechanism, there'd be no way to tell 36 | // the system to stop doing the transform. A single 4MB write could 37 | // cause the system to run out of memory. 38 | // 39 | // However, even in such a pathological case, only a single written chunk 40 | // would be consumed, and then the rest would wait (un-transformed) until 41 | // the results of the previous transformed chunk were consumed. 42 | 43 | 44 | import {Duplex} from './duplex'; 45 | 46 | 47 | import {inherits} from 'util'; 48 | inherits(Transform, Duplex); 49 | 50 | function TransformState(stream) { 51 | this.afterTransform = function (er, data) { 52 | return afterTransform(stream, er, data); 53 | }; 54 | 55 | this.needTransform = false; 56 | this.transforming = false; 57 | this.writecb = null; 58 | this.writechunk = null; 59 | this.writeencoding = null; 60 | } 61 | 62 | function afterTransform(stream, er, data) { 63 | var ts = stream._transformState; 64 | ts.transforming = false; 65 | 66 | var cb = ts.writecb; 67 | 68 | if (!cb) return stream.emit('error', new Error('no writecb in Transform class')); 69 | 70 | ts.writechunk = null; 71 | ts.writecb = null; 72 | 73 | if (data !== null && data !== undefined) stream.push(data); 74 | 75 | cb(er); 76 | 77 | var rs = stream._readableState; 78 | rs.reading = false; 79 | if (rs.needReadable || rs.length < rs.highWaterMark) { 80 | stream._read(rs.highWaterMark); 81 | } 82 | } 83 | export default Transform; 84 | export function Transform(options) { 85 | if (!(this instanceof Transform)) return new Transform(options); 86 | 87 | Duplex.call(this, options); 88 | 89 | this._transformState = new TransformState(this); 90 | 91 | // when the writable side finishes, then flush out anything remaining. 92 | var stream = this; 93 | 94 | // start out asking for a readable event once data is transformed. 95 | this._readableState.needReadable = true; 96 | 97 | // we have implemented the _read method, and done the other things 98 | // that Readable wants before the first _read call, so unset the 99 | // sync guard flag. 100 | this._readableState.sync = false; 101 | 102 | if (options) { 103 | if (typeof options.transform === 'function') this._transform = options.transform; 104 | 105 | if (typeof options.flush === 'function') this._flush = options.flush; 106 | } 107 | 108 | this.once('prefinish', function () { 109 | if (typeof this._flush === 'function') this._flush(function (er) { 110 | done(stream, er); 111 | });else done(stream); 112 | }); 113 | } 114 | 115 | Transform.prototype.push = function (chunk, encoding) { 116 | this._transformState.needTransform = false; 117 | return Duplex.prototype.push.call(this, chunk, encoding); 118 | }; 119 | 120 | // This is the part where you do stuff! 121 | // override this function in implementation classes. 122 | // 'chunk' is an input chunk. 123 | // 124 | // Call `push(newChunk)` to pass along transformed output 125 | // to the readable side. You may call 'push' zero or more times. 126 | // 127 | // Call `cb(err)` when you are done with this chunk. If you pass 128 | // an error, then that'll put the hurt on the whole operation. If you 129 | // never call cb(), then you'll never get another chunk. 130 | Transform.prototype._transform = function (chunk, encoding, cb) { 131 | throw new Error('Not implemented'); 132 | }; 133 | 134 | Transform.prototype._write = function (chunk, encoding, cb) { 135 | var ts = this._transformState; 136 | ts.writecb = cb; 137 | ts.writechunk = chunk; 138 | ts.writeencoding = encoding; 139 | if (!ts.transforming) { 140 | var rs = this._readableState; 141 | if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); 142 | } 143 | }; 144 | 145 | // Doesn't matter what the args are here. 146 | // _transform does all the work. 147 | // That we got here means that the readable side wants more data. 148 | Transform.prototype._read = function (n) { 149 | var ts = this._transformState; 150 | 151 | if (ts.writechunk !== null && ts.writecb && !ts.transforming) { 152 | ts.transforming = true; 153 | this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); 154 | } else { 155 | // mark that we need a transform, so that any data that comes in 156 | // will get processed, now that we've asked for it. 157 | ts.needTransform = true; 158 | } 159 | }; 160 | 161 | function done(stream, er) { 162 | if (er) return stream.emit('error', er); 163 | 164 | // if there's nothing in the write buffer, then that means 165 | // that nothing more will ever be provided 166 | var ws = stream._writableState; 167 | var ts = stream._transformState; 168 | 169 | if (ws.length) throw new Error('Calling transform done when ws.length != 0'); 170 | 171 | if (ts.transforming) throw new Error('Calling transform done when still transforming'); 172 | 173 | return stream.push(null); 174 | } 175 | -------------------------------------------------------------------------------- /polyfills/readable-stream/writable.js: -------------------------------------------------------------------------------- 1 | // A bit simpler than readable streams. 2 | // Implement an async ._write(chunk, encoding, cb), and it'll handle all 3 | // the drain event emission and buffering. 4 | 5 | 6 | import {inherits, deprecate} from 'util'; 7 | import {Buffer} from 'buffer'; 8 | Writable.WritableState = WritableState; 9 | import {EventEmitter} from 'events'; 10 | import {Duplex} from './duplex'; 11 | import {nextTick} from 'process'; 12 | inherits(Writable, EventEmitter); 13 | 14 | function nop() {} 15 | 16 | function WriteReq(chunk, encoding, cb) { 17 | this.chunk = chunk; 18 | this.encoding = encoding; 19 | this.callback = cb; 20 | this.next = null; 21 | } 22 | 23 | function WritableState(options, stream) { 24 | Object.defineProperty(this, 'buffer', { 25 | get: deprecate(function () { 26 | return this.getBuffer(); 27 | }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.') 28 | }); 29 | options = options || {}; 30 | 31 | // object stream flag to indicate whether or not this stream 32 | // contains buffers or objects. 33 | this.objectMode = !!options.objectMode; 34 | 35 | if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode; 36 | 37 | // the point at which write() starts returning false 38 | // Note: 0 is a valid value, means that we always return false if 39 | // the entire buffer is not flushed immediately on write() 40 | var hwm = options.highWaterMark; 41 | var defaultHwm = this.objectMode ? 16 : 16 * 1024; 42 | this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; 43 | 44 | // cast to ints. 45 | this.highWaterMark = ~ ~this.highWaterMark; 46 | 47 | this.needDrain = false; 48 | // at the start of calling end() 49 | this.ending = false; 50 | // when end() has been called, and returned 51 | this.ended = false; 52 | // when 'finish' is emitted 53 | this.finished = false; 54 | 55 | // should we decode strings into buffers before passing to _write? 56 | // this is here so that some node-core streams can optimize string 57 | // handling at a lower level. 58 | var noDecode = options.decodeStrings === false; 59 | this.decodeStrings = !noDecode; 60 | 61 | // Crypto is kind of old and crusty. Historically, its default string 62 | // encoding is 'binary' so we have to make this configurable. 63 | // Everything else in the universe uses 'utf8', though. 64 | this.defaultEncoding = options.defaultEncoding || 'utf8'; 65 | 66 | // not an actual buffer we keep track of, but a measurement 67 | // of how much we're waiting to get pushed to some underlying 68 | // socket or file. 69 | this.length = 0; 70 | 71 | // a flag to see when we're in the middle of a write. 72 | this.writing = false; 73 | 74 | // when true all writes will be buffered until .uncork() call 75 | this.corked = 0; 76 | 77 | // a flag to be able to tell if the onwrite cb is called immediately, 78 | // or on a later tick. We set this to true at first, because any 79 | // actions that shouldn't happen until "later" should generally also 80 | // not happen before the first write call. 81 | this.sync = true; 82 | 83 | // a flag to know if we're processing previously buffered items, which 84 | // may call the _write() callback in the same tick, so that we don't 85 | // end up in an overlapped onwrite situation. 86 | this.bufferProcessing = false; 87 | 88 | // the callback that's passed to _write(chunk,cb) 89 | this.onwrite = function (er) { 90 | onwrite(stream, er); 91 | }; 92 | 93 | // the callback that the user supplies to write(chunk,encoding,cb) 94 | this.writecb = null; 95 | 96 | // the amount that is being written when _write is called. 97 | this.writelen = 0; 98 | 99 | this.bufferedRequest = null; 100 | this.lastBufferedRequest = null; 101 | 102 | // number of pending user-supplied write callbacks 103 | // this must be 0 before 'finish' can be emitted 104 | this.pendingcb = 0; 105 | 106 | // emit prefinish if the only thing we're waiting for is _write cbs 107 | // This is relevant for synchronous Transform streams 108 | this.prefinished = false; 109 | 110 | // True if the error was already emitted and should not be thrown again 111 | this.errorEmitted = false; 112 | 113 | // count buffered requests 114 | this.bufferedRequestCount = 0; 115 | 116 | // allocate the first CorkedRequest, there is always 117 | // one allocated and free to use, and we maintain at most two 118 | this.corkedRequestsFree = new CorkedRequest(this); 119 | } 120 | 121 | WritableState.prototype.getBuffer = function writableStateGetBuffer() { 122 | var current = this.bufferedRequest; 123 | var out = []; 124 | while (current) { 125 | out.push(current); 126 | current = current.next; 127 | } 128 | return out; 129 | }; 130 | 131 | export default Writable; 132 | export function Writable(options) { 133 | 134 | // Writable ctor is applied to Duplexes, though they're not 135 | // instanceof Writable, they're instanceof Readable. 136 | if (!(this instanceof Writable) && !(this instanceof Duplex)) return new Writable(options); 137 | 138 | this._writableState = new WritableState(options, this); 139 | 140 | // legacy. 141 | this.writable = true; 142 | 143 | if (options) { 144 | if (typeof options.write === 'function') this._write = options.write; 145 | 146 | if (typeof options.writev === 'function') this._writev = options.writev; 147 | } 148 | 149 | EventEmitter.call(this); 150 | } 151 | 152 | // Otherwise people can pipe Writable streams, which is just wrong. 153 | Writable.prototype.pipe = function () { 154 | this.emit('error', new Error('Cannot pipe, not readable')); 155 | }; 156 | 157 | function writeAfterEnd(stream, cb) { 158 | var er = new Error('write after end'); 159 | // TODO: defer error events consistently everywhere, not just the cb 160 | stream.emit('error', er); 161 | nextTick(cb, er); 162 | } 163 | 164 | // If we get something that is not a buffer, string, null, or undefined, 165 | // and we're not in objectMode, then that's an error. 166 | // Otherwise stream chunks are all considered to be of length=1, and the 167 | // watermarks determine how many objects to keep in the buffer, rather than 168 | // how many bytes or characters. 169 | function validChunk(stream, state, chunk, cb) { 170 | var valid = true; 171 | var er = false; 172 | // Always throw error if a null is written 173 | // if we are not in object mode then throw 174 | // if it is not a buffer, string, or undefined. 175 | if (chunk === null) { 176 | er = new TypeError('May not write null values to stream'); 177 | } else if (!Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { 178 | er = new TypeError('Invalid non-string/buffer chunk'); 179 | } 180 | if (er) { 181 | stream.emit('error', er); 182 | nextTick(cb, er); 183 | valid = false; 184 | } 185 | return valid; 186 | } 187 | 188 | Writable.prototype.write = function (chunk, encoding, cb) { 189 | var state = this._writableState; 190 | var ret = false; 191 | 192 | if (typeof encoding === 'function') { 193 | cb = encoding; 194 | encoding = null; 195 | } 196 | 197 | if (Buffer.isBuffer(chunk)) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; 198 | 199 | if (typeof cb !== 'function') cb = nop; 200 | 201 | if (state.ended) writeAfterEnd(this, cb);else if (validChunk(this, state, chunk, cb)) { 202 | state.pendingcb++; 203 | ret = writeOrBuffer(this, state, chunk, encoding, cb); 204 | } 205 | 206 | return ret; 207 | }; 208 | 209 | Writable.prototype.cork = function () { 210 | var state = this._writableState; 211 | 212 | state.corked++; 213 | }; 214 | 215 | Writable.prototype.uncork = function () { 216 | var state = this._writableState; 217 | 218 | if (state.corked) { 219 | state.corked--; 220 | 221 | if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); 222 | } 223 | }; 224 | 225 | Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { 226 | // node::ParseEncoding() requires lower case. 227 | if (typeof encoding === 'string') encoding = encoding.toLowerCase(); 228 | if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding); 229 | this._writableState.defaultEncoding = encoding; 230 | return this; 231 | }; 232 | 233 | function decodeChunk(state, chunk, encoding) { 234 | if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { 235 | chunk = Buffer.from(chunk, encoding); 236 | } 237 | return chunk; 238 | } 239 | 240 | // if we're already writing something, then just put this 241 | // in the queue, and wait our turn. Otherwise, call _write 242 | // If we return false, then we need a drain event, so set that flag. 243 | function writeOrBuffer(stream, state, chunk, encoding, cb) { 244 | chunk = decodeChunk(state, chunk, encoding); 245 | 246 | if (Buffer.isBuffer(chunk)) encoding = 'buffer'; 247 | var len = state.objectMode ? 1 : chunk.length; 248 | 249 | state.length += len; 250 | 251 | var ret = state.length < state.highWaterMark; 252 | // we must ensure that previous needDrain will not be reset to false. 253 | if (!ret) state.needDrain = true; 254 | 255 | if (state.writing || state.corked) { 256 | var last = state.lastBufferedRequest; 257 | state.lastBufferedRequest = new WriteReq(chunk, encoding, cb); 258 | if (last) { 259 | last.next = state.lastBufferedRequest; 260 | } else { 261 | state.bufferedRequest = state.lastBufferedRequest; 262 | } 263 | state.bufferedRequestCount += 1; 264 | } else { 265 | doWrite(stream, state, false, len, chunk, encoding, cb); 266 | } 267 | 268 | return ret; 269 | } 270 | 271 | function doWrite(stream, state, writev, len, chunk, encoding, cb) { 272 | state.writelen = len; 273 | state.writecb = cb; 274 | state.writing = true; 275 | state.sync = true; 276 | if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); 277 | state.sync = false; 278 | } 279 | 280 | function onwriteError(stream, state, sync, er, cb) { 281 | --state.pendingcb; 282 | if (sync) nextTick(cb, er);else cb(er); 283 | 284 | stream._writableState.errorEmitted = true; 285 | stream.emit('error', er); 286 | } 287 | 288 | function onwriteStateUpdate(state) { 289 | state.writing = false; 290 | state.writecb = null; 291 | state.length -= state.writelen; 292 | state.writelen = 0; 293 | } 294 | 295 | function onwrite(stream, er) { 296 | var state = stream._writableState; 297 | var sync = state.sync; 298 | var cb = state.writecb; 299 | 300 | onwriteStateUpdate(state); 301 | 302 | if (er) onwriteError(stream, state, sync, er, cb);else { 303 | // Check if we're actually ready to finish, but don't emit yet 304 | var finished = needFinish(state); 305 | 306 | if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { 307 | clearBuffer(stream, state); 308 | } 309 | 310 | if (sync) { 311 | /**/ 312 | nextTick(afterWrite, stream, state, finished, cb); 313 | /**/ 314 | } else { 315 | afterWrite(stream, state, finished, cb); 316 | } 317 | } 318 | } 319 | 320 | function afterWrite(stream, state, finished, cb) { 321 | if (!finished) onwriteDrain(stream, state); 322 | state.pendingcb--; 323 | cb(); 324 | finishMaybe(stream, state); 325 | } 326 | 327 | // Must force callback to be called on nextTick, so that we don't 328 | // emit 'drain' before the write() consumer gets the 'false' return 329 | // value, and has a chance to attach a 'drain' listener. 330 | function onwriteDrain(stream, state) { 331 | if (state.length === 0 && state.needDrain) { 332 | state.needDrain = false; 333 | stream.emit('drain'); 334 | } 335 | } 336 | 337 | // if there's something in the buffer waiting, then process it 338 | function clearBuffer(stream, state) { 339 | state.bufferProcessing = true; 340 | var entry = state.bufferedRequest; 341 | 342 | if (stream._writev && entry && entry.next) { 343 | // Fast case, write everything using _writev() 344 | var l = state.bufferedRequestCount; 345 | var buffer = new Array(l); 346 | var holder = state.corkedRequestsFree; 347 | holder.entry = entry; 348 | 349 | var count = 0; 350 | while (entry) { 351 | buffer[count] = entry; 352 | entry = entry.next; 353 | count += 1; 354 | } 355 | 356 | doWrite(stream, state, true, state.length, buffer, '', holder.finish); 357 | 358 | // doWrite is almost always async, defer these to save a bit of time 359 | // as the hot path ends with doWrite 360 | state.pendingcb++; 361 | state.lastBufferedRequest = null; 362 | if (holder.next) { 363 | state.corkedRequestsFree = holder.next; 364 | holder.next = null; 365 | } else { 366 | state.corkedRequestsFree = new CorkedRequest(state); 367 | } 368 | } else { 369 | // Slow case, write chunks one-by-one 370 | while (entry) { 371 | var chunk = entry.chunk; 372 | var encoding = entry.encoding; 373 | var cb = entry.callback; 374 | var len = state.objectMode ? 1 : chunk.length; 375 | 376 | doWrite(stream, state, false, len, chunk, encoding, cb); 377 | entry = entry.next; 378 | // if we didn't call the onwrite immediately, then 379 | // it means that we need to wait until it does. 380 | // also, that means that the chunk and cb are currently 381 | // being processed, so move the buffer counter past them. 382 | if (state.writing) { 383 | break; 384 | } 385 | } 386 | 387 | if (entry === null) state.lastBufferedRequest = null; 388 | } 389 | 390 | state.bufferedRequestCount = 0; 391 | state.bufferedRequest = entry; 392 | state.bufferProcessing = false; 393 | } 394 | 395 | Writable.prototype._write = function (chunk, encoding, cb) { 396 | cb(new Error('not implemented')); 397 | }; 398 | 399 | Writable.prototype._writev = null; 400 | 401 | Writable.prototype.end = function (chunk, encoding, cb) { 402 | var state = this._writableState; 403 | 404 | if (typeof chunk === 'function') { 405 | cb = chunk; 406 | chunk = null; 407 | encoding = null; 408 | } else if (typeof encoding === 'function') { 409 | cb = encoding; 410 | encoding = null; 411 | } 412 | 413 | if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); 414 | 415 | // .end() fully uncorks 416 | if (state.corked) { 417 | state.corked = 1; 418 | this.uncork(); 419 | } 420 | 421 | // ignore unnecessary end() calls. 422 | if (!state.ending && !state.finished) endWritable(this, state, cb); 423 | }; 424 | 425 | function needFinish(state) { 426 | return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; 427 | } 428 | 429 | function prefinish(stream, state) { 430 | if (!state.prefinished) { 431 | state.prefinished = true; 432 | stream.emit('prefinish'); 433 | } 434 | } 435 | 436 | function finishMaybe(stream, state) { 437 | var need = needFinish(state); 438 | if (need) { 439 | if (state.pendingcb === 0) { 440 | prefinish(stream, state); 441 | state.finished = true; 442 | stream.emit('finish'); 443 | } else { 444 | prefinish(stream, state); 445 | } 446 | } 447 | return need; 448 | } 449 | 450 | function endWritable(stream, state, cb) { 451 | state.ending = true; 452 | finishMaybe(stream, state); 453 | if (cb) { 454 | if (state.finished) nextTick(cb);else stream.once('finish', cb); 455 | } 456 | state.ended = true; 457 | stream.writable = false; 458 | } 459 | 460 | // It seems a linked list but it is not 461 | // there will be only 2 of these for each stream 462 | function CorkedRequest(state) { 463 | var _this = this; 464 | 465 | this.next = null; 466 | this.entry = null; 467 | 468 | this.finish = function (err) { 469 | var entry = _this.entry; 470 | _this.entry = null; 471 | while (entry) { 472 | var cb = entry.callback; 473 | state.pendingcb--; 474 | cb(err); 475 | entry = entry.next; 476 | } 477 | if (state.corkedRequestsFree) { 478 | state.corkedRequestsFree.next = _this; 479 | } else { 480 | state.corkedRequestsFree = _this; 481 | } 482 | }; 483 | } 484 | -------------------------------------------------------------------------------- /polyfills/setimmediate.js: -------------------------------------------------------------------------------- 1 | /* 2 | MIT Licence 3 | Copyright (c) 2012 Barnesandnoble.com, llc, Donavon West, and Domenic Denicola 4 | https://github.com/YuzuJS/setImmediate/blob/f1ccbfdf09cb93aadf77c4aa749ea554503b9234/LICENSE.txt 5 | */ 6 | 7 | var nextHandle = 1; // Spec says greater than zero 8 | var tasksByHandle = {}; 9 | var currentlyRunningATask = false; 10 | var doc = global.document; 11 | var registerImmediate; 12 | 13 | export function setImmediate(callback) { 14 | // Callback can either be a function or a string 15 | if (typeof callback !== "function") { 16 | callback = new Function("" + callback); 17 | } 18 | // Copy function arguments 19 | var args = new Array(arguments.length - 1); 20 | for (var i = 0; i < args.length; i++) { 21 | args[i] = arguments[i + 1]; 22 | } 23 | // Store and register the task 24 | var task = { callback: callback, args: args }; 25 | tasksByHandle[nextHandle] = task; 26 | registerImmediate(nextHandle); 27 | return nextHandle++; 28 | } 29 | 30 | export function clearImmediate(handle) { 31 | delete tasksByHandle[handle]; 32 | } 33 | 34 | function run(task) { 35 | var callback = task.callback; 36 | var args = task.args; 37 | switch (args.length) { 38 | case 0: 39 | callback(); 40 | break; 41 | case 1: 42 | callback(args[0]); 43 | break; 44 | case 2: 45 | callback(args[0], args[1]); 46 | break; 47 | case 3: 48 | callback(args[0], args[1], args[2]); 49 | break; 50 | default: 51 | callback.apply(undefined, args); 52 | break; 53 | } 54 | } 55 | 56 | function runIfPresent(handle) { 57 | // From the spec: "Wait until any invocations of this algorithm started before this one have completed." 58 | // So if we're currently running a task, we'll need to delay this invocation. 59 | if (currentlyRunningATask) { 60 | // Delay by doing a setTimeout. setImmediate was tried instead, but in Firefox 7 it generated a 61 | // "too much recursion" error. 62 | setTimeout(runIfPresent, 0, handle); 63 | } else { 64 | var task = tasksByHandle[handle]; 65 | if (task) { 66 | currentlyRunningATask = true; 67 | try { 68 | run(task); 69 | } finally { 70 | clearImmediate(handle); 71 | currentlyRunningATask = false; 72 | } 73 | } 74 | } 75 | } 76 | 77 | function installNextTickImplementation() { 78 | registerImmediate = function(handle) { 79 | process.nextTick(function () { runIfPresent(handle); }); 80 | }; 81 | } 82 | 83 | function canUsePostMessage() { 84 | // The test against `importScripts` prevents this implementation from being installed inside a web worker, 85 | // where `global.postMessage` means something completely different and can't be used for this purpose. 86 | if (global.postMessage && !global.importScripts) { 87 | var postMessageIsAsynchronous = true; 88 | var oldOnMessage = global.onmessage; 89 | global.onmessage = function() { 90 | postMessageIsAsynchronous = false; 91 | }; 92 | global.postMessage("", "*"); 93 | global.onmessage = oldOnMessage; 94 | return postMessageIsAsynchronous; 95 | } 96 | } 97 | 98 | function installPostMessageImplementation() { 99 | // Installs an event handler on `global` for the `message` event: see 100 | // * https://developer.mozilla.org/en/DOM/window.postMessage 101 | // * http://www.whatwg.org/specs/web-apps/current-work/multipage/comms.html#crossDocumentMessages 102 | 103 | var messagePrefix = "setImmediate$" + Math.random() + "$"; 104 | var onGlobalMessage = function(event) { 105 | if (event.source === global && 106 | typeof event.data === "string" && 107 | event.data.indexOf(messagePrefix) === 0) { 108 | runIfPresent(+event.data.slice(messagePrefix.length)); 109 | } 110 | }; 111 | 112 | if (global.addEventListener) { 113 | global.addEventListener("message", onGlobalMessage, false); 114 | } else { 115 | global.attachEvent("onmessage", onGlobalMessage); 116 | } 117 | 118 | registerImmediate = function(handle) { 119 | global.postMessage(messagePrefix + handle, "*"); 120 | }; 121 | } 122 | 123 | function installMessageChannelImplementation() { 124 | var channel = new MessageChannel(); 125 | channel.port1.onmessage = function(event) { 126 | var handle = event.data; 127 | runIfPresent(handle); 128 | }; 129 | 130 | registerImmediate = function(handle) { 131 | channel.port2.postMessage(handle); 132 | }; 133 | } 134 | 135 | function installReadyStateChangeImplementation() { 136 | var html = doc.documentElement; 137 | registerImmediate = function(handle) { 138 | // Create a